repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
gurbuzali/hazelcast-jet | hazelcast-jet-sql/src/test/java/com/hazelcast/jet/sql/impl/connector/file/MetadataResolversTest.java | 4211 | /*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.jet.sql.impl.connector.file;
import com.google.common.collect.ImmutableMap;
import com.hazelcast.jet.sql.impl.schema.MappingField;
import com.hazelcast.sql.impl.QueryException;
import com.hazelcast.sql.impl.type.QueryDataType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
import java.util.Map;
import static com.hazelcast.jet.sql.impl.connector.SqlConnector.OPTION_FORMAT;
import static com.hazelcast.jet.sql.impl.connector.file.FileSqlConnector.OPTION_GLOB;
import static com.hazelcast.jet.sql.impl.connector.file.FileSqlConnector.OPTION_PATH;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.BDDMockito.given;
@RunWith(MockitoJUnitRunner.class)
public class MetadataResolversTest {
private static final String FORMAT = "some-format";
private MetadataResolvers resolvers;
@Mock
private MetadataResolver resolver;
@Mock
private Metadata metadata;
@Before
public void setUp() {
given(resolver.supportedFormat()).willReturn(FORMAT);
resolvers = new MetadataResolvers(resolver);
}
@Test
public void when_formatIsMissing_then_throws() {
assertThatThrownBy(() -> resolvers.resolveAndValidateFields(emptyList(), emptyMap()))
.isInstanceOf(QueryException.class)
.hasMessageContaining("Missing 'format");
}
@Test
public void when_pathIsMissing_then_throws() {
assertThatThrownBy(() -> resolvers.resolveAndValidateFields(emptyList(), singletonMap(OPTION_FORMAT, FORMAT)))
.isInstanceOf(QueryException.class)
.hasMessageContaining("Missing 'path");
}
@Test
public void when_formatIsNotSupported_then_throws() {
assertThatThrownBy(() -> resolvers.resolveAndValidateFields(
emptyList(),
ImmutableMap.of(OPTION_FORMAT, "some-other-format", OPTION_PATH, "/path")
)).isInstanceOf(QueryException.class)
.hasMessageContaining("Unsupported serialization format");
}
@Test
public void test_resolveAndValidateFields() {
// given
Map<String, String> options = ImmutableMap.of(OPTION_FORMAT, FORMAT, OPTION_PATH, "/path", OPTION_GLOB, "*");
given(resolver.resolveAndValidateFields(emptyList(), options))
.willReturn(singletonList(new MappingField("field", QueryDataType.VARCHAR)));
// when
List<MappingField> resolvedFields = resolvers.resolveAndValidateFields(emptyList(), options);
// then
assertThat(resolvedFields).containsOnly(new MappingField("field", QueryDataType.VARCHAR));
}
@Test
public void test_resolveMetadata() {
// given
List<MappingField> resolvedFields = singletonList(new MappingField("field", QueryDataType.VARCHAR));
Map<String, String> options = ImmutableMap.of(OPTION_FORMAT, FORMAT, OPTION_PATH, "/path", OPTION_GLOB, "*");
given(resolver.resolveMetadata(resolvedFields, options)).willReturn(metadata);
// when
Metadata metadata = resolvers.resolveMetadata(resolvedFields, options);
// then
assertThat(metadata).isNotNull();
}
}
| apache-2.0 |
nbudzyn/federkiel | src/main/java/de/nb/federkiel/feature/StringFeatureType.java | 744 | package de.nb.federkiel.feature;
import com.google.common.collect.ImmutableSet;
import de.nb.federkiel.interfaces.IFeatureType;
import de.nb.federkiel.interfaces.IFeatureValue;
/**
* A feature type for string feature values.
*
* @author nbudzyn
*/
public class StringFeatureType implements IFeatureType {
@Override
public ImmutableSet<IFeatureValue> getAllPossibleValues() {
return null;
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return true;
}
}
| apache-2.0 |
sunleepy/webx_activiti | src/main/java/com/alibaba/webx/activiti/app1/module/screen/simple/SayHiImage.java | 2147 | /*
* Copyright (c) 2002-2012 Alibaba Group Holding Limited.
* 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.alibaba.webx.activiti.app1.module.screen.simple;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.citrus.service.requestcontext.buffered.BufferedRequestContext;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 动态创建二进制图片。
*
* @author Michael Zhou
*/
public class SayHiImage {
@Autowired
private HttpServletResponse response;
@Autowired
private BufferedRequestContext brc;
public void execute() throws Exception {
// 为了节省内存,关闭buffering。
brc.setBuffering(false);
// 只要设置了正确的content type,你就可以输出任何文本或二进制的内容:
// HTML、JSON、JavaScript、JPG、PDF、EXCEL等。
response.setContentType("image/jpeg");
OutputStream out = response.getOutputStream();
writeImage(out);
}
private void writeImage(OutputStream out) throws IOException {
BufferedImage img = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.setPaint(Color.red);
g2d.setFont(new Font("Serif", Font.BOLD, 36));
g2d.drawString("Hi there, how are you doing today?", 5, g2d.getFontMetrics().getHeight());
g2d.dispose();
ImageIO.write(img, "jpg", out);
}
}
| apache-2.0 |
proliming/commons | commons-concurrent/src/main/java/com/proliming/commons/concurrent/TaskExecutor.java | 1435 | /*
* Copyright (c) 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.proliming.commons.concurrent;
import java.util.concurrent.Executor;
/**
* <p/>
* Simple task executor interface that abstracts the execution
* of a {@link Runnable}.
* <p>Implementations can use all sorts of different execution strategies,
* such as: synchronous, asynchronous, using a thread pool, and more.
*/
public interface TaskExecutor extends Executor {
/**
* Execute the given {@code task}.
* <p>The call might return immediately if the implementation uses
* an asynchronous execution strategy, or might block in the case
* of synchronous execution.
*
* @param task the {@code Runnable} to execute (never {@code null})
*
* @throws TaskRejectedException if the given task was not accepted
*/
@Override
void execute(Runnable task);
}
| apache-2.0 |
dump247/aws-sdk-java | aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/transform/BranchInfoJsonUnmarshaller.java | 2986 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.codecommit.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.codecommit.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* BranchInfo JSON Unmarshaller
*/
public class BranchInfoJsonUnmarshaller implements
Unmarshaller<BranchInfo, JsonUnmarshallerContext> {
public BranchInfo unmarshall(JsonUnmarshallerContext context)
throws Exception {
BranchInfo branchInfo = new BranchInfo();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("branchName", targetDepth)) {
context.nextToken();
branchInfo.setBranchName(StringJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("commitId", targetDepth)) {
context.nextToken();
branchInfo.setCommitId(StringJsonUnmarshaller.getInstance()
.unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return branchInfo;
}
private static BranchInfoJsonUnmarshaller instance;
public static BranchInfoJsonUnmarshaller getInstance() {
if (instance == null)
instance = new BranchInfoJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
mchaston/OakFunds | src/org/chaston/oakfunds/ledger/ui/AccountTransactionCreateServlet.java | 4057 | /*
* Copyright 2014 Miles Chaston
*
* 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.chaston.oakfunds.ledger.ui;
import com.google.inject.Inject;
import org.chaston.oakfunds.ledger.Account;
import org.chaston.oakfunds.ledger.AccountTransaction;
import org.chaston.oakfunds.ledger.LedgerManager;
import org.chaston.oakfunds.storage.StorageException;
import org.chaston.oakfunds.util.JSONUtils;
import org.chaston.oakfunds.util.ParameterHandler;
import org.chaston.oakfunds.util.RequestHandler;
import org.joda.time.Instant;
import org.json.simple.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* TODO(mchaston): write JavaDocs
*/
class AccountTransactionCreateServlet extends HttpServlet {
static final String URI_REGEX = "/ledger/account/([0-9]+)/create_transaction";
private static final Pattern URI_PATTERN = Pattern.compile(URI_REGEX);
private static final ParameterHandler<Instant> PARAMETER_DATE =
ParameterHandler.instantParameter("date")
.required("A date must be supplied.")
.build();
private static final ParameterHandler<BigDecimal> PARAMETER_AMOUNT =
ParameterHandler.bigDecimalParameter("amount")
.required("An amount must be supplied.")
.build();
private static final ParameterHandler<String> PARAMETER_COMMENT =
ParameterHandler.stringParameter("comment")
.build();
private final RequestHandler requestHandler;
private final LedgerManager ledgerManager;
@Inject
AccountTransactionCreateServlet(RequestHandler requestHandler,
LedgerManager ledgerManager) {
this.requestHandler = requestHandler;
this.ledgerManager = ledgerManager;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Read the requestURI to determine the account to add a transaction to.
Matcher matcher = URI_PATTERN.matcher(request.getRequestURI());
if (!matcher.matches()) {
// This should never happen as the servlet is only invoked on a match of the same pattern.
String errorMessage = "Unexpected match failure on: " + request.getRequestURI();
log(errorMessage);
response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMessage);
return;
}
final int accountId = Integer.parseInt(matcher.group(1));
final JSONObject jsonRequest = JSONUtils.readRequest(request, "create account transaction");
AccountTransaction bankAccount =
requestHandler.handleTransaction(request, response,
new RequestHandler.Action<AccountTransaction>() {
@Override
public AccountTransaction doAction(HttpServletRequest request)
throws StorageException, ServletException {
Account account =
ledgerManager.getAccount(accountId);
return ledgerManager.recordTransaction(account,
PARAMETER_DATE.parse(jsonRequest),
PARAMETER_AMOUNT.parse(jsonRequest),
PARAMETER_COMMENT.parse(jsonRequest));
}
});
// Write result to response.
response.setContentType("application/json");
JSONUtils.writeJSONString(response.getWriter(), bankAccount);
}
}
| apache-2.0 |
lvweiwolf/poi-3.16 | src/testcases/org/apache/poi/poifs/crypt/AllEncryptionTests.java | 1303 | /* ====================================================================
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.poi.poifs.crypt;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
* Collects all tests for package <tt>org.apache.poi.poifs.crypt</tt>.
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestBiff8DecryptingStream.class,
TestCipherAlgorithm.class,
TestXorEncryption.class
})
public final class AllEncryptionTests {
}
| apache-2.0 |
xiaobaiAndroid/jianxin | app/src/main/java/com/bzf/jianxin/service/ContactStateDisposeManager.java | 3713 | package com.bzf.jianxin.service;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v7.app.NotificationCompat;
import com.bzf.jianxin.R;
import com.bzf.jianxin.commonutils.HuanXinTool;
import com.hyphenate.exceptions.HyphenateException;
/**
* 好友状态处理的Manger
* com.bzf.jianxin.service
* Author: baizhengfu
* Email:709889312@qq.com
*/
public class ContactStateDisposeManager {
private static final String TAG = ContactStateDisposeManager.class.getName();
private static ContactStateDisposeManager instance;
private static Context mContext;
private ContactStateDisposeManager(){}
public static ContactStateDisposeManager getInstance(Context context){
if(instance==null){
instance = new ContactStateDisposeManager();
mContext = context;
}
return instance;
}
/**
* 处理添加了的联系人
* @param username
*/
public void disposeAddContact(String username) {
}
/**
* 处理 删除了联系人
* @param username
*/
public void disposeDeleteContact(String username) {
}
/**
* 处理收到好友邀请时
* @param username 发起加为好友用户的名称
* @param reason 对方发起好友邀请时发出的文字性描述
*/
public void disposeContactInvited(String username, String reason) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
builder.setContentTitle("好友请求");
builder.setContentText(username+"请求添加你为好友,理由:"+reason);
builder.setSmallIcon(R.mipmap.icon);
builder.setAutoCancel(true);
builder.setWhen(System.currentTimeMillis());
Notification notification = builder.build();
NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(2,notification);
try {
HuanXinTool.acceptInvitation(username);
} catch (HyphenateException e) {
e.printStackTrace();
}
}
/**
* 处理 好友请求被同意
* @param username
*/
public void disposeAcceptedInvited(String username) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
builder.setSmallIcon(R.mipmap.icon);
builder.setContentTitle("好友请求反馈");
builder.setContentText(username+"同意了你的好友请求");
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(true);
builder.setVisibility(Notification.VISIBILITY_PUBLIC);
Notification notification = builder.build();
NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(3,notification);
}
/**
* 处理 好友请求被拒绝
* @param username
*/
public void disposeDeclinedInvited(String username) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
builder.setSmallIcon(R.mipmap.icon);
builder.setContentTitle("好友请求反馈");
builder.setContentText(username+"拒绝了你的好友请求");
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(true);
//在任何情况下都会显示
builder.setVisibility(Notification.VISIBILITY_PUBLIC);
Notification notification = builder.build();
NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(3,notification);
}
}
| apache-2.0 |
JavaSaBr/jME3-SpaceShift-Editor | src/main/java/com/ss/editor/model/undo/impl/ChangeControlsOperation.java | 2358 | package com.ss.editor.model.undo.impl;
import com.jme3.scene.Node;
import com.jme3.scene.control.Control;
import com.ss.editor.annotation.FxThread;
import com.ss.editor.annotation.JmeThread;
import com.ss.editor.model.undo.editor.ModelChangeConsumer;
import com.ss.rlib.common.util.array.Array;
import org.jetbrains.annotations.NotNull;
/**
* The implementation of {@link AbstractEditorOperation} to chane {@link com.jme3.scene.control.AbstractControl} in {@link Node}.
*
* @author JavaSaBr.
*/
public class ChangeControlsOperation extends AbstractEditorOperation<ModelChangeConsumer> {
/**
* The controls to change.
*/
@NotNull
private final Array<Control> controls;
public ChangeControlsOperation(@NotNull final Array<Control> controls) {
this.controls = controls;
}
@Override
@JmeThread
protected void redoImpl(@NotNull final ModelChangeConsumer editor) {
EXECUTOR_MANAGER.addJmeTask(() -> {
for (final Control control : controls) {
redoChange(control);
}
EXECUTOR_MANAGER.addFxTask(() -> {
controls.forEach(editor, (control, consumer) ->
consumer.notifyFxChangeProperty(control, getPropertyName()));
});
});
}
/**
* Apply new changes to the control.
*
* @param control the control.
*/
@JmeThread
protected void redoChange(@NotNull final Control control) {
}
@Override
@JmeThread
protected void undoImpl(@NotNull final ModelChangeConsumer editor) {
EXECUTOR_MANAGER.addJmeTask(() -> {
for (final Control control : controls) {
undoChange(control);
}
EXECUTOR_MANAGER.addFxTask(() -> {
controls.forEach(editor, (control, consumer) ->
consumer.notifyFxChangeProperty(control, getPropertyName()));
});
});
}
/**
* Revert changes for the control.
*
* @param control the control.
*/
@JmeThread
protected void undoChange(@NotNull final Control control) {
}
/**
* Get the property name.
*
* @return the property name.
*/
@FxThread
protected @NotNull String getPropertyName() {
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
ox-it/cucm-http-api | src/main/java/com/cisco/axl/api/_8/RH323Phone.java | 40888 |
package com.cisco.axl.api._8;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for RH323Phone complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RH323Phone">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="name" type="{http://www.cisco.com/AXL/API/8.0}UniqueString128" minOccurs="0"/>
* <element name="description" type="{http://www.cisco.com/AXL/API/8.0}String128" minOccurs="0"/>
* <element name="product" type="{http://www.cisco.com/AXL/API/8.0}XProduct" minOccurs="0"/>
* <element name="model" type="{http://www.cisco.com/AXL/API/8.0}XModel" minOccurs="0"/>
* <element name="class" type="{http://www.cisco.com/AXL/API/8.0}XClass" minOccurs="0"/>
* <element name="protocol" type="{http://www.cisco.com/AXL/API/8.0}XDeviceProtocol" minOccurs="0"/>
* <element name="protocolSide" type="{http://www.cisco.com/AXL/API/8.0}XProtocolSide" minOccurs="0"/>
* <element name="callingSearchSpaceName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="devicePoolName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="commonDeviceConfigName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="commonPhoneConfigName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="locationName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="mediaResourceListName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="automatedAlternateRoutingCssName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="aarNeighborhoodName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="traceFlag" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="mlppDomainId" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="useTrustedRelayPoint" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/>
* <element name="retryVideoCallAsAudio" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="remoteDevice" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="cgpnTransformationCssName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="useDevicePoolCgpnTransformCss" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="geoLocationName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="alwaysUsePrimeLine" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/>
* <element name="alwaysUsePrimeLineForVoiceMessage" type="{http://www.cisco.com/AXL/API/8.0}XStatus" minOccurs="0"/>
* <element name="srtpAllowed" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="unattendedPort" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="subscribeCallingSearchSpaceName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="waitForFarEndH245TerminalSet" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="mtpRequired" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="mtpPreferredCodec" type="{http://www.cisco.com/AXL/API/8.0}XSIPCodec" minOccurs="0"/>
* <element name="callerIdDn" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
* <element name="callingPartySelection" type="{http://www.cisco.com/AXL/API/8.0}XCallingPartySelection" minOccurs="0"/>
* <element name="callingLineIdPresentation" type="{http://www.cisco.com/AXL/API/8.0}XPresentationBit" minOccurs="0"/>
* <element name="displayIEDelivery" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="redirectOutboundNumberIe" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="redirectInboundNumberIe" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="presenceGroupName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="hlogStatus" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="ownerUserName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="signalingPort" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="gateKeeperInfo" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="gateKeeperName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="e164" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
* <element name="technologyPrefix" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
* <element name="zone" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="lines" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice minOccurs="0">
* <element name="line" type="{http://www.cisco.com/AXL/API/8.0}RH323Line" maxOccurs="unbounded" minOccurs="0"/>
* <element name="lineIdentifier" type="{http://www.cisco.com/AXL/API/8.0}RNumplanIdentifier" maxOccurs="unbounded" minOccurs="0"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="ignorePresentationIndicators" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* </sequence>
* <attribute name="ctiid" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" />
* <attribute name="uuid" type="{http://www.cisco.com/AXL/API/8.0}XUUID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RH323Phone", propOrder = {
"name",
"description",
"product",
"model",
"clazz",
"protocol",
"protocolSide",
"callingSearchSpaceName",
"devicePoolName",
"commonDeviceConfigName",
"commonPhoneConfigName",
"locationName",
"mediaResourceListName",
"automatedAlternateRoutingCssName",
"aarNeighborhoodName",
"traceFlag",
"mlppDomainId",
"useTrustedRelayPoint",
"retryVideoCallAsAudio",
"remoteDevice",
"cgpnTransformationCssName",
"useDevicePoolCgpnTransformCss",
"geoLocationName",
"alwaysUsePrimeLine",
"alwaysUsePrimeLineForVoiceMessage",
"srtpAllowed",
"unattendedPort",
"subscribeCallingSearchSpaceName",
"waitForFarEndH245TerminalSet",
"mtpRequired",
"mtpPreferredCodec",
"callerIdDn",
"callingPartySelection",
"callingLineIdPresentation",
"displayIEDelivery",
"redirectOutboundNumberIe",
"redirectInboundNumberIe",
"presenceGroupName",
"hlogStatus",
"ownerUserName",
"signalingPort",
"gateKeeperInfo",
"lines",
"ignorePresentationIndicators"
})
public class RH323Phone {
protected String name;
protected String description;
protected String product;
protected String model;
@XmlElement(name = "class")
protected String clazz;
protected String protocol;
protected String protocolSide;
protected XFkType callingSearchSpaceName;
protected XFkType devicePoolName;
protected XFkType commonDeviceConfigName;
protected XFkType commonPhoneConfigName;
protected XFkType locationName;
protected XFkType mediaResourceListName;
protected XFkType automatedAlternateRoutingCssName;
protected XFkType aarNeighborhoodName;
protected String traceFlag;
protected Integer mlppDomainId;
protected String useTrustedRelayPoint;
protected String retryVideoCallAsAudio;
protected String remoteDevice;
protected XFkType cgpnTransformationCssName;
protected String useDevicePoolCgpnTransformCss;
protected XFkType geoLocationName;
protected String alwaysUsePrimeLine;
protected String alwaysUsePrimeLineForVoiceMessage;
protected String srtpAllowed;
protected String unattendedPort;
protected XFkType subscribeCallingSearchSpaceName;
protected String waitForFarEndH245TerminalSet;
protected String mtpRequired;
protected String mtpPreferredCodec;
protected String callerIdDn;
protected String callingPartySelection;
protected String callingLineIdPresentation;
protected String displayIEDelivery;
protected String redirectOutboundNumberIe;
protected String redirectInboundNumberIe;
protected XFkType presenceGroupName;
protected String hlogStatus;
protected XFkType ownerUserName;
protected String signalingPort;
protected RH323Phone.GateKeeperInfo gateKeeperInfo;
protected RH323Phone.Lines lines;
protected String ignorePresentationIndicators;
@XmlAttribute
@XmlSchemaType(name = "positiveInteger")
protected BigInteger ctiid;
@XmlAttribute
protected String uuid;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the product property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProduct() {
return product;
}
/**
* Sets the value of the product property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProduct(String value) {
this.product = value;
}
/**
* Gets the value of the model property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getModel() {
return model;
}
/**
* Sets the value of the model property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setModel(String value) {
this.model = value;
}
/**
* Gets the value of the clazz property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClazz() {
return clazz;
}
/**
* Sets the value of the clazz property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClazz(String value) {
this.clazz = value;
}
/**
* Gets the value of the protocol property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProtocol() {
return protocol;
}
/**
* Sets the value of the protocol property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProtocol(String value) {
this.protocol = value;
}
/**
* Gets the value of the protocolSide property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProtocolSide() {
return protocolSide;
}
/**
* Sets the value of the protocolSide property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProtocolSide(String value) {
this.protocolSide = value;
}
/**
* Gets the value of the callingSearchSpaceName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getCallingSearchSpaceName() {
return callingSearchSpaceName;
}
/**
* Sets the value of the callingSearchSpaceName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setCallingSearchSpaceName(XFkType value) {
this.callingSearchSpaceName = value;
}
/**
* Gets the value of the devicePoolName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getDevicePoolName() {
return devicePoolName;
}
/**
* Sets the value of the devicePoolName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setDevicePoolName(XFkType value) {
this.devicePoolName = value;
}
/**
* Gets the value of the commonDeviceConfigName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getCommonDeviceConfigName() {
return commonDeviceConfigName;
}
/**
* Sets the value of the commonDeviceConfigName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setCommonDeviceConfigName(XFkType value) {
this.commonDeviceConfigName = value;
}
/**
* Gets the value of the commonPhoneConfigName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getCommonPhoneConfigName() {
return commonPhoneConfigName;
}
/**
* Sets the value of the commonPhoneConfigName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setCommonPhoneConfigName(XFkType value) {
this.commonPhoneConfigName = value;
}
/**
* Gets the value of the locationName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getLocationName() {
return locationName;
}
/**
* Sets the value of the locationName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setLocationName(XFkType value) {
this.locationName = value;
}
/**
* Gets the value of the mediaResourceListName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getMediaResourceListName() {
return mediaResourceListName;
}
/**
* Sets the value of the mediaResourceListName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setMediaResourceListName(XFkType value) {
this.mediaResourceListName = value;
}
/**
* Gets the value of the automatedAlternateRoutingCssName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getAutomatedAlternateRoutingCssName() {
return automatedAlternateRoutingCssName;
}
/**
* Sets the value of the automatedAlternateRoutingCssName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setAutomatedAlternateRoutingCssName(XFkType value) {
this.automatedAlternateRoutingCssName = value;
}
/**
* Gets the value of the aarNeighborhoodName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getAarNeighborhoodName() {
return aarNeighborhoodName;
}
/**
* Sets the value of the aarNeighborhoodName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setAarNeighborhoodName(XFkType value) {
this.aarNeighborhoodName = value;
}
/**
* Gets the value of the traceFlag property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTraceFlag() {
return traceFlag;
}
/**
* Sets the value of the traceFlag property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTraceFlag(String value) {
this.traceFlag = value;
}
/**
* Gets the value of the mlppDomainId property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getMlppDomainId() {
return mlppDomainId;
}
/**
* Sets the value of the mlppDomainId property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setMlppDomainId(Integer value) {
this.mlppDomainId = value;
}
/**
* Gets the value of the useTrustedRelayPoint property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUseTrustedRelayPoint() {
return useTrustedRelayPoint;
}
/**
* Sets the value of the useTrustedRelayPoint property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUseTrustedRelayPoint(String value) {
this.useTrustedRelayPoint = value;
}
/**
* Gets the value of the retryVideoCallAsAudio property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRetryVideoCallAsAudio() {
return retryVideoCallAsAudio;
}
/**
* Sets the value of the retryVideoCallAsAudio property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRetryVideoCallAsAudio(String value) {
this.retryVideoCallAsAudio = value;
}
/**
* Gets the value of the remoteDevice property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemoteDevice() {
return remoteDevice;
}
/**
* Sets the value of the remoteDevice property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemoteDevice(String value) {
this.remoteDevice = value;
}
/**
* Gets the value of the cgpnTransformationCssName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getCgpnTransformationCssName() {
return cgpnTransformationCssName;
}
/**
* Sets the value of the cgpnTransformationCssName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setCgpnTransformationCssName(XFkType value) {
this.cgpnTransformationCssName = value;
}
/**
* Gets the value of the useDevicePoolCgpnTransformCss property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUseDevicePoolCgpnTransformCss() {
return useDevicePoolCgpnTransformCss;
}
/**
* Sets the value of the useDevicePoolCgpnTransformCss property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUseDevicePoolCgpnTransformCss(String value) {
this.useDevicePoolCgpnTransformCss = value;
}
/**
* Gets the value of the geoLocationName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getGeoLocationName() {
return geoLocationName;
}
/**
* Sets the value of the geoLocationName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setGeoLocationName(XFkType value) {
this.geoLocationName = value;
}
/**
* Gets the value of the alwaysUsePrimeLine property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlwaysUsePrimeLine() {
return alwaysUsePrimeLine;
}
/**
* Sets the value of the alwaysUsePrimeLine property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlwaysUsePrimeLine(String value) {
this.alwaysUsePrimeLine = value;
}
/**
* Gets the value of the alwaysUsePrimeLineForVoiceMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlwaysUsePrimeLineForVoiceMessage() {
return alwaysUsePrimeLineForVoiceMessage;
}
/**
* Sets the value of the alwaysUsePrimeLineForVoiceMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlwaysUsePrimeLineForVoiceMessage(String value) {
this.alwaysUsePrimeLineForVoiceMessage = value;
}
/**
* Gets the value of the srtpAllowed property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSrtpAllowed() {
return srtpAllowed;
}
/**
* Sets the value of the srtpAllowed property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSrtpAllowed(String value) {
this.srtpAllowed = value;
}
/**
* Gets the value of the unattendedPort property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUnattendedPort() {
return unattendedPort;
}
/**
* Sets the value of the unattendedPort property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUnattendedPort(String value) {
this.unattendedPort = value;
}
/**
* Gets the value of the subscribeCallingSearchSpaceName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getSubscribeCallingSearchSpaceName() {
return subscribeCallingSearchSpaceName;
}
/**
* Sets the value of the subscribeCallingSearchSpaceName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setSubscribeCallingSearchSpaceName(XFkType value) {
this.subscribeCallingSearchSpaceName = value;
}
/**
* Gets the value of the waitForFarEndH245TerminalSet property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWaitForFarEndH245TerminalSet() {
return waitForFarEndH245TerminalSet;
}
/**
* Sets the value of the waitForFarEndH245TerminalSet property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWaitForFarEndH245TerminalSet(String value) {
this.waitForFarEndH245TerminalSet = value;
}
/**
* Gets the value of the mtpRequired property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMtpRequired() {
return mtpRequired;
}
/**
* Sets the value of the mtpRequired property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMtpRequired(String value) {
this.mtpRequired = value;
}
/**
* Gets the value of the mtpPreferredCodec property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMtpPreferredCodec() {
return mtpPreferredCodec;
}
/**
* Sets the value of the mtpPreferredCodec property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMtpPreferredCodec(String value) {
this.mtpPreferredCodec = value;
}
/**
* Gets the value of the callerIdDn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCallerIdDn() {
return callerIdDn;
}
/**
* Sets the value of the callerIdDn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCallerIdDn(String value) {
this.callerIdDn = value;
}
/**
* Gets the value of the callingPartySelection property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCallingPartySelection() {
return callingPartySelection;
}
/**
* Sets the value of the callingPartySelection property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCallingPartySelection(String value) {
this.callingPartySelection = value;
}
/**
* Gets the value of the callingLineIdPresentation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCallingLineIdPresentation() {
return callingLineIdPresentation;
}
/**
* Sets the value of the callingLineIdPresentation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCallingLineIdPresentation(String value) {
this.callingLineIdPresentation = value;
}
/**
* Gets the value of the displayIEDelivery property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDisplayIEDelivery() {
return displayIEDelivery;
}
/**
* Sets the value of the displayIEDelivery property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDisplayIEDelivery(String value) {
this.displayIEDelivery = value;
}
/**
* Gets the value of the redirectOutboundNumberIe property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRedirectOutboundNumberIe() {
return redirectOutboundNumberIe;
}
/**
* Sets the value of the redirectOutboundNumberIe property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRedirectOutboundNumberIe(String value) {
this.redirectOutboundNumberIe = value;
}
/**
* Gets the value of the redirectInboundNumberIe property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRedirectInboundNumberIe() {
return redirectInboundNumberIe;
}
/**
* Sets the value of the redirectInboundNumberIe property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRedirectInboundNumberIe(String value) {
this.redirectInboundNumberIe = value;
}
/**
* Gets the value of the presenceGroupName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getPresenceGroupName() {
return presenceGroupName;
}
/**
* Sets the value of the presenceGroupName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setPresenceGroupName(XFkType value) {
this.presenceGroupName = value;
}
/**
* Gets the value of the hlogStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHlogStatus() {
return hlogStatus;
}
/**
* Sets the value of the hlogStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHlogStatus(String value) {
this.hlogStatus = value;
}
/**
* Gets the value of the ownerUserName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getOwnerUserName() {
return ownerUserName;
}
/**
* Sets the value of the ownerUserName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setOwnerUserName(XFkType value) {
this.ownerUserName = value;
}
/**
* Gets the value of the signalingPort property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSignalingPort() {
return signalingPort;
}
/**
* Sets the value of the signalingPort property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSignalingPort(String value) {
this.signalingPort = value;
}
/**
* Gets the value of the gateKeeperInfo property.
*
* @return
* possible object is
* {@link RH323Phone.GateKeeperInfo }
*
*/
public RH323Phone.GateKeeperInfo getGateKeeperInfo() {
return gateKeeperInfo;
}
/**
* Sets the value of the gateKeeperInfo property.
*
* @param value
* allowed object is
* {@link RH323Phone.GateKeeperInfo }
*
*/
public void setGateKeeperInfo(RH323Phone.GateKeeperInfo value) {
this.gateKeeperInfo = value;
}
/**
* Gets the value of the lines property.
*
* @return
* possible object is
* {@link RH323Phone.Lines }
*
*/
public RH323Phone.Lines getLines() {
return lines;
}
/**
* Sets the value of the lines property.
*
* @param value
* allowed object is
* {@link RH323Phone.Lines }
*
*/
public void setLines(RH323Phone.Lines value) {
this.lines = value;
}
/**
* Gets the value of the ignorePresentationIndicators property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIgnorePresentationIndicators() {
return ignorePresentationIndicators;
}
/**
* Sets the value of the ignorePresentationIndicators property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIgnorePresentationIndicators(String value) {
this.ignorePresentationIndicators = value;
}
/**
* Gets the value of the ctiid property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getCtiid() {
return ctiid;
}
/**
* Sets the value of the ctiid property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setCtiid(BigInteger value) {
this.ctiid = value;
}
/**
* Gets the value of the uuid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuid(String value) {
this.uuid = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="gateKeeperName" type="{http://www.cisco.com/AXL/API/8.0}XFkType" minOccurs="0"/>
* <element name="e164" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
* <element name="technologyPrefix" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
* <element name="zone" type="{http://www.cisco.com/AXL/API/8.0}String50" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"gateKeeperName",
"e164",
"technologyPrefix",
"zone"
})
public static class GateKeeperInfo {
protected XFkType gateKeeperName;
protected String e164;
protected String technologyPrefix;
protected String zone;
/**
* Gets the value of the gateKeeperName property.
*
* @return
* possible object is
* {@link XFkType }
*
*/
public XFkType getGateKeeperName() {
return gateKeeperName;
}
/**
* Sets the value of the gateKeeperName property.
*
* @param value
* allowed object is
* {@link XFkType }
*
*/
public void setGateKeeperName(XFkType value) {
this.gateKeeperName = value;
}
/**
* Gets the value of the e164 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getE164() {
return e164;
}
/**
* Sets the value of the e164 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setE164(String value) {
this.e164 = value;
}
/**
* Gets the value of the technologyPrefix property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTechnologyPrefix() {
return technologyPrefix;
}
/**
* Sets the value of the technologyPrefix property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTechnologyPrefix(String value) {
this.technologyPrefix = value;
}
/**
* Gets the value of the zone property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getZone() {
return zone;
}
/**
* Sets the value of the zone property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setZone(String value) {
this.zone = value;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice minOccurs="0">
* <element name="line" type="{http://www.cisco.com/AXL/API/8.0}RH323Line" maxOccurs="unbounded" minOccurs="0"/>
* <element name="lineIdentifier" type="{http://www.cisco.com/AXL/API/8.0}RNumplanIdentifier" maxOccurs="unbounded" minOccurs="0"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"line",
"lineIdentifier"
})
public static class Lines {
protected List<RH323Line> line;
protected List<RNumplanIdentifier> lineIdentifier;
/**
* Gets the value of the line property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the line property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLine().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link RH323Line }
*
*
*/
public List<RH323Line> getLine() {
if (line == null) {
line = new ArrayList<RH323Line>();
}
return this.line;
}
/**
* Gets the value of the lineIdentifier property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineIdentifier property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineIdentifier().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link RNumplanIdentifier }
*
*
*/
public List<RNumplanIdentifier> getLineIdentifier() {
if (lineIdentifier == null) {
lineIdentifier = new ArrayList<RNumplanIdentifier>();
}
return this.lineIdentifier;
}
}
}
| apache-2.0 |
amedia/meteo | meteo-jaxb/src/main/java/no/api/meteo/jaxb/nowcast/v0_9/Pressure.java | 3107 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.02.17 at 03:24:38 PM CET
//
package no.api.meteo.jaxb.nowcast.v0_9;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for pressure complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="pressure">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="unit" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="value" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}decimal">
* <minInclusive value="0"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "pressure")
public class Pressure {
@XmlAttribute(name = "unit", required = true)
protected String unit;
@XmlAttribute(name = "value", required = true)
protected BigDecimal value;
@XmlAttribute(name = "id")
protected String id;
/**
* Gets the value of the unit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUnit() {
return unit;
}
/**
* Sets the value of the unit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUnit(String value) {
this.unit = value;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
}
| apache-2.0 |
square/keywhiz | server/src/test/java/keywhiz/service/resources/SecretsDeliveryResourceTest.java | 3604 | /*
* Copyright (C) 2015 Square, 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 keywhiz.service.resources;
import com.google.common.collect.ImmutableSet;
import java.util.Base64;
import java.util.List;
import keywhiz.api.ApiDate;
import keywhiz.api.SecretDeliveryResponse;
import keywhiz.api.model.Client;
import keywhiz.api.model.SanitizedSecret;
import keywhiz.api.model.Secret;
import keywhiz.service.daos.AclDAO;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
public class SecretsDeliveryResourceTest {
private static final ApiDate NOW = ApiDate.now();
@Rule public MockitoRule mockito = MockitoJUnit.rule();
@Mock AclDAO aclDAO;
SecretsDeliveryResource secretsDeliveryResource;
Secret firstSecret = new Secret(0, "first_secret_name", null, null,
() -> Base64.getEncoder().encodeToString("first_secret_contents".getBytes(UTF_8)), "checksum", NOW, null, NOW, null, null,
null, null, 0, 1L, NOW, null);
SanitizedSecret sanitizedFirstSecret = SanitizedSecret.fromSecret(firstSecret);
Secret secondSecret = new Secret(1, "second_secret_name", null, null,
() -> Base64.getEncoder().encodeToString("second_secret_contents".getBytes(UTF_8)), "checksum", NOW, null, NOW, null, null,
null, null, 0, 1L, NOW, null);
SanitizedSecret sanitizedSecondSecret = SanitizedSecret.fromSecret(secondSecret);
Client client;
@Before public void setUp() {
secretsDeliveryResource = new SecretsDeliveryResource(aclDAO);
client = new Client(0, "client_name", null, null, null, null, null, null, null, null, false, false
);
}
@Test public void returnsEmptyJsonArrayWhenUserHasNoSecrets() throws Exception {
when(aclDAO.getSanitizedSecretsFor(client)).thenReturn(ImmutableSet.of());
List<SecretDeliveryResponse> secrets = secretsDeliveryResource.getSecrets(client);
assertThat(secrets).isEmpty();
}
@Test public void returnsJsonArrayWhenUserHasOneSecret() throws Exception {
when(aclDAO.getSanitizedSecretsFor(client)).thenReturn(ImmutableSet.of(sanitizedFirstSecret));
List<SecretDeliveryResponse> secrets = secretsDeliveryResource.getSecrets(client);
assertThat(secrets).containsOnly(SecretDeliveryResponse.fromSanitizedSecret(
SanitizedSecret.fromSecret(firstSecret)));
}
@Test public void returnsJsonArrayWhenUserHasMultipleSecrets() throws Exception {
when(aclDAO.getSanitizedSecretsFor(client))
.thenReturn(ImmutableSet.of(sanitizedFirstSecret, sanitizedSecondSecret));
List<SecretDeliveryResponse> secrets = secretsDeliveryResource.getSecrets(client);
assertThat(secrets).containsOnly(
SecretDeliveryResponse.fromSanitizedSecret(SanitizedSecret.fromSecret(firstSecret)),
SecretDeliveryResponse.fromSanitizedSecret(SanitizedSecret.fromSecret(secondSecret)));
}
}
| apache-2.0 |
tsdl2013/COCOFramework | framework/src/main/java/com/cocosw/framework/core/BaseFragment.java | 13815 | package com.cocosw.framework.core;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.cocosw.accessory.connectivity.NetworkConnectivity;
import com.cocosw.framework.R;
import com.cocosw.framework.app.Injector;
import com.cocosw.framework.exception.CocoException;
import com.cocosw.framework.exception.ExceptionManager;
import com.cocosw.framework.loader.CocoLoader;
import com.cocosw.framework.loader.ThrowableLoader;
import com.cocosw.framework.uiquery.CocoQuery;
import com.cocosw.lifecycle.LifecycleDispatcher;
import com.cocosw.undobar.UndoBarController;
import com.cocosw.undobar.UndoBarController.UndoListener;
import java.util.List;
import butterknife.ButterKnife;
/**
* Base Fragment, all other fragments in this application should extend from this class.
*
* - Loader has been integrated in, so you could simply running async background task in pendingdata()
* - ButterKnife integrated
* - Safely launch intent
*
* Created by kai on 19/05/15.
*/
public abstract class BaseFragment<T> extends Fragment implements
DialogResultListener, CocoLoader<T>, Base.OnActivityInsetsCallback {
/**
* Loader would not be initialized by fragment.
*/
protected static final int NEVER = -1;
/**
* Loader will be initialized when fragment was created
*/
protected static final int ONCREATE = 0;
protected Context context;
protected Loader<T> loader;
protected CocoQuery q;
protected View v;
CocoDialog parentDialog;
private T items;
private boolean loaderRunning;
/**
* Check network connection
*
* @throws CocoException
*/
protected void checkNetwork() throws CocoException {
if (!NetworkConnectivity.getInstance().checkConnected()) {
throw new CocoException(getString(R.string.network_error));
}
}
public ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
public AppCompatActivity getActionBarActivity() {
return ((AppCompatActivity) getActivity());
}
/**
* Close current UI container(activity/dialog)
*/
public void finish() {
if (parentDialog != null) {
parentDialog.dismiss();
} else {
getActivity().finish();
}
}
protected SystemBarTintManager getTintManager() {
if (getActivity() instanceof Base) {
return ((Base) getActivity()).getTintManager();
}
return null;
}
/**
* run on Ui thread
*
* @param runnable
*/
protected void runOnUiThread(Runnable runnable) {
getActivity().runOnUiThread(runnable);
}
/**
* Get exception from loader if it provides one by being a
* {@link ThrowableLoader}
*
* @param loader
* @return exception or null if none provided
*/
protected Exception getException(final Loader<T> loader) {
if (loader instanceof ThrowableLoader) {
return ((ThrowableLoader<T>) loader).clearException();
} else {
return null;
}
}
public ThrowableLoader<T> getLoader() {
return (ThrowableLoader<T>) loader;
}
/**
* When the loader been initialized
*/
protected int getLoaderOn() {
return BaseFragment.NEVER;
}
public CharSequence getTitle() {
return "";
}
/**
* Is this fragment still part of an activity and usable from the UI-thread?
*
* @return true if usable on the UI-thread, false otherwise
*/
protected boolean isUsable() {
return getActivity() != null;
}
/**
* The layout file which will be inflated for this fragment
* @return layout file id
*/
public abstract int layoutId();
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LifecycleDispatcher.get().onFragmentActivityCreated(this, savedInstanceState);
if (getLoaderOn() == ONCREATE && reloadNeeded(savedInstanceState)) {
onStartLoading();
getLoaderManager().initLoader(this.hashCode(), getArguments(), this);
}
}
protected boolean reloadNeeded(final Bundle savedInstanceState) {
return true;
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LifecycleDispatcher.get().onFragmentCreated(this, savedInstanceState);
context = getActivity();
setHasOptionsMenu(true);
q = new CocoQuery(getActivity());
}
protected void save(String key, Object obj) {
if (getActivity() instanceof Base)
((Base) getActivity()).save(key, obj);
}
protected void save(Object obj) {
if (getActivity() instanceof Base && obj != null)
((Base) getActivity()).save(this.getClass().getName() + obj.getClass().getName(), obj);
}
protected <T> T load(String key) {
if (getActivity() instanceof Base)
return (T) ((Base) getActivity()).load(key);
return null;
}
protected Object load(Object obj) {
if (getActivity() instanceof Base && obj != null)
return ((Base) getActivity()).load(this.getClass().getName() + obj.getClass().getName());
return null;
}
@Override
public Loader<T> onCreateLoader(final int id, final Bundle args) {
onStartLoading();
return loader = new ThrowableLoader<T>(getActivity(), items) {
@Override
public T loadData() throws Exception {
return pendingData(args);
}
};
}
protected void inject() {
Injector.inject(this);
}
protected void onStartLoading() {
loaderRunning = true;
}
protected void onStopLoading() {
loaderRunning = false;
hideLoading();
}
@Override
public View onCreateView(final LayoutInflater inflater,
final ViewGroup container, final Bundle savedInstanceState) {
LifecycleDispatcher.get().onFragmentCreateView(this, inflater, container, savedInstanceState);
v = inflater.inflate(layoutId(), null);
ButterKnife.bind(this, v);
if (q == null)
q = new CocoQuery(v);
else
q.recycle(v);
try {
setupUI(v, savedInstanceState);
} catch (final Exception e) {
ExceptionManager.error(e, context, this);
}
return v;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
v = null;
q = null;
loader = null;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LifecycleDispatcher.get().onFragmentViewCreated(this, view, savedInstanceState);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
LifecycleDispatcher.get().onFragmentSaveInstanceState(this, outState);
}
@Override
public void onStop() {
super.onStop();
LifecycleDispatcher.get().onFragmentStopped(this);
}
@Override
public void onPause() {
super.onPause();
if (getActivity() instanceof Base) {
Base activity = ((Base) getActivity());
activity.removeInsetChangedCallback(this);
activity.resetInsets();
}
LifecycleDispatcher.get().onFragmentPaused(this);
}
@Override
public void onResume() {
super.onResume();
if (getActivity() instanceof Base) {
((Base) getActivity()).addInsetChangedCallback(this);
}
LifecycleDispatcher.get().onFragmentResumed(this);
}
@Override
public void onDetach() {
super.onDetach();
LifecycleDispatcher.get().onFragmentDetach(this);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
LifecycleDispatcher.get().onFragmentAttach(this, activity);
}
@Override
public void onDialogResult(final int requestCode, final int resultCode,
final Bundle arguments) {
// Intentionally left blank
}
/**
* A handy way of findViewById
* @param resourceId view id
* @return view instance
*/
protected final <E extends View> E view(int resourceId) {
return (E) v.findViewById(resourceId);
}
@Override
public void onLoaderDone(final T items) {
}
@Override
public void onLoaderReset(final Loader<T> loader) {
}
@Override
public void onLoadFinished(final Loader<T> loader, final T items) {
final Exception exception = getException(loader);
onStopLoading();
if (exception != null) {
showError(exception);
return;
}
onLoaderDone(items);
}
@Override
public T pendingData(final Bundle arg) throws Exception {
return null;
}
/**
* Reload current loader
*/
public void refresh() {
refresh(getArguments());
}
/**
* Reload current loader with arguments
*
* @param b arguments
*/
protected void refresh(final Bundle b) {
onStartLoading();
getLoaderManager().restartLoader(this.hashCode(), b, this);
}
/**
* Is current loader running or not
* @return Is current loader running or not
*/
protected boolean isLoaderRunning() {
return loaderRunning;
}
/**
* Set up your fragment ui, which exactly like you did in {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} with inflated view
*
* @param view
* @param bundle
* @throws Exception
*/
protected abstract void setupUI(View view, Bundle bundle) throws Exception;
/**
* Failback of loader, meaning there is a exception been catched in {@link #pendingData(Bundle)}
*
* @param e the catch exception in loader
*/
@Override
public void showError(final Exception e) {
try {
ExceptionManager.handle(e, getActivity(), this);
} catch (final CocoException e1) {
showRefresh(e1);
}
}
protected void showRefresh(final CocoException e) {
new UndoBarController.UndoBar(getActivity()).message(e.getMessage()).listener(new UndoListener() {
@Override
public void onUndo(Parcelable parcelable) {
refresh();
}
}).style(UndoBarController.RETRYSTYLE).show();
}
private Base<?> getBase() {
try {
return (Base<?>) getActivity();
} catch (final Exception e) {
return null;
}
}
protected void showLoading(final String str) {
getBase().showLoading(str);
}
@Override
public void onDestroy() {
super.onDestroy();
LifecycleDispatcher.get().onFragmentDestroyed(this);
}
@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> fragments = getChildFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
protected void hideLoading() {
if (getBase() != null)
getBase().hideLoading();
}
@Override
public void onInsetsChanged(SystemBarTintManager.SystemBarConfig insets) {
if (v != null)
v.setPadding(
0, insets.getPixelInsetTop(hasActionBarBlock())
, insets.getPixelInsetRight(), insets.getPixelInsetBottom()
);
}
protected boolean hasActionBarBlock() {
return !(getActionBar() == null || !getActionBar().isShowing());
}
/**
* Safely start a intent without worry activity not found
* @param intent the intent try to launch
*/
public void startActivitySafely(Intent intent) {
try {
super.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), R.string.activity_not_found, Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(getActivity(), R.string.activity_not_found, Toast.LENGTH_SHORT).show();
}
}
/**
* Safely start a intent for result without worry activity not found
* @param intent the intent try to launch
*/
public void startActivityForResultSafely(Intent intent, int requestCode) {
try {
super.startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), R.string.activity_not_found, Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(getActivity(), R.string.activity_not_found, Toast.LENGTH_SHORT).show();
}
}
public boolean onBackPressed() {
return false;
}
}
| apache-2.0 |
jinkg/UAFClient | fidoclient/src/androidTest/java/com/yalin/fidoclient/ApplicationTest.java | 3000 | /*
* Copyright 2016 YaLin Jin
*
* 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.yalin.fidoclient;
import android.app.Application;
import android.test.ApplicationTestCase;
import com.google.gson.Gson;
import com.yalin.fidoclient.constants.Constants;
import com.yalin.fidoclient.net.response.FacetIdListResponse;
import com.yalin.fidoclient.op.ASMMessageHandler;
import com.yalin.fidoclient.op.Completion;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
public void testBase64Encoded() {
String base64String = "VkNhalNrYWVsajhHclZJdG5hMkF5eXRIMVlrQ3pBb3Z6T1ZHblRNTg";
String base64String1 = base64String.trim();
assertTrue(base64String1.matches(Constants.BASE64_REGULAR));
}
public void testFacetIdMatch() {
String facetIdListJson = "{\"trustedFacets\":[{\"version\":{\"major\":1,\"minor\":0},\"ids\":[\"android:apk-key-hash:q/e9IaNQq0aVXc8lllq7i/AsAX0\",\"android:apk-key-hash:fX7gLfYPhfPY74RGgK0NYG6Qn8Y\",\"android:apk-key-hash:Tr3wU3S3ZzXhrdXsQY8ykrKPYok\",\"android:apk-key-hash:EVXld/jIwGnA0Lpa+HZ+r+095m4\",\"android:apk-key-hash:LGVXnmy3laAWV/WZJ7PBiA9ASkg\",\"ios:bundle-id:com.raonsecure.fido.rp1\",\"android:apk-key-hash:Df+2X53Z0UscvUu6obxC3rIfFyk\",\"android:apk-key-hash:/G50F1N5KDg/rxYX1gYwLlp7FvM\",\"ios:bundle-id:com.kt.fidocert\",\"android:apk-key-hash:NVvf2qB+6Pr/9cLsS35pOpv67As\",\"ios:bundle-id:com.raonsecure.fidocert\",\"android:apk-key-hash:Y9a2IZqAfkqQtyVXx7p5sFr4RCc\",\"android:apk-key-hash:NVvf2qB+6Pr/9cLsS35pOpv67As\",\"android:apk-key-hash:f+jGL/M5P0cm1tqfxD05s/851eE\",\"android:apk-key-hash:/M90Btryt52setdCdLo1ih96MXg\",\"ios:bundle-id:com.crosscert.fidorpc\",\"android:apk-key-hash:AwHDCRdzkMAsOa7aDPbnG2J95Is\",\"ios:bundle-id:com.crosscert.fidorpc\"]}]}";
String facetId = "android:apk-key-hash:q/e9IaNQq0aVXc8lllq7i/AsAX0";
String facetId1 = "android:apk-key-hash:SvYZ4Sgas9T2+6DpNj566iscuns";
FacetIdListResponse facetIdListResponse = new Gson().fromJson(facetIdListJson, FacetIdListResponse.class);
boolean match = ASMMessageHandler.checkFacetId(facetId, facetIdListResponse.trustedFacets);
boolean match1 = ASMMessageHandler.checkFacetId(facetId1, facetIdListResponse.trustedFacets);
assertTrue(match);
assertTrue(!match1);
}
} | apache-2.0 |
alexhilton/miscellaneous | java/Exercises/src/exercises/threads/threadexception/NativeExceptionHandling.java | 478 | /**
*
*/
package exercises.threads.threadexception;
import java.util.concurrent.*;
/**
* @author gongzhihui
*
*/
public class NativeExceptionHandling {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new ExceptionThread());
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
}
| apache-2.0 |
cahergil/MusicApp | app/src/test/java/com/radio/chernandez/musicapp/ExampleUnitTest.java | 407 | package com.radio.chernandez.musicapp;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
sequenceiq/cloudbreak | integration-test/src/main/java/com/sequenceiq/it/ssh/EverythingOkCommand.java | 1505 | package com.sequenceiq.it.ssh;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.Environment;
import org.apache.sshd.server.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class EverythingOkCommand implements Command {
private static final Logger LOGGER = LoggerFactory.getLogger(EverythingOkCommand.class);
private ExitCallback callback;
private InputStream in;
private OutputStream err;
private OutputStream out;
@Override
public void setInputStream(InputStream in) {
LOGGER.info("setInputStream");
this.in = in;
}
@Override
public void setOutputStream(OutputStream out) {
LOGGER.info("setErrorStream");
this.out = out;
}
@Override
public void setErrorStream(OutputStream err) {
LOGGER.info("setErrorStream");
this.err = err;
}
@Override
public void setExitCallback(ExitCallback callback) {
this.callback = callback;
LOGGER.info("setExitCallback");
}
@Override
public void start(Environment env) throws IOException {
LOGGER.info("start");
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(err);
callback.onExit(0);
}
@Override
public void destroy() throws Exception {
LOGGER.info("destroy");
}
}
| apache-2.0 |
T5750/maven-archetype-templates | SpringBoot/springboot-elasticsearch/src/main/java/com/evangel/service/CityService.java | 457 | package com.evangel.service;
import java.util.List;
import com.evangel.domain.City;
public interface CityService {
/**
* 新增城市信息
*
* @param city
* @return
*/
Long saveCity(City city);
/**
* 根据关键词,function score query 权重分分页查询
*
* @param pageNumber
* @param pageSize
* @param searchContent
* @return
*/
List<City> searchCity(Integer pageNumber, Integer pageSize,
String searchContent);
} | apache-2.0 |
baart92/jgrades | jg-backend/implementation/base/jg-lic/implementation/src/main/java/org/jgrades/lic/entities/ProductEntity.java | 2556 | package org.jgrades.lic.entities;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import javax.persistence.*;
@Entity
@Table(name = "JG_LIC_PRODUCT")
public class ProductEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String version;
@Column
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime validFrom;
@Column
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime validTo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public DateTime getValidFrom() {
return validFrom;
}
public void setValidFrom(DateTime validFrom) {
this.validFrom = validFrom;
}
public DateTime getValidTo() {
return validTo;
}
public void setValidTo(DateTime validTo) {
this.validTo = validTo;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("id", id)
.append("name", name)
.append("version", version)
.append("validFrom", validFrom)
.append("validTo", validTo)
.toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
ProductEntity rhs = (ProductEntity) obj;
return new EqualsBuilder()
.append(this.name, rhs.name)
.append(this.version, rhs.version)
.append(this.validFrom, rhs.validFrom)
.append(this.validTo, rhs.validTo)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(name)
.append(version)
.toHashCode();
}
}
| apache-2.0 |
googleapis/java-docfx-doclet | third_party/docfx-doclet-143274/src/main/java/com/microsoft/model/Return.java | 800 | package com.microsoft.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Return {
@JsonProperty("type")
private final String returnType;
@JsonProperty("description")
private String returnDescription;
public Return(String returnType, String returnDescription) {
this.returnType = returnType;
this.returnDescription = returnDescription;
}
public Return(String returnType) {
this.returnType = returnType;
}
public String getReturnType() {
return returnType;
}
public String getReturnDescription() {
return returnDescription;
}
public void setReturnDescription(String returnDescription) {
this.returnDescription = returnDescription;
}
}
| apache-2.0 |
nathanross/GWTriFold | SampleApp/src/com/website/sample/client/GreetingServiceAsync.java | 309 | package com.website.sample.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* The async counterpart of <code>GreetingService</code>.
*/
public interface GreetingServiceAsync {
void greetServer(String input, AsyncCallback<String> callback)
throws IllegalArgumentException;
}
| apache-2.0 |
jaadds/product-apim | modules/integration/tests-common/clients/publisher/src/gen/java/org/wso2/am/integration/clients/publisher/api/v1/dto/LifecycleStateAvailableTransitionsDTO.java | 3280 | /*
* WSO2 API Manager - Publisher API
* This specifies a **RESTful API** for WSO2 **API Manager** - Publisher. Please see [full swagger definition](https://raw.githubusercontent.com/wso2/carbon-apimgt/v6.0.4/components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/main/resources/publisher-api.yaml) of the API which is written using [swagger 2.0](http://swagger.io/) specification.
*
* OpenAPI spec version: v1.1
* Contact: architecture@wso2.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.wso2.am.integration.clients.publisher.api.v1.dto;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
/**
* LifecycleStateAvailableTransitionsDTO
*/
public class LifecycleStateAvailableTransitionsDTO {
@SerializedName("event")
private String event = null;
@SerializedName("targetState")
private String targetState = null;
public LifecycleStateAvailableTransitionsDTO event(String event) {
this.event = event;
return this;
}
/**
* Get event
* @return event
**/
@ApiModelProperty(example = "Promote", value = "")
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public LifecycleStateAvailableTransitionsDTO targetState(String targetState) {
this.targetState = targetState;
return this;
}
/**
* Get targetState
* @return targetState
**/
@ApiModelProperty(example = "Created", value = "")
public String getTargetState() {
return targetState;
}
public void setTargetState(String targetState) {
this.targetState = targetState;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LifecycleStateAvailableTransitionsDTO lifecycleStateAvailableTransitions = (LifecycleStateAvailableTransitionsDTO) o;
return Objects.equals(this.event, lifecycleStateAvailableTransitions.event) &&
Objects.equals(this.targetState, lifecycleStateAvailableTransitions.targetState);
}
@Override
public int hashCode() {
return Objects.hash(event, targetState);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LifecycleStateAvailableTransitionsDTO {\n");
sb.append(" event: ").append(toIndentedString(event)).append("\n");
sb.append(" targetState: ").append(toIndentedString(targetState)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-directconnect/src/main/java/com/amazonaws/services/directconnect/model/DuplicateTagKeysException.java | 1231 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.directconnect.model;
import javax.annotation.Generated;
/**
* <p>
* A tag key was specified more than once.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DuplicateTagKeysException extends com.amazonaws.services.directconnect.model.AmazonDirectConnectException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new DuplicateTagKeysException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public DuplicateTagKeysException(String message) {
super(message);
}
}
| apache-2.0 |
ogrebgr/forge-android-skeleton-basic | app/src/main/java/com/bolyartech/forge/skeleton/dagger/basic/units/login/LoginTaskImpl.java | 7305 | package com.bolyartech.forge.skeleton.dagger.basic.units.login;
import android.support.annotation.NonNull;
import com.bolyartech.forge.base.exchange.HttpExchange;
import com.bolyartech.forge.base.exchange.ResultProducer;
import com.bolyartech.forge.base.exchange.builders.ForgePostHttpExchangeBuilder;
import com.bolyartech.forge.base.exchange.forge.BasicResponseCodes;
import com.bolyartech.forge.base.exchange.forge.ForgeExchangeHelper;
import com.bolyartech.forge.base.exchange.forge.ForgeExchangeResult;
import com.bolyartech.forge.base.rc_task.AbstractRcTask;
import com.bolyartech.forge.base.rc_task.RcTaskResult;
import com.bolyartech.forge.base.session.Session;
import com.bolyartech.forge.skeleton.dagger.basic.app.AppConfiguration;
import com.bolyartech.forge.skeleton.dagger.basic.app.AuthenticationResponseCodes;
import com.bolyartech.forge.skeleton.dagger.basic.app.CurrentUser;
import com.bolyartech.forge.skeleton.dagger.basic.app.CurrentUserHolder;
import com.bolyartech.forge.skeleton.dagger.basic.app.LoginPrefs;
import com.bolyartech.forge.skeleton.dagger.basic.app.SessionForgeExchangeExecutor;
import com.bolyartech.scram_sasl.client.ScramClientFunctionality;
import com.bolyartech.scram_sasl.common.ScramException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import javax.inject.Inject;
public class LoginTaskImpl extends AbstractRcTask<RcTaskResult<Void, Integer>> implements LoginTask {
private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
private final ForgeExchangeHelper forgeExchangeHelper;
private final ScramClientFunctionality scramClientFunctionality;
private final SessionForgeExchangeExecutor sessionExecutor;
private final Session session;
private final CurrentUserHolder currentUserHolder;
private final AppConfiguration appConfiguration;
private String username;
private String password;
private boolean autologin;
@Inject
public LoginTaskImpl(ForgeExchangeHelper forgeExchangeHelper,
ScramClientFunctionality scramClientFunctionality,
SessionForgeExchangeExecutor sessionExecutor,
Session session,
CurrentUserHolder currentUserHolder,
AppConfiguration appConfiguration) {
super(TASK_ID);
this.forgeExchangeHelper = forgeExchangeHelper;
this.scramClientFunctionality = scramClientFunctionality;
this.sessionExecutor = sessionExecutor;
this.session = session;
this.currentUserHolder = currentUserHolder;
this.appConfiguration = appConfiguration;
}
@Override
public void execute() {
try {
if (this.username == null) {
throw new IllegalStateException("username is null. Did you forgot to call init() " +
"before execute()?");
}
HttpExchange<ForgeExchangeResult> login1exchange = createLoginStep1Exchange(username);
ForgeExchangeResult rez1 = sessionExecutor.execute(login1exchange);
if (rez1.getCode() != BasicResponseCodes.OK) {
logger.warn("login1exchange not successful");
setTaskResult(RcTaskResult.createErrorResult(rez1.getCode()));
return;
}
if (isCancelled()) {
return;
}
String serverFirst = rez1.getPayload();
String clientFinal = scramClientFunctionality.prepareFinalMessage(password, serverFirst);
if (clientFinal == null) {
logger.warn("Invalid login 1");
setTaskResult(RcTaskResult.createErrorResult(AuthenticationResponseCodes.Errors.INVALID_LOGIN));
return;
}
HttpExchange<ForgeExchangeResult> login2exchange = createLoginStep2Exchange(clientFinal);
ForgeExchangeResult rez2 = sessionExecutor.execute(login2exchange);
if (rez2.getCode() != BasicResponseCodes.OK) {
logger.warn("login1exchange not successful");
setTaskResult(RcTaskResult.createErrorResult(rez1.getCode()));
return;
}
if (isCancelled()) {
return;
}
JSONObject jsonObj = new JSONObject(rez2.getPayload());
int sessionTtl = jsonObj.getInt("session_ttl");
JSONObject sessionInfo = jsonObj.optJSONObject("session_info");
String serverFinal = jsonObj.getString("final_message");
if (!scramClientFunctionality.checkServerFinalMessage(serverFinal)) {
logger.warn("Invalid login 2");
setTaskResult(RcTaskResult.createErrorResult(BasicResponseCodes.Errors.UNSPECIFIED_ERROR));
return;
}
if (sessionInfo == null) {
logger.error("sessionInfo is empty.");
setTaskResult(RcTaskResult.createErrorResult(BasicResponseCodes.Errors.UNSPECIFIED_ERROR));
return;
}
session.startSession(sessionTtl);
currentUserHolder.setCurrentUser(
new CurrentUser(sessionInfo.getLong("user_id"),
sessionInfo.optString("screen_name", null)));
logger.debug("App login OK");
// appConfiguration.getAppPrefs().save();
LoginPrefs lp = appConfiguration.getLoginPrefs();
lp.setUsername(username);
lp.setPassword(password);
if (!autologin) {
lp.setManualRegistration(true);
}
lp.save();
setTaskResult(RcTaskResult.createSuccessResult(null));
} catch (ScramException | ResultProducer.ResultProducerException | IOException |
JSONException e) {
logger.error(e.getMessage());
setTaskResult(RcTaskResult.createErrorResult(BasicResponseCodes.Errors.UNSPECIFIED_ERROR));
}
}
public void init(@NonNull String username, @NonNull String password, boolean autologin) {
this.username = username;
this.password = password;
this.autologin = autologin;
}
private HttpExchange<ForgeExchangeResult> createLoginStep1Exchange(String username) throws ScramException {
ForgePostHttpExchangeBuilder step1builder = forgeExchangeHelper.
createForgePostHttpExchangeBuilder("login");
String clientFirst = scramClientFunctionality.prepareFirstMessage(username);
step1builder.addPostParameter("app_type", "");
step1builder.addPostParameter("app_version", "1");
step1builder.addPostParameter("step", "1");
step1builder.addPostParameter("data", clientFirst);
return step1builder.build();
}
private HttpExchange<ForgeExchangeResult> createLoginStep2Exchange(String clientFinal) {
ForgePostHttpExchangeBuilder step2builder = forgeExchangeHelper.
createForgePostHttpExchangeBuilder("login");
step2builder.addPostParameter("step", "2");
step2builder.addPostParameter("data", clientFinal);
return step2builder.build();
}
} | apache-2.0 |
iemejia/incubator-beam | sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/SchemaTranslation.java | 18841 | /*
* 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.beam.sdk.schemas;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.beam.model.pipeline.v1.SchemaApi;
import org.apache.beam.model.pipeline.v1.SchemaApi.ArrayTypeValue;
import org.apache.beam.model.pipeline.v1.SchemaApi.AtomicTypeValue;
import org.apache.beam.model.pipeline.v1.SchemaApi.FieldValue;
import org.apache.beam.model.pipeline.v1.SchemaApi.IterableTypeValue;
import org.apache.beam.model.pipeline.v1.SchemaApi.MapTypeEntry;
import org.apache.beam.model.pipeline.v1.SchemaApi.MapTypeValue;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
import org.apache.beam.sdk.schemas.Schema.Field;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.schemas.Schema.LogicalType;
import org.apache.beam.sdk.schemas.Schema.TypeName;
import org.apache.beam.sdk.util.SerializableUtils;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.vendor.grpc.v1p26p0.com.google.protobuf.ByteString;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Maps;
/** Utility methods for translating schemas. */
@Experimental(Kind.SCHEMAS)
public class SchemaTranslation {
private static final String URN_BEAM_LOGICAL_DATETIME = "beam:logical_type:datetime:v1";
private static final String URN_BEAM_LOGICAL_DECIMAL = "beam:logical_type:decimal:v1";
private static final String URN_BEAM_LOGICAL_JAVASDK = "beam:logical_type:javasdk:v1";
public static SchemaApi.Schema schemaToProto(Schema schema, boolean serializeLogicalType) {
String uuid = schema.getUUID() != null ? schema.getUUID().toString() : "";
SchemaApi.Schema.Builder builder = SchemaApi.Schema.newBuilder().setId(uuid);
for (Field field : schema.getFields()) {
SchemaApi.Field protoField =
fieldToProto(
field,
schema.indexOf(field.getName()),
schema.getEncodingPositions().get(field.getName()),
serializeLogicalType);
builder.addFields(protoField);
}
builder.addAllOptions(optionsToProto(schema.getOptions()));
return builder.build();
}
private static SchemaApi.Field fieldToProto(
Field field, int fieldId, int position, boolean serializeLogicalType) {
return SchemaApi.Field.newBuilder()
.setName(field.getName())
.setDescription(field.getDescription())
.setType(fieldTypeToProto(field.getType(), serializeLogicalType))
.setId(fieldId)
.setEncodingPosition(position)
.addAllOptions(optionsToProto(field.getOptions()))
.build();
}
private static SchemaApi.FieldType fieldTypeToProto(
FieldType fieldType, boolean serializeLogicalType) {
SchemaApi.FieldType.Builder builder = SchemaApi.FieldType.newBuilder();
switch (fieldType.getTypeName()) {
case ROW:
builder.setRowType(
SchemaApi.RowType.newBuilder()
.setSchema(schemaToProto(fieldType.getRowSchema(), serializeLogicalType)));
break;
case ARRAY:
builder.setArrayType(
SchemaApi.ArrayType.newBuilder()
.setElementType(
fieldTypeToProto(fieldType.getCollectionElementType(), serializeLogicalType)));
break;
case ITERABLE:
builder.setIterableType(
SchemaApi.IterableType.newBuilder()
.setElementType(
fieldTypeToProto(fieldType.getCollectionElementType(), serializeLogicalType)));
break;
case MAP:
builder.setMapType(
SchemaApi.MapType.newBuilder()
.setKeyType(fieldTypeToProto(fieldType.getMapKeyType(), serializeLogicalType))
.setValueType(fieldTypeToProto(fieldType.getMapValueType(), serializeLogicalType))
.build());
break;
case LOGICAL_TYPE:
LogicalType logicalType = fieldType.getLogicalType();
SchemaApi.LogicalType.Builder logicalTypeBuilder =
SchemaApi.LogicalType.newBuilder()
.setArgumentType(
fieldTypeToProto(logicalType.getArgumentType(), serializeLogicalType))
.setArgument(
fieldValueToProto(logicalType.getArgumentType(), logicalType.getArgument()))
.setRepresentation(
fieldTypeToProto(logicalType.getBaseType(), serializeLogicalType))
// TODO(BEAM-7855): "javasdk" types should only be a last resort. Types defined in
// Beam should have their own URN, and there should be a mechanism for users to
// register their own types by URN.
.setUrn(URN_BEAM_LOGICAL_JAVASDK);
if (serializeLogicalType) {
logicalTypeBuilder =
logicalTypeBuilder.setPayload(
ByteString.copyFrom(SerializableUtils.serializeToByteArray(logicalType)));
}
builder.setLogicalType(logicalTypeBuilder.build());
break;
// Special-case for DATETIME and DECIMAL which are logical types in portable representation,
// but not yet in Java. (BEAM-7554)
case DATETIME:
builder.setLogicalType(
SchemaApi.LogicalType.newBuilder()
.setUrn(URN_BEAM_LOGICAL_DATETIME)
.setRepresentation(fieldTypeToProto(FieldType.INT64, serializeLogicalType))
.build());
break;
case DECIMAL:
builder.setLogicalType(
SchemaApi.LogicalType.newBuilder()
.setUrn(URN_BEAM_LOGICAL_DECIMAL)
.setRepresentation(fieldTypeToProto(FieldType.BYTES, serializeLogicalType))
.build());
break;
case BYTE:
builder.setAtomicType(SchemaApi.AtomicType.BYTE);
break;
case INT16:
builder.setAtomicType(SchemaApi.AtomicType.INT16);
break;
case INT32:
builder.setAtomicType(SchemaApi.AtomicType.INT32);
break;
case INT64:
builder.setAtomicType(SchemaApi.AtomicType.INT64);
break;
case FLOAT:
builder.setAtomicType(SchemaApi.AtomicType.FLOAT);
break;
case DOUBLE:
builder.setAtomicType(SchemaApi.AtomicType.DOUBLE);
break;
case STRING:
builder.setAtomicType(SchemaApi.AtomicType.STRING);
break;
case BOOLEAN:
builder.setAtomicType(SchemaApi.AtomicType.BOOLEAN);
break;
case BYTES:
builder.setAtomicType(SchemaApi.AtomicType.BYTES);
break;
}
builder.setNullable(fieldType.getNullable());
return builder.build();
}
public static Schema schemaFromProto(SchemaApi.Schema protoSchema) {
Schema.Builder builder = Schema.builder();
Map<String, Integer> encodingLocationMap = Maps.newHashMap();
for (SchemaApi.Field protoField : protoSchema.getFieldsList()) {
Field field = fieldFromProto(protoField);
builder.addField(field);
encodingLocationMap.put(protoField.getName(), protoField.getEncodingPosition());
}
builder.setOptions(optionsFromProto(protoSchema.getOptionsList()));
Schema schema = builder.build();
schema.setEncodingPositions(encodingLocationMap);
if (!protoSchema.getId().isEmpty()) {
schema.setUUID(UUID.fromString(protoSchema.getId()));
}
return schema;
}
private static Field fieldFromProto(SchemaApi.Field protoField) {
return Field.of(protoField.getName(), fieldTypeFromProto(protoField.getType()))
.withOptions(optionsFromProto(protoField.getOptionsList()))
.withDescription(protoField.getDescription());
}
private static FieldType fieldTypeFromProto(SchemaApi.FieldType protoFieldType) {
FieldType fieldType = fieldTypeFromProtoWithoutNullable(protoFieldType);
if (protoFieldType.getNullable()) {
fieldType = fieldType.withNullable(true);
}
return fieldType;
}
private static FieldType fieldTypeFromProtoWithoutNullable(SchemaApi.FieldType protoFieldType) {
switch (protoFieldType.getTypeInfoCase()) {
case ATOMIC_TYPE:
switch (protoFieldType.getAtomicType()) {
case BYTE:
return FieldType.of(TypeName.BYTE);
case INT16:
return FieldType.of(TypeName.INT16);
case INT32:
return FieldType.of(TypeName.INT32);
case INT64:
return FieldType.of(TypeName.INT64);
case FLOAT:
return FieldType.of(TypeName.FLOAT);
case DOUBLE:
return FieldType.of(TypeName.DOUBLE);
case STRING:
return FieldType.of(TypeName.STRING);
case BOOLEAN:
return FieldType.of(TypeName.BOOLEAN);
case BYTES:
return FieldType.of(TypeName.BYTES);
case UNSPECIFIED:
throw new IllegalArgumentException("Encountered UNSPECIFIED AtomicType");
default:
throw new IllegalArgumentException(
"Encountered unknown AtomicType: " + protoFieldType.getAtomicType());
}
case ROW_TYPE:
return FieldType.row(schemaFromProto(protoFieldType.getRowType().getSchema()));
case ARRAY_TYPE:
return FieldType.array(fieldTypeFromProto(protoFieldType.getArrayType().getElementType()));
case ITERABLE_TYPE:
return FieldType.iterable(
fieldTypeFromProto(protoFieldType.getIterableType().getElementType()));
case MAP_TYPE:
return FieldType.map(
fieldTypeFromProto(protoFieldType.getMapType().getKeyType()),
fieldTypeFromProto(protoFieldType.getMapType().getValueType()));
case LOGICAL_TYPE:
// Special-case for DATETIME and DECIMAL which are logical types in portable representation,
// but not yet in Java. (BEAM-7554)
String urn = protoFieldType.getLogicalType().getUrn();
if (urn.equals(URN_BEAM_LOGICAL_DATETIME)) {
return FieldType.DATETIME;
} else if (urn.equals(URN_BEAM_LOGICAL_DECIMAL)) {
return FieldType.DECIMAL;
} else if (urn.equals(URN_BEAM_LOGICAL_JAVASDK)) {
return FieldType.logicalType(
(LogicalType)
SerializableUtils.deserializeFromByteArray(
protoFieldType.getLogicalType().getPayload().toByteArray(), "logicalType"));
} else {
throw new IllegalArgumentException("Encountered unsupported logical type URN: " + urn);
}
default:
throw new IllegalArgumentException(
"Unexpected type_info: " + protoFieldType.getTypeInfoCase());
}
}
public static SchemaApi.Row rowToProto(Row row) {
SchemaApi.Row.Builder builder = SchemaApi.Row.newBuilder();
for (int i = 0; i < row.getFieldCount(); ++i) {
builder.addValues(fieldValueToProto(row.getSchema().getField(i).getType(), row.getValue(i)));
}
return builder.build();
}
public static Object rowFromProto(SchemaApi.Row row, FieldType fieldType) {
Row.Builder builder = Row.withSchema(fieldType.getRowSchema());
for (int i = 0; i < row.getValuesCount(); ++i) {
builder.addValue(
fieldValueFromProto(fieldType.getRowSchema().getField(i).getType(), row.getValues(i)));
}
return builder.build();
}
static SchemaApi.FieldValue fieldValueToProto(FieldType fieldType, Object value) {
FieldValue.Builder builder = FieldValue.newBuilder();
switch (fieldType.getTypeName()) {
case ARRAY:
return builder
.setArrayValue(
arrayValueToProto(fieldType.getCollectionElementType(), (Iterable) value))
.build();
case ITERABLE:
return builder
.setIterableValue(
iterableValueToProto(fieldType.getCollectionElementType(), (Iterable) value))
.build();
case MAP:
return builder
.setMapValue(
mapToProto(fieldType.getMapKeyType(), fieldType.getMapValueType(), (Map) value))
.build();
case ROW:
return builder.setRowValue(rowToProto((Row) value)).build();
case LOGICAL_TYPE:
default:
return builder.setAtomicValue(primitiveRowFieldToProto(fieldType, value)).build();
}
}
static Object fieldValueFromProto(FieldType fieldType, SchemaApi.FieldValue value) {
switch (fieldType.getTypeName()) {
case ARRAY:
return arrayValueFromProto(fieldType.getCollectionElementType(), value.getArrayValue());
case ITERABLE:
return iterableValueFromProto(
fieldType.getCollectionElementType(), value.getIterableValue());
case MAP:
return mapFromProto(
fieldType.getMapKeyType(), fieldType.getMapValueType(), value.getMapValue());
case ROW:
return rowFromProto(value.getRowValue(), fieldType);
case LOGICAL_TYPE:
default:
return primitiveFromProto(fieldType, value.getAtomicValue());
}
}
private static SchemaApi.ArrayTypeValue arrayValueToProto(
FieldType elementType, Iterable values) {
return ArrayTypeValue.newBuilder()
.addAllElement(Iterables.transform(values, e -> fieldValueToProto(elementType, e)))
.build();
}
private static Iterable arrayValueFromProto(
FieldType elementType, SchemaApi.ArrayTypeValue values) {
return values.getElementList().stream()
.map(e -> fieldValueFromProto(elementType, e))
.collect(Collectors.toList());
}
private static SchemaApi.IterableTypeValue iterableValueToProto(
FieldType elementType, Iterable values) {
return IterableTypeValue.newBuilder()
.addAllElement(Iterables.transform(values, e -> fieldValueToProto(elementType, e)))
.build();
}
private static Object iterableValueFromProto(FieldType elementType, IterableTypeValue values) {
return values.getElementList().stream()
.map(e -> fieldValueFromProto(elementType, e))
.collect(Collectors.toList());
}
private static SchemaApi.MapTypeValue mapToProto(
FieldType keyType, FieldType valueType, Map<Object, Object> map) {
MapTypeValue.Builder builder = MapTypeValue.newBuilder();
for (Map.Entry entry : map.entrySet()) {
MapTypeEntry mapProtoEntry =
MapTypeEntry.newBuilder()
.setKey(fieldValueToProto(keyType, entry.getKey()))
.setValue(fieldValueToProto(valueType, entry.getValue()))
.build();
builder.addEntries(mapProtoEntry);
}
return builder.build();
}
private static Object mapFromProto(
FieldType mapKeyType, FieldType mapValueType, MapTypeValue mapValue) {
return mapValue.getEntriesList().stream()
.collect(
Collectors.toMap(
entry -> fieldValueFromProto(mapKeyType, entry.getKey()),
entry -> fieldValueFromProto(mapValueType, entry.getValue())));
}
private static AtomicTypeValue primitiveRowFieldToProto(FieldType fieldType, Object value) {
switch (fieldType.getTypeName()) {
case BYTE:
return AtomicTypeValue.newBuilder().setByte((byte) value).build();
case INT16:
return AtomicTypeValue.newBuilder().setInt16((short) value).build();
case INT32:
return AtomicTypeValue.newBuilder().setInt32((int) value).build();
case INT64:
return AtomicTypeValue.newBuilder().setInt64((long) value).build();
case FLOAT:
return AtomicTypeValue.newBuilder().setFloat((float) value).build();
case DOUBLE:
return AtomicTypeValue.newBuilder().setDouble((double) value).build();
case STRING:
return AtomicTypeValue.newBuilder().setString((String) value).build();
case BOOLEAN:
return AtomicTypeValue.newBuilder().setBoolean((boolean) value).build();
case BYTES:
return AtomicTypeValue.newBuilder().setBytes(ByteString.copyFrom((byte[]) value)).build();
default:
throw new RuntimeException("FieldType unexpected " + fieldType.getTypeName());
}
}
private static Object primitiveFromProto(FieldType fieldType, AtomicTypeValue value) {
switch (fieldType.getTypeName()) {
case BYTE:
return (byte) value.getByte();
case INT16:
return (short) value.getInt16();
case INT32:
return value.getInt32();
case INT64:
return value.getInt64();
case FLOAT:
return value.getFloat();
case DOUBLE:
return value.getDouble();
case STRING:
return value.getString();
case BOOLEAN:
return value.getBoolean();
case BYTES:
return value.getBytes().toByteArray();
default:
throw new RuntimeException("FieldType unexpected " + fieldType.getTypeName());
}
}
private static List<SchemaApi.Option> optionsToProto(Schema.Options options) {
List<SchemaApi.Option> protoOptions = new ArrayList<>();
for (String name : options.getOptionNames()) {
protoOptions.add(
SchemaApi.Option.newBuilder()
.setName(name)
.setType(fieldTypeToProto(Objects.requireNonNull(options.getType(name)), false))
.setValue(
fieldValueToProto(
Objects.requireNonNull(options.getType(name)), options.getValue(name)))
.build());
}
return protoOptions;
}
private static Schema.Options optionsFromProto(List<SchemaApi.Option> protoOptions) {
Schema.Options.Builder optionBuilder = Schema.Options.builder();
for (SchemaApi.Option protoOption : protoOptions) {
FieldType fieldType = fieldTypeFromProto(protoOption.getType());
optionBuilder.setOption(
protoOption.getName(), fieldType, fieldValueFromProto(fieldType, protoOption.getValue()));
}
return optionBuilder.build();
}
}
| apache-2.0 |
btc-ag/redg | redg-generator/src/main/java/com/btc/redg/generator/extractor/datatypeprovider/xml/TableTypeMapping.java | 1676 | /*
* Copyright 2017 BTC Business Technology AG
*
* 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.btc.redg.generator.extractor.datatypeprovider.xml;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("table")
public class TableTypeMapping {
private String tableName;
@XStreamImplicit
private List<ColumnTypeMapping> columnTypeMappings;
public TableTypeMapping() {
}
public TableTypeMapping(String tableName, List<ColumnTypeMapping> columnTypeMappings) {
this.tableName = tableName;
this.columnTypeMappings = columnTypeMappings;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public List<ColumnTypeMapping> getColumnTypeMappings() {
return columnTypeMappings;
}
public void setColumnTypeMappings(List<ColumnTypeMapping> columnTypeMappings) {
this.columnTypeMappings = columnTypeMappings;
}
}
| apache-2.0 |
stevem999/gocd | config/config-server/src/test/java/com/thoughtworks/go/config/serialization/JobPropertiesTest.java | 6349 | /*
* Copyright 2016 ThoughtWorks, 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.thoughtworks.go.config.serialization;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.helper.BuildPlanMother;
import com.thoughtworks.go.helper.ConfigFileFixture;
import com.thoughtworks.go.util.ConfigElementImplementationRegistryMother;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import static com.thoughtworks.go.helper.ConfigFileFixture.ONE_PIPELINE;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class JobPropertiesTest {
private MagicalGoConfigXmlLoader loader;
private MagicalGoConfigXmlWriter writer;
private ConfigCache configCache = new ConfigCache();
@Before
public void setUp() throws Exception {
loader = new MagicalGoConfigXmlLoader(configCache, ConfigElementImplementationRegistryMother.withNoPlugins());
writer = new MagicalGoConfigXmlWriter(configCache, ConfigElementImplementationRegistryMother.withNoPlugins());
}
@Test
public void shouldLoadJobProperties() throws Exception {
String jobXml = "<job name=\"dev\">\n"
+ " <properties>\n"
+ " <property name=\"coverage\" src=\"reports/emma.html\" xpath=\"//coverage/class\" />\n"
+ " <property name=\"prop2\" src=\"test.xml\" xpath=\"//value\" />\n"
+ " </properties>\n"
+ "</job>";
CruiseConfig config = loader.loadConfigHolder(ConfigFileFixture.withJob(jobXml)).configForEdit;
JobConfig jobConfig = config.pipelineConfigByName(new CaseInsensitiveString("pipeline1")).get(1).allBuildPlans().first();
assertThat(jobConfig.getProperties().first(),
is(new ArtifactPropertyConfig("coverage", "reports/emma.html", "//coverage/class")));
assertThat(jobConfig.getProperties().get(1),
is(new ArtifactPropertyConfig("prop2", "test.xml", "//value")));
}
@Test
public void shouldWriteJobProperties() throws Exception {
String jobXml = "<job name=\"dev\">\n"
+ " <properties>\n"
+ " <property name=\"coverage\" src=\"reports/emma.html\" xpath=\"//coverage/class\" />\n"
+ " <property name=\"prop2\" src=\"test.xml\" xpath=\"//value\" />\n"
+ " </properties>\n"
+ "</job>";
CruiseConfig config = loader.loadConfigHolder(ConfigFileFixture.withJob(jobXml)).configForEdit;
JobConfig jobConfig = config.pipelineConfigByName(new CaseInsensitiveString("pipeline1")).get(1).allBuildPlans().first();
assertThat(writer.toXmlPartial(jobConfig), is(jobXml));
}
@Test
public void shouldNotLoadDuplicateJobProperties() throws Exception {
String jobXml = "<job name=\"dev\">\n"
+ "<properties>\n"
+ "<property name=\"coverage\" src=\"reports/emma.html\" xpath=\"//coverage/class\" />\n"
+ "<property name=\"coverage\" src=\"test.xml\" xpath=\"//value\" />\n"
+ "</properties>\n"
+ "</job>";
try {
loadJobConfig(jobXml);
fail("should not define two job properties with same name");
} catch (Exception e) {
assertThat(e.getMessage(), containsString("Duplicate unique value"));
}
}
@Test
public void shouldNotWriteDuplicateJobProperties() throws Exception {
ArtifactPropertyConfig artifactPropertyConfig = new ArtifactPropertyConfig("coverage",
"reports/emma.html", "//coverage/class");
CruiseConfig cruiseConfig = cruiseConfigWithProperties(artifactPropertyConfig, artifactPropertyConfig);
try {
writer.write(cruiseConfig, new ByteArrayOutputStream(), false);
fail("should not write two job properties with same name");
} catch (Exception e) {
assertThat(e.getMessage(), containsString("Duplicate unique value"));
}
}
@Test
public void shouldNotAllowEmptyJobProperties() throws Exception {
String jobXml = "<job name=\"dev\">\n"
+ "<properties>\n"
+ "</properties>\n"
+ "</job>";
try {
loadJobConfig(jobXml);
fail("should not allow empty job properties");
} catch (Exception e) {
assertThat(e.getMessage(), containsString("One of '{property}' is expected"));
}
}
@Test
public void shouldNotWriteEmptyJobProperties() throws Exception {
CruiseConfig cruiseConfig = cruiseConfigWithProperties();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
writer.write(cruiseConfig, buffer, false);
assertThat(new String(buffer.toByteArray()), not(containsString("properties")));
}
private CruiseConfig cruiseConfigWithProperties(ArtifactPropertyConfig... artifactPropertyConfigs)
throws Exception {
CruiseConfig cruiseConfig = loader.loadConfigHolder(ONE_PIPELINE).configForEdit;
JobConfig jobConfig = BuildPlanMother.withArtifactPropertiesGenerator(artifactPropertyConfigs);
cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline1")).first().allBuildPlans().add(jobConfig);
return cruiseConfig;
}
private JobConfig loadJobConfig(String jobXml) throws Exception {
CruiseConfig config = loader.loadConfigHolder(ConfigFileFixture.withJob(jobXml)).configForEdit;
return config.pipelineConfigByName(new CaseInsensitiveString("pipeline1")).first().allBuildPlans().first();
}
}
| apache-2.0 |
opetrovski/development | oscm-app-vmware/javasrc/org/oscm/app/vmware/business/VMwareDatacenterInventory.java | 8052 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: 2016-05-24
*
*******************************************************************************/
package org.oscm.app.vmware.business;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import org.oscm.app.vmware.business.VMwareValue.Unit;
import org.oscm.app.vmware.business.model.VMwareHost;
import org.oscm.app.vmware.business.model.VMwareStorage;
import org.oscm.app.vmware.business.model.VMwareVirtualMachine;
import org.oscm.app.vmware.remote.vmware.ManagedObjectAccessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vmware.vim25.DynamicProperty;
import com.vmware.vim25.ManagedObjectReference;
/**
* The data center inventory contains information about all resources available
* in the vCenter. The inventory is filled by adding property sets obtained from
* a VMware property collector.
*
* @author Dirk Bernsau
*
*/
public class VMwareDatacenterInventory {
private static final Logger logger = LoggerFactory
.getLogger(VMwareDatacenterInventory.class);
private HashMap<String, VMwareStorage> storages = new HashMap<String, VMwareStorage>();
private HashMap<String, List<VMwareStorage>> storageByHost = new HashMap<String, List<VMwareStorage>>();
private Collection<VMwareVirtualMachine> vms = new ArrayList<VMwareVirtualMachine>();
private HashMap<String, VMwareHost> hostsSystems = new HashMap<String, VMwareHost>();
private HashMap<Object, String> hostCache = new HashMap<Object, String>();
/**
* Adds a storage instance to the inventory based on given properties.
*
* @return the created storage instance
*/
public VMwareStorage addStorage(String host,
List<DynamicProperty> properties) {
if (properties == null || properties.size() == 0) {
return null;
}
VMwareStorage result = new VMwareStorage();
for (DynamicProperty dp : properties) {
String key = dp.getName();
if ("summary.name".equals(key) && dp.getVal() != null) {
result.setName(dp.getVal().toString());
} else if ("summary.capacity".equals(key) && dp.getVal() != null) {
result.setCapacity(VMwareValue
.fromBytes(Long.parseLong(dp.getVal().toString())));
} else if ("summary.freeSpace".equals(key) && dp.getVal() != null) {
result.setFreeStorage(VMwareValue
.fromBytes(Long.parseLong(dp.getVal().toString())));
}
}
storages.put(result.getName(), result);
if (storageByHost.containsKey(host)) {
storageByHost.get(host).add(result);
} else {
List<VMwareStorage> storage = new ArrayList<VMwareStorage>();
storage.add(result);
storageByHost.put(host, storage);
}
return result;
}
/**
* Adds a host instance to the inventory based on given properties.
*
* @return the created host instance
*/
public VMwareHost addHostSystem(List<DynamicProperty> properties) {
if (properties == null || properties.size() == 0) {
return null;
}
VMwareHost result = new VMwareHost(this);
for (DynamicProperty dp : properties) {
String key = dp.getName();
if ("name".equals(key) && dp.getVal() != null) {
result.setName(dp.getVal().toString());
} else if ("summary.hardware.memorySize".equals(key)
&& dp.getVal() != null) {
result.setMemorySizeMB(VMwareValue
.fromBytes(Long.parseLong(dp.getVal().toString()))
.getValue(Unit.MB));
} else if ("summary.hardware.numCpuCores".equals(key)
&& dp.getVal() != null) {
result.setCpuCores(Integer.parseInt(dp.getVal().toString()));
}
}
hostsSystems.put(result.getName(), result);
return result;
}
/**
* Adds a VM instance to the inventory based on given properties.
*
* @return the created VM instance
*/
public VMwareVirtualMachine addVirtualMachine(
List<DynamicProperty> properties, ManagedObjectAccessor serviceUtil)
throws Exception {
if (properties == null || properties.size() == 0) {
return null;
}
VMwareVirtualMachine result = new VMwareVirtualMachine();
for (DynamicProperty dp : properties) {
String key = dp.getName();
if ("name".equals(key) && dp.getVal() != null) {
result.setName(dp.getVal().toString());
} else if ("summary.config.memorySizeMB".equals(key)
&& dp.getVal() != null) {
result.setMemorySizeMB(
Integer.parseInt(dp.getVal().toString()));
} else if ("summary.config.numCpu".equals(key)
&& dp.getVal() != null) {
result.setNumCpu(Integer.parseInt(dp.getVal().toString()));
} else if ("runtime.host".equals(key)) {
ManagedObjectReference mor = (ManagedObjectReference) dp
.getVal();
Object cacheKey = mor == null ? null : mor.getValue();
if (!hostCache.containsKey(cacheKey)) {
Object name = serviceUtil.getDynamicProperty(mor, "name");
if (name != null) {
hostCache.put(cacheKey, name.toString());
}
}
result.setHostName(hostCache.get(cacheKey));
}
}
if (result.getHostName() != null) {
vms.add(result);
} else {
logger.warn("Cannot determine host system for VM '"
+ result.getName()
+ "'. Check whether configured VMware API user host rights to access the host system.");
}
return result;
}
/**
* Initializes the allocation data of the host by summing up all configured
* (not the actual used) resources of all VMs deployed on each host.
*
*/
public void initialize() {
for (VMwareHost hostSystem : hostsSystems.values()) {
hostSystem.setAllocatedMemoryMB(0);
hostSystem.setAllocatedCPUs(0);
hostSystem.setAllocatedVMs(0);
}
for (VMwareVirtualMachine vm : vms) {
VMwareHost hostSystem = hostsSystems.get(vm.getHostName());
if (hostSystem != null) {
long vmMemMBytes = vm.getMemorySizeMB();
hostSystem.setAllocatedMemoryMB(
hostSystem.getAllocatedMemoryMB() + vmMemMBytes);
hostSystem.setAllocatedCPUs(
hostSystem.getAllocatedCPUs() + vm.getNumCpu());
hostSystem.setAllocatedVMs(hostSystem.getAllocatedVMs() + 1);
}
}
}
public VMwareStorage getStorage(String name) {
return storages.get(name);
}
public List<VMwareStorage> getStorageByHost(String host) {
return storageByHost.get(host);
}
public VMwareHost getHost(String name) {
return hostsSystems.get(name);
}
public Collection<VMwareHost> getHosts() {
return new ArrayList<VMwareHost>(hostsSystems.values());
}
/**
* Reset the enabling information for all hosts and storages within the
* inventory. The resources have late to be enabled one by when when reading
* the configuration.
*/
public void disableHostsAndStorages() {
for (VMwareHost host : hostsSystems.values()) {
host.setEnabled(false);
}
for (VMwareStorage storage : storages.values()) {
storage.setEnabled(false);
}
}
}
| apache-2.0 |
enjoy0924/hibernate-sample | src/main/java/com/allere/hibernate/utils/JacksonJsonUtil.java | 3046 | package com.allere.hibernate.utils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Json转换工具
*
* Created by G_dragon on 2015/7/24.
*/
public class JacksonJsonUtil {
private static ObjectMapper mapper;
/**
* 获取ObjectMapper实例
* @param createNew 方式:true,新实例;false,存在的mapper实例
* @return
*/
public static synchronized ObjectMapper getMapperInstance(boolean createNew) {
if (createNew) {
return new ObjectMapper();
} else if (mapper == null) {
mapper = new ObjectMapper();
}
return mapper;
}
/**
* 将java对象转换成json字符串
* @param obj 准备转换的对象
* @return json字符串
* @throws Exception
*/
public static String beanToJson(Object obj) throws Exception {
try {
ObjectMapper objectMapper = getMapperInstance(false);
String json =objectMapper.writeValueAsString(obj);
return json;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* 将java对象转换成json字符串
* @param obj 准备转换的对象
* @param createNew ObjectMapper实例方式:true,新实例;false,存在的mapper实例
* @return json字符串
* @throws Exception
*/
public static String beanToJson(Object obj,Boolean createNew) throws Exception {
try {
ObjectMapper objectMapper = getMapperInstance(createNew);
String json =objectMapper.writeValueAsString(obj);
return json;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* 将json字符串转换成java对象
* @param json 准备转换的json字符串
* @param cls 准备转换的类
* @return
* @throws Exception
*/
public static Object jsonToBean(String json, Class<?> cls) throws Exception {
try {
ObjectMapper objectMapper = getMapperInstance(false);
Object vo = objectMapper.readValue(json, cls);
return vo;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* 将json字符串转换成java对象
* @param json 准备转换的json字符串
* @param cls 准备转换的类
* @param createNew ObjectMapper实例方式:true,新实例;false,存在的mapper实例
* @return
* @throws Exception
*/
public static <T> T jsonToBean(String json, Class<T> cls,Boolean createNew) throws Exception {
try {
ObjectMapper objectMapper = getMapperInstance(createNew);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
T vo = objectMapper.readValue(json, cls);
return vo;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
} | apache-2.0 |
chris6k/mk | src/com/jk/makemoney/services/TaskService.java | 1956 | package com.jk.makemoney.services;
import android.util.Log;
import com.jk.makemoney.utils.Constants;
import com.jk.makemoney.utils.MkHttp;
import com.jk.makemoney.utils.UserProfile;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author chris.xue
* 任务service层
*/
public class TaskService {
private static final String TAG = "TaskService";
private static final String TASK_BASE = Constants.API_HOST + "/task";
private static final String FINISH_ENDPOINT = TASK_BASE + "/finish";
/**
* 任务完成
*
* @param platformId
* @param taskId
* @param amount
*/
public boolean finishTask(int platformId, String taskId, int amount, String taskName) {
HttpPost post = new HttpPost(FINISH_ENDPOINT);
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(5);
params.add(new BasicNameValuePair("userId", UserProfile.getInstance().getUserId()));
params.add(new BasicNameValuePair("platformId", String.valueOf(platformId)));
params.add(new BasicNameValuePair("taskId", taskId));
params.add(new BasicNameValuePair("amount", String.valueOf(amount)));
params.add(new BasicNameValuePair("taskName", taskName));
SecurityService.appendAuthHeader(post, null);
post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse response = MkHttp.getInstance().send(post).get(1, TimeUnit.MINUTES);
return response.getStatusLine().getStatusCode() == 200;
} catch (Exception e) {
Log.e(TAG, "finish task failed", e);
}
return false;
}
}
| apache-2.0 |
dhakehurst/net.akehurst.application.framework.examples | net.akehurst.app.helloWorld/application/desktop.console/src/main/java/helloWorld/application/desktop/console/HelloWorldConsoleApplication.java | 2193 | /**
* Copyright (C) 2016 Dr. David H. Akehurst (http://dr.david.h.akehurst.net)
*
* 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 helloWorld.application.desktop.console;
import helloWorld.computational.greeter.Greeter;
import helloWorld.engineering.channel.user.UserProxyToText;
import net.akehurst.application.framework.common.annotations.declaration.Application;
import net.akehurst.application.framework.common.annotations.instance.ComponentInstance;
import net.akehurst.application.framework.common.annotations.instance.ServiceInstance;
import net.akehurst.application.framework.realisation.AbstractApplication;
import net.akehurst.application.framework.service.configuration.file.HJsonConfigurationService;
import net.akehurst.application.framework.technology.filesystem.StandardFilesystem;
import net.akehurst.application.framework.technology.gui.console.StandardStreams;
import net.akehurst.application.framework.technology.log4j.Log4JLogger;
@Application
public class HelloWorldConsoleApplication extends AbstractApplication {
public HelloWorldConsoleApplication(final String id) {
super(id);
}
@ServiceInstance
Log4JLogger logger;
@ServiceInstance
StandardFilesystem fs;
@ServiceInstance
HJsonConfigurationService configuration;
@ComponentInstance
// @Connect(port="portUser", to="proxy.portUser")
Greeter greeter;
@ComponentInstance
UserProxyToText proxy;
@ComponentInstance
StandardStreams console;
@Override
public void afConnectParts() {
this.greeter.portUser().connect(this.proxy.portUser());
this.proxy.portConsole().connect(this.console.portOutput());
}
}
| apache-2.0 |
gpelaez/beacons-plugin | src/android/LocationManagerService.java | 3134 | package me.gpelaez.cordova.plugins.ibeacon;
import java.util.HashSet;
import java.util.Set;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
public class LocationManagerService implements LocationListener {
public static final int INTERFAL_TIME = 60000;
public static final int MIN_DISTANCE = 10;
static final String TAG = LocationManagerService.class.getSimpleName();
static final String PROXIMITY_ALERT_INTENT = "LocationManagerProximityAlert";
private LocationManager locationManager;
private Set<LocationChangedListener> listeners = new HashSet<LocationChangedListener>();
private final Activity activity;
private Boolean isListening = false;
public LocationManagerService(Activity activity) {
this.activity = activity;
locationManager = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
}
public void addRegion(String id, double latitude, double longitude,
float radius) {
Log.d(TAG, "Adding Proximity Alert: id: " + id + ", lat: " + latitude
+ ", lon: " + longitude + ", radius: " + longitude);
PendingIntent proximityIntent = createIntent(id);
locationManager.addProximityAlert(latitude, longitude, radius, -1,
proximityIntent);
}
public void removeRegion(String id) {
PendingIntent proximityIntent = createIntent(id);
locationManager.removeProximityAlert(proximityIntent);
}
private PendingIntent createIntent(String id) {
Intent intent = new Intent(PROXIMITY_ALERT_INTENT);
intent.putExtra("id", id);
return PendingIntent.getBroadcast(activity, 0, intent,
FLAG_ACTIVITY_NEW_TASK);
}
private void startListening() {
isListening = true;
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
INTERFAL_TIME, MIN_DISTANCE, this);
}
public void addLocationChangedListener(LocationChangedListener listener) {
this.listeners.add(listener);
if (!isListening) {
startListening();
}
}
public void removeLocationChangedListener(LocationChangedListener listener) {
this.listeners.remove(listener);
if (this.listeners.size() == 0) {
locationManager.removeUpdates(this);
isListening = false;
}
}
@Override
public void onLocationChanged(Location location) {
// TODO Location change
for (LocationChangedListener changedListener : listeners) {
changedListener.onLocationChanged(location);
}
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
Deepaksoftvision/GPC_POC | src/main/java/controllers/TestHelper.java | 8723 | /**
*
*/
package controllers;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
/**
*/
public class TestHelper extends TestController
{
/* To get the Website Name */
public String getUrlTitle() throws Exception
{
URL aURL = new URL(WebsiteURL);
String WebName = aURL.getHost();
String WebSiteName = WebName.toUpperCase();
return WebSiteName;
}
/* To Press ENTER Key using Robot */
public void hitEnter() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_ENTER);
re.keyRelease(KeyEvent.VK_ENTER);
}
/* To Press BACKSPACE Key using Robot */
public void hitBackspace() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_BACK_SPACE);
re.keyRelease(KeyEvent.VK_BACK_SPACE);
}
/* To Press DELETE Key using Robot */
public void hitDelete() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_DELETE);
re.keyRelease(KeyEvent.VK_DELETE);
}
/* To Select all the Text/Web Elements using ROBOT */
public void selectAll() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_CONTROL);
re.keyPress(KeyEvent.VK_A);
re.keyRelease(KeyEvent.VK_CONTROL);
re.keyRelease(KeyEvent.VK_A);
}
/* To Copy all the Selected Text/Web Elements using ROBOT */
public void copyAll() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_CONTROL);
re.keyPress(KeyEvent.VK_C);
re.keyRelease(KeyEvent.VK_CONTROL);
re.keyRelease(KeyEvent.VK_C);
}
/* To Paste all the Selected Text/Web Elements using ROBOT */
public void pasteAll() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_CONTROL);
re.keyPress(KeyEvent.VK_V);
re.keyRelease(KeyEvent.VK_CONTROL);
re.keyRelease(KeyEvent.VK_V);
}
/* To Capture Screenshot(Replaces if already exists) */
/*
* Also, Make sure that the automation in running in the foreground to
* capture the Image of the Browser. Else, It'll capture the open Window
*/
public void robotScreenCapture(String robotImageName) throws Exception
{
re = new Robot();
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = re.createScreenCapture(area);
// Save as PNG
File file = new File(robotImageName);
if (file.exists()) {
file.delete();
}
ImageIO.write(bufferedImage, "png", file);
}
/* To ZoomOut */
public void robotZoomOut() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_CONTROL);
re.keyPress(KeyEvent.VK_SUBTRACT);
re.keyRelease(KeyEvent.VK_SUBTRACT);
re.keyRelease(KeyEvent.VK_CONTROL);
}
/* To ZoomIn */
public void robotZoomIn() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_CONTROL);
re.keyPress(KeyEvent.VK_ADD);
re.keyRelease(KeyEvent.VK_ADD);
re.keyRelease(KeyEvent.VK_CONTROL);
}
/* To ScrollUp using ROBOT */
public void robotScrollUp() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_PAGE_UP);
re.keyRelease(KeyEvent.VK_PAGE_UP);
}
/* To ScrollDown using ROBOT */
public void robotScrollDown() throws Exception
{
re = new Robot();
re.keyPress(KeyEvent.VK_PAGE_DOWN);
re.keyRelease(KeyEvent.VK_PAGE_DOWN);
}
/* To ScrollUp using JavaScript Executor */
public void scrollUp() throws Exception
{
((JavascriptExecutor) driver).executeScript("scroll(0, -100);");
}
/* To ScrollDown using JavaScript Executor */
public void scrollDown() throws Exception
{
((JavascriptExecutor) driver).executeScript("scroll(0, 100);");
}
/* To Move cursor to the Desired Location */
public void moveCursor(int X_Position, int Y_Position) throws Exception
{
re.mouseMove(X_Position, Y_Position);
}
/* To Accept the Alert Dialog Message */
public void alertAccept() throws Exception
{
al = driver.switchTo().alert();
al.accept();
}
/* To Dismiss the Alert Dialog Message */
public void alertDismiss() throws Exception
{
al = driver.switchTo().alert();
al.dismiss();
}
/* To Get the Alert Messages */
public String getAlertText() throws Exception
{
al = driver.switchTo().alert();
String text = al.getText();
Thread.sleep(2000);
alertAccept();
return text;
}
/* To Upload a File using JAVA AWT ROBOT */
public void fileUpload(String FileToUpload) throws Exception
{
Thread.sleep(5000);
StringSelection filetocopy = new StringSelection(FileToUpload);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filetocopy, null);
Thread.sleep(1000);
re = new Robot();
re.keyPress(KeyEvent.VK_CONTROL);
re.keyPress(KeyEvent.VK_V);
re.keyRelease(KeyEvent.VK_V);
re.keyRelease(KeyEvent.VK_CONTROL);
re.keyPress(KeyEvent.VK_ENTER);
re.keyRelease(KeyEvent.VK_ENTER);
}
/* To Perform a WebAction of Mouse Over */
public void mousehover(WebElement element)
{
ac = new Actions(driver);
ac.moveToElement(element).build().perform();
}
/* To Perform Select Option by Visible Text */
public void selectByVisibleText(WebElement element, String value)
{
se = new Select(element);
se.selectByVisibleText(value);
}
/* To Perform Select Option by Index */
public void selectByIndex(WebElement element, int value)
{
se = new Select(element);
se.selectByIndex(value);
}
/* To Perform Select Option by Value */
public void selectByValue(WebElement element, String value)
{
se = new Select(element);
se.selectByValue(value);
}
/* To click a certain Web Element */
public void click(WebElement element)
{
element.click();
}
/* To click a certain Web Element using DOM/ JavaScript Executor */
public void JSclick(WebElement element)
{
((JavascriptExecutor) driver).executeScript("return arguments[0].click();", element);
}
/* To Type at the specified location */
public void sendKeys(WebElement element, String value)
{
element.sendKeys(value);
}
/* To Clear the content in the input location */
public void clear(WebElement element)
{
element.clear();
}
/* To Drag and Drop from Source Locator to Destination Locator */
public void dragandDrop(WebElement Source, WebElement Destination)
{
ac = new Actions(driver);
ac.dragAndDrop(Source, Destination);
}
/*To Drag from the given WebElement Location and Drop at the given WebElement location */
public void dragandDropTo(WebElement Source, int XOffset, int YOffset) throws Exception
{
ac = new Actions(driver);
ac.dragAndDropBy(Source, XOffset, YOffset);
}
/*To Open a Page in New Tab */
public void rightClick(WebElement element)
{
ac = new Actions(driver);
ac.contextClick(element);
ac.build().perform();
}
/*To Close Current Tab */
public void closeCurrentTab()
{
driver.close();
}
/*To Perform Click and Hold Action */
public void clickAndHold(WebElement element)
{
ac = new Actions(driver);
ac.clickAndHold(element);
ac.build().perform();
}
/*To Perform Click and Hold Action */
public void doubleClick(WebElement element)
{
ac = new Actions(driver);
ac.doubleClick(element);
ac.build().perform();
}
/*To Switch To Frame By Index */
public void switchToFrameByIndex(int index) throws Exception
{
driver.switchTo().frame(index);
}
/*To Switch To Frame By Frame Name */
public void switchToFrameByFrameName(String frameName) throws Exception
{
driver.switchTo().frame(frameName);
}
/*To Switch To Frame By Web Element */
public void switchToFrameByWebElement(WebElement element) throws Exception
{
driver.switchTo().frame(element);
}
/*To Switch out of a Frame */
public void switchOutOfFrame() throws Exception
{
driver.switchTo().defaultContent();
}
/*To Get Tooltip Text */
public String getTooltipText(WebElement element)
{
String tooltipText = element.getAttribute("title").trim();
return tooltipText;
}
/*To Close all Tabs/Windows except the First Tab */
public void closeAllTabsExceptFirst()
{
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
for(int i=1;i<tabs.size();i++)
{
driver.switchTo().window(tabs.get(i));
driver.close();
}
driver.switchTo().window(tabs.get(0));
}
/*To Print all the Windows */
public void printAllTheWindows()
{
ArrayList<String> al = new ArrayList<String>(driver.getWindowHandles());
for(String window : al)
{
System.out.println(window);
}
}
}
| apache-2.0 |
aws/aws-lambda-java-libs | aws-lambda-java-runtime-interface-client/src/main/java/com/amazonaws/services/lambda/runtime/api/client/XRayErrorCause.java | 3587 | /* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. */
package com.amazonaws.services.lambda.runtime.api.client;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* helper class for serializing an exception in the format expected by XRay's web console.
*/
public class XRayErrorCause {
private final String working_directory;
private final Collection<XRayException> exceptions;
private final Collection<String> paths;
public XRayErrorCause(Throwable throwable) {
working_directory = System.getProperty("user.dir");
exceptions = Collections.unmodifiableCollection(Collections.singletonList(new XRayException(throwable)));
paths = Collections.unmodifiableCollection(
Arrays.stream(throwable.getStackTrace())
.map(XRayErrorCause::determineFileName)
.collect(Collectors.toSet()));
}
public String getWorking_directory() {
return working_directory;
}
public Collection<XRayException> getExceptions() {
return exceptions;
}
public Collection<String> getPaths() {
return paths;
}
/**
* This method provides compatibility between Java 8 and Java 11 in determining the fileName of the class in the
* StackTraceElement.
*
* If the fileName property of the StackTraceElement is null (as it can be for native methods in Java 11), it
* constructs it using the className by stripping out the package and appending ".java".
*/
private static String determineFileName(StackTraceElement e) {
String fileName = null;
if(e.getFileName() != null) {
fileName = e.getFileName();
}
if(fileName == null) {
String className = e.getClassName();
fileName = className == null ? null : className.substring(className.lastIndexOf('.') + 1) + ".java";
}
return fileName;
}
public static class XRayException {
private final String message;
private final String type;
private final List<StackElement> stack;
public XRayException(Throwable throwable) {
this.message = throwable.getMessage();
this.type = throwable.getClass().getName();
this.stack = Arrays.stream(throwable.getStackTrace()).map(this::toStackElement).collect(Collectors.toList());
}
private StackElement toStackElement(StackTraceElement e) {
return new StackElement(
e.getMethodName(),
determineFileName(e),
e.getLineNumber());
}
public String getMessage() {
return message;
}
public String getType() {
return type;
}
public List<StackElement> getStack() {
return stack;
}
public static class StackElement {
private final String label;
private final String path;
private final int line;
private StackElement(String label, String path, int line) {
this.label = label;
this.path = path;
this.line = line;
}
public String getLabel() {
return label;
}
public String getPath() {
return path;
}
public int getLine() {
return line;
}
}
}
}
| apache-2.0 |
dunyuling/javabase | src/main/java/com/lhg/test/gtan/begin/junit/Junit_01.java | 1250 | package com.lhg.test.gtan.begin.junit;
import java.util.*;
public class Junit_01 {
public static void main(String args[]) {
Junit_01 junit_01 = new Junit_01();
List<Data> dataList = junit_01.init();
junit_01.sort(dataList);
}
public List<Data> init() {
List<Data> dataList = new ArrayList<Data>();
String[] dataArr = {"2.7.8","2.7.8-SNAPSHOT","2.7.8-1","2.4.4-SNAPSHOT","2.7.8-2","2.7.8.RC1",
"2.7.8.RC2","2.8.9-1","2.4.3.RC2"};
int i = 0;
for(i=0;i<dataArr.length;i++) {
Data data = new Data();
data.setVersion(dataArr[i]);
dataList.add(data);
}
return dataList;
}
public void sort(List<Data> dataList) {
Object[] dataArr1 = dataList.toArray();
int i = 0,j = 0;
Sort sort = new Sort();
for(i=0;i<dataArr1.length;i++) {
for(j=i+1;j<dataArr1.length;j++) {
String version_01 = ((Data)dataArr1[i]).getVersion().trim();
String version_02 = ((Data)dataArr1[j]).getVersion().trim();
sort.isSameKind(dataArr1,i,j,version_01,version_02);
}
}
for(i=0;i<dataArr1.length;i++) {
out(((Data)dataArr1[i]).getVersion());
}
}
public static void out(String str) {
System.out.println(str);
}
}
| apache-2.0 |
freeVM/freeVM | enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/rmi/basicregistry/Client.java | 1767 | /*
* 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.harmony.test.func.api.java.rmi.basicregistry;
import java.rmi.Naming;
import org.apache.harmony.test.func.api.java.rmi.share.ServerInterface;
public class Client {
private ServerInterface server;
private final int clientNumber;
private final int creatorNumber;
public Client(int givenCreatorNumber, int givenClientNumber) {
this.clientNumber = givenClientNumber;
this.creatorNumber = givenCreatorNumber;
}
public void lookUpServer(String serverName) throws Throwable {
server = (ServerInterface) Naming.lookup(serverName);
}
public boolean verifyRemoteMethod() throws Throwable {
String s = server.remoteMethod("number " + clientNumber
+ ", my creator number is " + creatorNumber);
System.err.println(s);
return ("I am server number " + clientNumber
+ ", my creator number is " + creatorNumber).equals(s);
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-documentai/v1beta3/1.31.0/com/google/api/services/documentai/v1beta3/model/GoogleCloudDocumentaiV1beta3UndeployProcessorVersionMetadata.java | 2630 | /*
* 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.documentai.v1beta3.model;
/**
* The long running operation metadata for the undeploy processor version method.
*
* <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 Document AI 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 GoogleCloudDocumentaiV1beta3UndeployProcessorVersionMetadata extends com.google.api.client.json.GenericJson {
/**
* The basic metadata of the long running operation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudDocumentaiV1beta3CommonOperationMetadata commonMetadata;
/**
* The basic metadata of the long running operation.
* @return value or {@code null} for none
*/
public GoogleCloudDocumentaiV1beta3CommonOperationMetadata getCommonMetadata() {
return commonMetadata;
}
/**
* The basic metadata of the long running operation.
* @param commonMetadata commonMetadata or {@code null} for none
*/
public GoogleCloudDocumentaiV1beta3UndeployProcessorVersionMetadata setCommonMetadata(GoogleCloudDocumentaiV1beta3CommonOperationMetadata commonMetadata) {
this.commonMetadata = commonMetadata;
return this;
}
@Override
public GoogleCloudDocumentaiV1beta3UndeployProcessorVersionMetadata set(String fieldName, Object value) {
return (GoogleCloudDocumentaiV1beta3UndeployProcessorVersionMetadata) super.set(fieldName, value);
}
@Override
public GoogleCloudDocumentaiV1beta3UndeployProcessorVersionMetadata clone() {
return (GoogleCloudDocumentaiV1beta3UndeployProcessorVersionMetadata) super.clone();
}
}
| apache-2.0 |
toobs/Toobs | trunk/PresFramework/src/main/java/org/toobsframework/pres/layout/manager/ComponentLayoutManager.java | 14169 | /*
* This file is licensed to the Toobs Framework Group under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The Toobs Framework Group 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.toobsframework.pres.layout.manager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.toobsframework.pres.layout.ComponentLayoutInitializationException;
import org.toobsframework.pres.layout.ComponentLayoutNotFoundException;
import org.toobsframework.pres.layout.ComponentRef;
import org.toobsframework.pres.base.XslManagerBase;
import org.toobsframework.pres.component.Component;
import org.toobsframework.pres.component.ComponentInitializationException;
import org.toobsframework.pres.component.ComponentNotFoundException;
import org.toobsframework.pres.component.config.ContentType;
import org.toobsframework.pres.component.manager.ComponentManager;
import org.toobsframework.pres.layout.RuntimeLayout;
import org.toobsframework.pres.layout.RuntimeLayoutConfig;
import org.toobsframework.pres.layout.config.Layout;
import org.toobsframework.pres.layout.config.Layouts;
import org.toobsframework.pres.layout.config.Section;
import org.toobsframework.pres.util.PresConstants;
import org.toobsframework.transformpipeline.domain.IXMLTransformer;
import org.toobsframework.exception.PermissionException;
public final class ComponentLayoutManager extends XslManagerBase implements IComponentLayoutManager {
private ComponentManager componentManager;
private Map<String, RuntimeLayout> runtimeRegistry;
private Map<String, LayoutConfigHolder> configRegistry;
private ComponentLayoutManager() throws ComponentLayoutInitializationException {
log.info("Constructing new ComponentLayoutManager");
}
// Read from config file
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
configRegistry = new LinkedHashMap<String, LayoutConfigHolder>();
this.insertConfigFile(PresConstants.TOOBS_INTERNAL_ERROR_CONFIG_LAYOUTS);
loadConfig(Layouts.class);
configureRegistry();
}
public RuntimeLayout getLayout(String layoutId) throws ComponentLayoutNotFoundException, ComponentLayoutInitializationException {
if (isDoReload()) {
Date initStart = new Date();
this.loadConfig(Layouts.class);
configureRegistry();
Date initEnd = new Date();
log.info("Init Time: " + (initEnd.getTime() - initStart.getTime()));
}
if (!runtimeRegistry.containsKey(layoutId)) {
throw new ComponentLayoutNotFoundException(layoutId);
}
return (RuntimeLayout) runtimeRegistry.get(layoutId);
}
public RuntimeLayout getLayout(PermissionException permissionException)
throws ComponentLayoutNotFoundException, ComponentLayoutInitializationException {
String objectErrorPage = permissionException.getAction() + permissionException.getObjectTypeName();
if (!runtimeRegistry.containsKey(objectErrorPage)) {
log.info("Permission Error page " + objectErrorPage + " not defined");
return null;
}
return (RuntimeLayout) runtimeRegistry.get(objectErrorPage);
}
@Override
protected void registerConfiguration(Object object, String fileName) {
Layouts componentLayoutConfig = (Layouts) object;
Layout[] layouts = componentLayoutConfig.getLayout();
if ((layouts != null) && (layouts.length > 0)) {
for (int j = 0; j < layouts.length; j ++) {
try {
if (configRegistry.containsKey(layouts[j].getId()) && !isInitDone()) {
log.warn("Overriding layout with Id: " + layouts[j].getId());
}
configRegistry.put(layouts[j].getId(), new LayoutConfigHolder(layouts[j]));
} catch (Exception e) {
log.warn("Error configuring and registering component " + layouts[j].getId() + ": " + e.getMessage(), e);
}
}
}
}
private void configureRegistry() throws ComponentLayoutInitializationException {
runtimeRegistry = new HashMap<String, RuntimeLayout>();
for (Map.Entry<String,LayoutConfigHolder> configEntry : configRegistry.entrySet()) {
LayoutConfigHolder holder = configEntry.getValue();
if (!holder.configured || !runtimeRegistry.containsKey(configEntry.getKey())) {
processLayoutConfig(holder, null);
}
}
if (!isDoReload()) {
configRegistry.clear();
configRegistry = null;
}
}
private void processLayoutConfig(LayoutConfigHolder configHolder, String childName) throws ComponentLayoutInitializationException {
String extend = configHolder.layout.getExtend();
// Check to see if there is a parent and it has been initialized
if (extend != null) {
LayoutConfigHolder parentConfigHolder = configRegistry.get(extend);
if (parentConfigHolder != null) {
if (!runtimeRegistry.containsKey(extend)) {
processLayoutConfig(parentConfigHolder, extend);
}
parentConfigHolder.addChild(extend);
} else {
log.warn("Extension layout " + extend + " not found for layout " + configHolder.layout.getId());
}
}
RuntimeLayout runtimeLayout = new RuntimeLayout();
configureLayout(configHolder.layout, runtimeLayout, defaultTransformer, htmlTransformer, xmlTransformer);
runtimeRegistry.put(runtimeLayout.getId(), runtimeLayout);
configHolder.configured = true;
if (childName != null) {
configHolder.addChild(extend);
}
}
public void configureLayout(
Layout compLayout,
RuntimeLayout layout,
IXMLTransformer defaultTransformer,
IXMLTransformer htmlTransformer,
IXMLTransformer xmlTransformer) throws ComponentLayoutInitializationException {
RuntimeLayoutConfig layoutConfig = new RuntimeLayoutConfig();
List<Section> tempSections = new ArrayList<Section>();
// Inherited from extended definition
String extendStr = compLayout.getExtend();
if (extendStr != null) {
String[] extSplit = extendStr.split(";");
for (int ext = 0; ext < extSplit.length; ext++) {
String extension = extSplit[ext];
RuntimeLayout extend = runtimeRegistry.get(extension);
if (extend == null) {
log.error("The Layout extension " + extension + " for " + compLayout.getId() +
" could not be located in the registry.\n"
+ "Check the spelling and case of the extends property and ensure it is defined before\n"
+ "the dependent templates");
throw new ComponentLayoutInitializationException("Missing extension " + extension + " for " + compLayout.getId());
}
RuntimeLayoutConfig extendConfig = extend.getConfig();
if (extend == null) {
throw new ComponentLayoutInitializationException("Layout " + compLayout.getId() +
" cannot extend " + extension + " cause it does not exist or has not yet been loaded");
}
if (extendConfig.getAllParams() != null) {
layoutConfig.addParam(extendConfig.getAllParams());
}
if (extendConfig.getAllTransformParams() != null) {
layoutConfig.addTransformParam(extendConfig.getAllTransformParams());
}
if (extendConfig.getAllSections() != null) {
tempSections.addAll(extendConfig.getAllSections());
}
//layoutConfig.addSection(extendConfig.getAllSections());
layoutConfig.setNoAccessLayout(extendConfig.getNoAccessLayout());
//layout.addTransform(extend.getAllTransforms());
layout.getTransforms().putAll(extend.getTransforms());
//layout.setUseComponentScan(extend.isUseComponentScan());
//layout.setEmbedded(extend.isEmbedded());
}
}
if (compLayout.getParameters() != null) {
layoutConfig.addParam(compLayout.getParameters().getParameter());
}
if (compLayout.getTransformParameters() != null) {
layoutConfig.addTransformParam(compLayout.getTransformParameters().getParameter());
}
for (Section sec : compLayout.getSection()) {
tempSections.add(sortComponents(sec));
}
sortSections(tempSections);
layoutConfig.addSection(tempSections);
for (Section section : tempSections) {
for (int i = 0; i < section.getComponentRefCount(); i++) {
org.toobsframework.pres.layout.config.ComponentRef componentRef = section.getComponentRef(i);
try {
Component component = componentManager.getComponent(componentRef.getComponentId(), true);
if (componentRef.getLoader().toString().equalsIgnoreCase("direct")) {
layoutConfig.addComponentRef(new ComponentRef(component, componentRef.getParameters() ) );
}
} catch (ComponentNotFoundException e) {
throw new ComponentLayoutInitializationException(
"Layout " + compLayout.getId() + " could not be initialized. Referenced component " +
componentRef.getComponentId() + " could not be found");
} catch (ComponentInitializationException e) {
throw new ComponentLayoutInitializationException(
"Layout " + compLayout.getId() + " could not be initialized. Referenced component " +
componentRef.getComponentId() + " failed to initialize: " + e.getMessage(), e);
}
}
}
//layoutConfig.addSection(compLayout.getSection());
if (compLayout.getNoAccessLayout() != null) {
layoutConfig.setNoAccessLayout(compLayout.getNoAccessLayout());
}
layout.setId(compLayout.getId());
//layout.setUseComponentScan(compLayout.getUseComponentScan() || layout.isEmbedded());
//layout.setEmbedded(compLayout.getEmbedded() || layout.isEmbedded());
//Set component pipeline properties.
if (compLayout.getPipeline() != null) {
Enumeration<ContentType> contentTypeEnum = compLayout.getPipeline().enumerateContentType();
while (contentTypeEnum.hasMoreElements()) {
List<org.toobsframework.pres.component.Transform> theseTransforms = new ArrayList<org.toobsframework.pres.component.Transform>();
ContentType thisContentType = (ContentType) contentTypeEnum.nextElement();
Enumeration<org.toobsframework.pres.component.config.Transform> transEnum = thisContentType.enumerateTransform();
while (transEnum.hasMoreElements()) {
org.toobsframework.pres.component.config.Transform thisTransformConfig = (org.toobsframework.pres.component.config.Transform) transEnum.nextElement();
org.toobsframework.pres.component.Transform thisTransform = new org.toobsframework.pres.component.Transform();
thisTransform.setTransformName(thisTransformConfig.getName());
thisTransform.setTransformParams(thisTransformConfig.getParameters());
theseTransforms.add(thisTransform);
}
String[] ctSplit = thisContentType.getContentType().split(";");
for (int ct = 0; ct < ctSplit.length; ct++) {
layout.getTransforms().put(ctSplit[ct], theseTransforms);
}
}
}
/*
if (compLayout.getTransformCount() > 0) {
layout.getTransforms().clear();
for (int t = 0; t < compLayout.getTransformCount(); t++) {
layout.addTransform(new Transform(compLayout.getTransform(t)));
}
}
*/
layout.setConfig(layoutConfig);
layout.setDoItRef(compLayout.getDoItRef());
layout.setHtmlTransformer(htmlTransformer);
layout.setDefaultTransformer(defaultTransformer);
layout.setXmlTransformer(xmlTransformer);
if (log.isDebugEnabled()) {
log.debug("Layout " + compLayout.getId() + " xml " + layout.getLayoutXml());
}
}
private static Section sortComponents(Section sec) {
List<org.toobsframework.pres.layout.config.ComponentRef> compRefs = Arrays.asList( sec.getComponentRef() );
Collections.sort(compRefs, new Comparator<org.toobsframework.pres.layout.config.ComponentRef>() {
public int compare(org.toobsframework.pres.layout.config.ComponentRef o1, org.toobsframework.pres.layout.config.ComponentRef o2) {
return o1.getOrder() - o2.getOrder();
}
});
org.toobsframework.pres.layout.config.ComponentRef[] sortedRefs = new org.toobsframework.pres.layout.config.ComponentRef[compRefs.size()];
sec.setComponentRef(compRefs.toArray(sortedRefs));
return sec;
}
private static void sortSections(List<Section> tempSections) {
Collections.sort(tempSections, new Comparator<Section>() {
public int compare(Section o1, Section o2) {
return o1.getOrder() - o2.getOrder();
}
});
}
public void setComponentManager(ComponentManager componentManager) {
this.componentManager = componentManager;
}
private class LayoutConfigHolder {
boolean configured;
Layout layout;
Set<String> children;
private LayoutConfigHolder(Layout layout) {
this.layout = layout;
}
public Set<String> getChildren() {
return children;
}
public void addChild(String child) {
if (children == null) {
children = new HashSet<String>();
}
this.children.add(child);
}
public boolean isConfigured() {
return configured;
}
public void setConfigured(boolean configured) {
this.configured = configured;
}
}
} | apache-2.0 |
KleeGroup/vertigo-struts2 | src/main/java/io/vertigo/struts2/resources/Resources.java | 1050 | /**
* vertigo - simple java starter
*
* Copyright (C) 2013-2017, KleeGroup, direction.technique@kleegroup.com (http://www.kleegroup.com)
* KleeGroup, Centre d'affaire la Boursidiere - BP 159 - 92357 Le Plessis Robinson Cedex - France
*
* 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.vertigo.struts2.resources;
import io.vertigo.lang.MessageKey;
/**
* Ressources générales.
*
* @author mlaroche
*/
public enum Resources implements MessageKey {
/** {0} : le champ est obligatoire. */
CHAMP_OBLIGATOIRE,
}
| apache-2.0 |
ItudeMobile/itude-mobile-web-mobbl | src/main/java/com/itude/mobile/web/annotations/PageQualifier.java | 1014 | /*
* (C) Copyright Itude Mobile B.V., The Netherlands
*
* Licimport javax.enterprise.util.AnnotationLiteral;
"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.itude.mobile.web.annotations;
import javax.enterprise.util.AnnotationLiteral;
public class PageQualifier extends AnnotationLiteral<ForPage> implements ForPage
{
private static final long serialVersionUID = 1L;
private final String _value;
public PageQualifier(String value)
{
_value = value;
}
@Override
public String value()
{
return _value;
}
}
| apache-2.0 |
z-yuxie/yuxie-TGD | tgd-interface/src/main/java/com/yuxie/tgd/pojo/dto/SelectObjectList.java | 1916 | package com.yuxie.tgd.pojo.dto;
/**
* Created by 147356 on 2017/4/25.
*/
public class SelectObjectList {
//序列化ID
private static final long serialVersionUID = 1L;
//用户ID
private Long userId;
//父对象ID
private Long parentObjectId;
//父对象版本
private Integer parentObjectVersion;
//对象类型
private Integer objectType;
//获取状态种类
private Integer listType;
//排序规则
private Integer sortType;
@Override
public String toString() {
return "SelectObjectList{" +
"userId=" + userId +
", parentObjectId=" + parentObjectId +
", parentObjectVersion=" + parentObjectVersion +
", objectType=" + objectType +
", listType=" + listType +
", sortType=" + sortType +
'}';
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getParentObjectId() {
return parentObjectId;
}
public void setParentObjectId(Long parentObjectId) {
this.parentObjectId = parentObjectId;
}
public Integer getParentObjectVersion() {
return parentObjectVersion;
}
public void setParentObjectVersion(Integer parentObjectVersion) {
this.parentObjectVersion = parentObjectVersion;
}
public Integer getObjectType() {
return objectType;
}
public void setObjectType(Integer objectType) {
this.objectType = objectType;
}
public Integer getListType() {
return listType;
}
public void setListType(Integer listType) {
this.listType = listType;
}
public Integer getSortType() {
return sortType;
}
public void setSortType(Integer sortType) {
this.sortType = sortType;
}
}
| apache-2.0 |
sloscal1/SearchParty | java/src/core/messages/SearcherCentricMessages.java | 88954 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/contract.proto
package core.messages;
public final class SearcherCentricMessages {
private SearcherCentricMessages() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface ContractOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required string dispatch_address = 1;
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
boolean hasDispatchAddress();
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
java.lang.String getDispatchAddress();
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
com.google.protobuf.ByteString
getDispatchAddressBytes();
// required int32 experiment_port = 2;
/**
* <code>required int32 experiment_port = 2;</code>
*
* <pre>
*The port that the dispatcher will be listening to.
* </pre>
*/
boolean hasExperimentPort();
/**
* <code>required int32 experiment_port = 2;</code>
*
* <pre>
*The port that the dispatcher will be listening to.
* </pre>
*/
int getExperimentPort();
// optional int32 reply_port = 3;
/**
* <code>optional int32 reply_port = 3;</code>
*
* <pre>
*The secret to share in the communications (should be unique per contract)
* </pre>
*/
boolean hasReplyPort();
/**
* <code>optional int32 reply_port = 3;</code>
*
* <pre>
*The secret to share in the communications (should be unique per contract)
* </pre>
*/
int getReplyPort();
}
/**
* Protobuf type {@code search.Contract}
*
* <pre>
*This message comes with the startup of a new core.party.Searcher to
*let that object know where the dispatcher is, and any other
*pertinent details needed to get the experimentation architecture
*up and running.
* </pre>
*/
public static final class Contract extends
com.google.protobuf.GeneratedMessage
implements ContractOrBuilder {
// Use Contract.newBuilder() to construct.
private Contract(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private Contract(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final Contract defaultInstance;
public static Contract getDefaultInstance() {
return defaultInstance;
}
public Contract getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Contract(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
dispatchAddress_ = input.readBytes();
break;
}
case 16: {
bitField0_ |= 0x00000002;
experimentPort_ = input.readInt32();
break;
}
case 24: {
bitField0_ |= 0x00000004;
replyPort_ = input.readInt32();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return core.messages.SearcherCentricMessages.internal_static_search_Contract_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return core.messages.SearcherCentricMessages.internal_static_search_Contract_fieldAccessorTable
.ensureFieldAccessorsInitialized(
core.messages.SearcherCentricMessages.Contract.class, core.messages.SearcherCentricMessages.Contract.Builder.class);
}
public static com.google.protobuf.Parser<Contract> PARSER =
new com.google.protobuf.AbstractParser<Contract>() {
public Contract parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Contract(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<Contract> getParserForType() {
return PARSER;
}
private int bitField0_;
// required string dispatch_address = 1;
public static final int DISPATCH_ADDRESS_FIELD_NUMBER = 1;
private java.lang.Object dispatchAddress_;
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public boolean hasDispatchAddress() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public java.lang.String getDispatchAddress() {
java.lang.Object ref = dispatchAddress_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
dispatchAddress_ = s;
}
return s;
}
}
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public com.google.protobuf.ByteString
getDispatchAddressBytes() {
java.lang.Object ref = dispatchAddress_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
dispatchAddress_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// required int32 experiment_port = 2;
public static final int EXPERIMENT_PORT_FIELD_NUMBER = 2;
private int experimentPort_;
/**
* <code>required int32 experiment_port = 2;</code>
*
* <pre>
*The port that the dispatcher will be listening to.
* </pre>
*/
public boolean hasExperimentPort() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required int32 experiment_port = 2;</code>
*
* <pre>
*The port that the dispatcher will be listening to.
* </pre>
*/
public int getExperimentPort() {
return experimentPort_;
}
// optional int32 reply_port = 3;
public static final int REPLY_PORT_FIELD_NUMBER = 3;
private int replyPort_;
/**
* <code>optional int32 reply_port = 3;</code>
*
* <pre>
*The secret to share in the communications (should be unique per contract)
* </pre>
*/
public boolean hasReplyPort() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional int32 reply_port = 3;</code>
*
* <pre>
*The secret to share in the communications (should be unique per contract)
* </pre>
*/
public int getReplyPort() {
return replyPort_;
}
private void initFields() {
dispatchAddress_ = "";
experimentPort_ = 0;
replyPort_ = 0;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasDispatchAddress()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasExperimentPort()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getDispatchAddressBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeInt32(2, experimentPort_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeInt32(3, replyPort_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getDispatchAddressBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, experimentPort_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(3, replyPort_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static core.messages.SearcherCentricMessages.Contract parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static core.messages.SearcherCentricMessages.Contract parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.Contract parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static core.messages.SearcherCentricMessages.Contract parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.Contract parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static core.messages.SearcherCentricMessages.Contract parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.Contract parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static core.messages.SearcherCentricMessages.Contract parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.Contract parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static core.messages.SearcherCentricMessages.Contract parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(core.messages.SearcherCentricMessages.Contract prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code search.Contract}
*
* <pre>
*This message comes with the startup of a new core.party.Searcher to
*let that object know where the dispatcher is, and any other
*pertinent details needed to get the experimentation architecture
*up and running.
* </pre>
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements core.messages.SearcherCentricMessages.ContractOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return core.messages.SearcherCentricMessages.internal_static_search_Contract_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return core.messages.SearcherCentricMessages.internal_static_search_Contract_fieldAccessorTable
.ensureFieldAccessorsInitialized(
core.messages.SearcherCentricMessages.Contract.class, core.messages.SearcherCentricMessages.Contract.Builder.class);
}
// Construct using core.messages.SearcherCentricMessages.Contract.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
dispatchAddress_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
experimentPort_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
replyPort_ = 0;
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return core.messages.SearcherCentricMessages.internal_static_search_Contract_descriptor;
}
public core.messages.SearcherCentricMessages.Contract getDefaultInstanceForType() {
return core.messages.SearcherCentricMessages.Contract.getDefaultInstance();
}
public core.messages.SearcherCentricMessages.Contract build() {
core.messages.SearcherCentricMessages.Contract result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public core.messages.SearcherCentricMessages.Contract buildPartial() {
core.messages.SearcherCentricMessages.Contract result = new core.messages.SearcherCentricMessages.Contract(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.dispatchAddress_ = dispatchAddress_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.experimentPort_ = experimentPort_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.replyPort_ = replyPort_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof core.messages.SearcherCentricMessages.Contract) {
return mergeFrom((core.messages.SearcherCentricMessages.Contract)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(core.messages.SearcherCentricMessages.Contract other) {
if (other == core.messages.SearcherCentricMessages.Contract.getDefaultInstance()) return this;
if (other.hasDispatchAddress()) {
bitField0_ |= 0x00000001;
dispatchAddress_ = other.dispatchAddress_;
onChanged();
}
if (other.hasExperimentPort()) {
setExperimentPort(other.getExperimentPort());
}
if (other.hasReplyPort()) {
setReplyPort(other.getReplyPort());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasDispatchAddress()) {
return false;
}
if (!hasExperimentPort()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
core.messages.SearcherCentricMessages.Contract parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (core.messages.SearcherCentricMessages.Contract) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// required string dispatch_address = 1;
private java.lang.Object dispatchAddress_ = "";
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public boolean hasDispatchAddress() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public java.lang.String getDispatchAddress() {
java.lang.Object ref = dispatchAddress_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
dispatchAddress_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public com.google.protobuf.ByteString
getDispatchAddressBytes() {
java.lang.Object ref = dispatchAddress_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
dispatchAddress_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public Builder setDispatchAddress(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
dispatchAddress_ = value;
onChanged();
return this;
}
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public Builder clearDispatchAddress() {
bitField0_ = (bitField0_ & ~0x00000001);
dispatchAddress_ = getDefaultInstance().getDispatchAddress();
onChanged();
return this;
}
/**
* <code>required string dispatch_address = 1;</code>
*
* <pre>
*The IPv4 address where the Dispatcher can be found.
*e.g., 127.0.0.1, localhost, etc.
* </pre>
*/
public Builder setDispatchAddressBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
dispatchAddress_ = value;
onChanged();
return this;
}
// required int32 experiment_port = 2;
private int experimentPort_ ;
/**
* <code>required int32 experiment_port = 2;</code>
*
* <pre>
*The port that the dispatcher will be listening to.
* </pre>
*/
public boolean hasExperimentPort() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required int32 experiment_port = 2;</code>
*
* <pre>
*The port that the dispatcher will be listening to.
* </pre>
*/
public int getExperimentPort() {
return experimentPort_;
}
/**
* <code>required int32 experiment_port = 2;</code>
*
* <pre>
*The port that the dispatcher will be listening to.
* </pre>
*/
public Builder setExperimentPort(int value) {
bitField0_ |= 0x00000002;
experimentPort_ = value;
onChanged();
return this;
}
/**
* <code>required int32 experiment_port = 2;</code>
*
* <pre>
*The port that the dispatcher will be listening to.
* </pre>
*/
public Builder clearExperimentPort() {
bitField0_ = (bitField0_ & ~0x00000002);
experimentPort_ = 0;
onChanged();
return this;
}
// optional int32 reply_port = 3;
private int replyPort_ ;
/**
* <code>optional int32 reply_port = 3;</code>
*
* <pre>
*The secret to share in the communications (should be unique per contract)
* </pre>
*/
public boolean hasReplyPort() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional int32 reply_port = 3;</code>
*
* <pre>
*The secret to share in the communications (should be unique per contract)
* </pre>
*/
public int getReplyPort() {
return replyPort_;
}
/**
* <code>optional int32 reply_port = 3;</code>
*
* <pre>
*The secret to share in the communications (should be unique per contract)
* </pre>
*/
public Builder setReplyPort(int value) {
bitField0_ |= 0x00000004;
replyPort_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 reply_port = 3;</code>
*
* <pre>
*The secret to share in the communications (should be unique per contract)
* </pre>
*/
public Builder clearReplyPort() {
bitField0_ = (bitField0_ & ~0x00000004);
replyPort_ = 0;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:search.Contract)
}
static {
defaultInstance = new Contract(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:search.Contract)
}
public interface RunSettingsOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// repeated .search.Argument argument = 1;
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
java.util.List<core.messages.SearcherCentricMessages.Argument>
getArgumentList();
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
core.messages.SearcherCentricMessages.Argument getArgument(int index);
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
int getArgumentCount();
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
java.util.List<? extends core.messages.SearcherCentricMessages.ArgumentOrBuilder>
getArgumentOrBuilderList();
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
core.messages.SearcherCentricMessages.ArgumentOrBuilder getArgumentOrBuilder(
int index);
// optional bool terminal = 2 [default = false];
/**
* <code>optional bool terminal = 2 [default = false];</code>
*
* <pre>
*True when there are no further experiments
* </pre>
*/
boolean hasTerminal();
/**
* <code>optional bool terminal = 2 [default = false];</code>
*
* <pre>
*True when there are no further experiments
* </pre>
*/
boolean getTerminal();
// optional string results_table_prefix = 3;
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
boolean hasResultsTablePrefix();
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
java.lang.String getResultsTablePrefix();
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
com.google.protobuf.ByteString
getResultsTablePrefixBytes();
}
/**
* Protobuf type {@code search.RunSettings}
*
* <pre>
*Encapsulates the specific parameter settings of this experiment
* </pre>
*/
public static final class RunSettings extends
com.google.protobuf.GeneratedMessage
implements RunSettingsOrBuilder {
// Use RunSettings.newBuilder() to construct.
private RunSettings(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private RunSettings(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final RunSettings defaultInstance;
public static RunSettings getDefaultInstance() {
return defaultInstance;
}
public RunSettings getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private RunSettings(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
argument_ = new java.util.ArrayList<core.messages.SearcherCentricMessages.Argument>();
mutable_bitField0_ |= 0x00000001;
}
argument_.add(input.readMessage(core.messages.SearcherCentricMessages.Argument.PARSER, extensionRegistry));
break;
}
case 16: {
bitField0_ |= 0x00000001;
terminal_ = input.readBool();
break;
}
case 26: {
bitField0_ |= 0x00000002;
resultsTablePrefix_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
argument_ = java.util.Collections.unmodifiableList(argument_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return core.messages.SearcherCentricMessages.internal_static_search_RunSettings_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return core.messages.SearcherCentricMessages.internal_static_search_RunSettings_fieldAccessorTable
.ensureFieldAccessorsInitialized(
core.messages.SearcherCentricMessages.RunSettings.class, core.messages.SearcherCentricMessages.RunSettings.Builder.class);
}
public static com.google.protobuf.Parser<RunSettings> PARSER =
new com.google.protobuf.AbstractParser<RunSettings>() {
public RunSettings parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new RunSettings(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<RunSettings> getParserForType() {
return PARSER;
}
private int bitField0_;
// repeated .search.Argument argument = 1;
public static final int ARGUMENT_FIELD_NUMBER = 1;
private java.util.List<core.messages.SearcherCentricMessages.Argument> argument_;
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public java.util.List<core.messages.SearcherCentricMessages.Argument> getArgumentList() {
return argument_;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public java.util.List<? extends core.messages.SearcherCentricMessages.ArgumentOrBuilder>
getArgumentOrBuilderList() {
return argument_;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public int getArgumentCount() {
return argument_.size();
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public core.messages.SearcherCentricMessages.Argument getArgument(int index) {
return argument_.get(index);
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public core.messages.SearcherCentricMessages.ArgumentOrBuilder getArgumentOrBuilder(
int index) {
return argument_.get(index);
}
// optional bool terminal = 2 [default = false];
public static final int TERMINAL_FIELD_NUMBER = 2;
private boolean terminal_;
/**
* <code>optional bool terminal = 2 [default = false];</code>
*
* <pre>
*True when there are no further experiments
* </pre>
*/
public boolean hasTerminal() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional bool terminal = 2 [default = false];</code>
*
* <pre>
*True when there are no further experiments
* </pre>
*/
public boolean getTerminal() {
return terminal_;
}
// optional string results_table_prefix = 3;
public static final int RESULTS_TABLE_PREFIX_FIELD_NUMBER = 3;
private java.lang.Object resultsTablePrefix_;
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public boolean hasResultsTablePrefix() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public java.lang.String getResultsTablePrefix() {
java.lang.Object ref = resultsTablePrefix_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
resultsTablePrefix_ = s;
}
return s;
}
}
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public com.google.protobuf.ByteString
getResultsTablePrefixBytes() {
java.lang.Object ref = resultsTablePrefix_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resultsTablePrefix_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
argument_ = java.util.Collections.emptyList();
terminal_ = false;
resultsTablePrefix_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
for (int i = 0; i < getArgumentCount(); i++) {
if (!getArgument(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
for (int i = 0; i < argument_.size(); i++) {
output.writeMessage(1, argument_.get(i));
}
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBool(2, terminal_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(3, getResultsTablePrefixBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < argument_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, argument_.get(i));
}
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(2, terminal_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getResultsTablePrefixBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static core.messages.SearcherCentricMessages.RunSettings parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static core.messages.SearcherCentricMessages.RunSettings parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.RunSettings parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static core.messages.SearcherCentricMessages.RunSettings parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.RunSettings parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static core.messages.SearcherCentricMessages.RunSettings parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.RunSettings parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static core.messages.SearcherCentricMessages.RunSettings parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.RunSettings parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static core.messages.SearcherCentricMessages.RunSettings parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(core.messages.SearcherCentricMessages.RunSettings prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code search.RunSettings}
*
* <pre>
*Encapsulates the specific parameter settings of this experiment
* </pre>
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements core.messages.SearcherCentricMessages.RunSettingsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return core.messages.SearcherCentricMessages.internal_static_search_RunSettings_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return core.messages.SearcherCentricMessages.internal_static_search_RunSettings_fieldAccessorTable
.ensureFieldAccessorsInitialized(
core.messages.SearcherCentricMessages.RunSettings.class, core.messages.SearcherCentricMessages.RunSettings.Builder.class);
}
// Construct using core.messages.SearcherCentricMessages.RunSettings.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getArgumentFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
if (argumentBuilder_ == null) {
argument_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
argumentBuilder_.clear();
}
terminal_ = false;
bitField0_ = (bitField0_ & ~0x00000002);
resultsTablePrefix_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return core.messages.SearcherCentricMessages.internal_static_search_RunSettings_descriptor;
}
public core.messages.SearcherCentricMessages.RunSettings getDefaultInstanceForType() {
return core.messages.SearcherCentricMessages.RunSettings.getDefaultInstance();
}
public core.messages.SearcherCentricMessages.RunSettings build() {
core.messages.SearcherCentricMessages.RunSettings result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public core.messages.SearcherCentricMessages.RunSettings buildPartial() {
core.messages.SearcherCentricMessages.RunSettings result = new core.messages.SearcherCentricMessages.RunSettings(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (argumentBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
argument_ = java.util.Collections.unmodifiableList(argument_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.argument_ = argument_;
} else {
result.argument_ = argumentBuilder_.build();
}
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000001;
}
result.terminal_ = terminal_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000002;
}
result.resultsTablePrefix_ = resultsTablePrefix_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof core.messages.SearcherCentricMessages.RunSettings) {
return mergeFrom((core.messages.SearcherCentricMessages.RunSettings)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(core.messages.SearcherCentricMessages.RunSettings other) {
if (other == core.messages.SearcherCentricMessages.RunSettings.getDefaultInstance()) return this;
if (argumentBuilder_ == null) {
if (!other.argument_.isEmpty()) {
if (argument_.isEmpty()) {
argument_ = other.argument_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureArgumentIsMutable();
argument_.addAll(other.argument_);
}
onChanged();
}
} else {
if (!other.argument_.isEmpty()) {
if (argumentBuilder_.isEmpty()) {
argumentBuilder_.dispose();
argumentBuilder_ = null;
argument_ = other.argument_;
bitField0_ = (bitField0_ & ~0x00000001);
argumentBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getArgumentFieldBuilder() : null;
} else {
argumentBuilder_.addAllMessages(other.argument_);
}
}
}
if (other.hasTerminal()) {
setTerminal(other.getTerminal());
}
if (other.hasResultsTablePrefix()) {
bitField0_ |= 0x00000004;
resultsTablePrefix_ = other.resultsTablePrefix_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
for (int i = 0; i < getArgumentCount(); i++) {
if (!getArgument(i).isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
core.messages.SearcherCentricMessages.RunSettings parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (core.messages.SearcherCentricMessages.RunSettings) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// repeated .search.Argument argument = 1;
private java.util.List<core.messages.SearcherCentricMessages.Argument> argument_ =
java.util.Collections.emptyList();
private void ensureArgumentIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
argument_ = new java.util.ArrayList<core.messages.SearcherCentricMessages.Argument>(argument_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilder<
core.messages.SearcherCentricMessages.Argument, core.messages.SearcherCentricMessages.Argument.Builder, core.messages.SearcherCentricMessages.ArgumentOrBuilder> argumentBuilder_;
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public java.util.List<core.messages.SearcherCentricMessages.Argument> getArgumentList() {
if (argumentBuilder_ == null) {
return java.util.Collections.unmodifiableList(argument_);
} else {
return argumentBuilder_.getMessageList();
}
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public int getArgumentCount() {
if (argumentBuilder_ == null) {
return argument_.size();
} else {
return argumentBuilder_.getCount();
}
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public core.messages.SearcherCentricMessages.Argument getArgument(int index) {
if (argumentBuilder_ == null) {
return argument_.get(index);
} else {
return argumentBuilder_.getMessage(index);
}
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder setArgument(
int index, core.messages.SearcherCentricMessages.Argument value) {
if (argumentBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureArgumentIsMutable();
argument_.set(index, value);
onChanged();
} else {
argumentBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder setArgument(
int index, core.messages.SearcherCentricMessages.Argument.Builder builderForValue) {
if (argumentBuilder_ == null) {
ensureArgumentIsMutable();
argument_.set(index, builderForValue.build());
onChanged();
} else {
argumentBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder addArgument(core.messages.SearcherCentricMessages.Argument value) {
if (argumentBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureArgumentIsMutable();
argument_.add(value);
onChanged();
} else {
argumentBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder addArgument(
int index, core.messages.SearcherCentricMessages.Argument value) {
if (argumentBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureArgumentIsMutable();
argument_.add(index, value);
onChanged();
} else {
argumentBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder addArgument(
core.messages.SearcherCentricMessages.Argument.Builder builderForValue) {
if (argumentBuilder_ == null) {
ensureArgumentIsMutable();
argument_.add(builderForValue.build());
onChanged();
} else {
argumentBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder addArgument(
int index, core.messages.SearcherCentricMessages.Argument.Builder builderForValue) {
if (argumentBuilder_ == null) {
ensureArgumentIsMutable();
argument_.add(index, builderForValue.build());
onChanged();
} else {
argumentBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder addAllArgument(
java.lang.Iterable<? extends core.messages.SearcherCentricMessages.Argument> values) {
if (argumentBuilder_ == null) {
ensureArgumentIsMutable();
super.addAll(values, argument_);
onChanged();
} else {
argumentBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder clearArgument() {
if (argumentBuilder_ == null) {
argument_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
argumentBuilder_.clear();
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public Builder removeArgument(int index) {
if (argumentBuilder_ == null) {
ensureArgumentIsMutable();
argument_.remove(index);
onChanged();
} else {
argumentBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public core.messages.SearcherCentricMessages.Argument.Builder getArgumentBuilder(
int index) {
return getArgumentFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public core.messages.SearcherCentricMessages.ArgumentOrBuilder getArgumentOrBuilder(
int index) {
if (argumentBuilder_ == null) {
return argument_.get(index); } else {
return argumentBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public java.util.List<? extends core.messages.SearcherCentricMessages.ArgumentOrBuilder>
getArgumentOrBuilderList() {
if (argumentBuilder_ != null) {
return argumentBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(argument_);
}
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public core.messages.SearcherCentricMessages.Argument.Builder addArgumentBuilder() {
return getArgumentFieldBuilder().addBuilder(
core.messages.SearcherCentricMessages.Argument.getDefaultInstance());
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public core.messages.SearcherCentricMessages.Argument.Builder addArgumentBuilder(
int index) {
return getArgumentFieldBuilder().addBuilder(
index, core.messages.SearcherCentricMessages.Argument.getDefaultInstance());
}
/**
* <code>repeated .search.Argument argument = 1;</code>
*
* <pre>
*The arguments to pass to the experiment program
* </pre>
*/
public java.util.List<core.messages.SearcherCentricMessages.Argument.Builder>
getArgumentBuilderList() {
return getArgumentFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
core.messages.SearcherCentricMessages.Argument, core.messages.SearcherCentricMessages.Argument.Builder, core.messages.SearcherCentricMessages.ArgumentOrBuilder>
getArgumentFieldBuilder() {
if (argumentBuilder_ == null) {
argumentBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
core.messages.SearcherCentricMessages.Argument, core.messages.SearcherCentricMessages.Argument.Builder, core.messages.SearcherCentricMessages.ArgumentOrBuilder>(
argument_,
((bitField0_ & 0x00000001) == 0x00000001),
getParentForChildren(),
isClean());
argument_ = null;
}
return argumentBuilder_;
}
// optional bool terminal = 2 [default = false];
private boolean terminal_ ;
/**
* <code>optional bool terminal = 2 [default = false];</code>
*
* <pre>
*True when there are no further experiments
* </pre>
*/
public boolean hasTerminal() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional bool terminal = 2 [default = false];</code>
*
* <pre>
*True when there are no further experiments
* </pre>
*/
public boolean getTerminal() {
return terminal_;
}
/**
* <code>optional bool terminal = 2 [default = false];</code>
*
* <pre>
*True when there are no further experiments
* </pre>
*/
public Builder setTerminal(boolean value) {
bitField0_ |= 0x00000002;
terminal_ = value;
onChanged();
return this;
}
/**
* <code>optional bool terminal = 2 [default = false];</code>
*
* <pre>
*True when there are no further experiments
* </pre>
*/
public Builder clearTerminal() {
bitField0_ = (bitField0_ & ~0x00000002);
terminal_ = false;
onChanged();
return this;
}
// optional string results_table_prefix = 3;
private java.lang.Object resultsTablePrefix_ = "";
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public boolean hasResultsTablePrefix() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public java.lang.String getResultsTablePrefix() {
java.lang.Object ref = resultsTablePrefix_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
resultsTablePrefix_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public com.google.protobuf.ByteString
getResultsTablePrefixBytes() {
java.lang.Object ref = resultsTablePrefix_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
resultsTablePrefix_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public Builder setResultsTablePrefix(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
resultsTablePrefix_ = value;
onChanged();
return this;
}
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public Builder clearResultsTablePrefix() {
bitField0_ = (bitField0_ & ~0x00000004);
resultsTablePrefix_ = getDefaultInstance().getResultsTablePrefix();
onChanged();
return this;
}
/**
* <code>optional string results_table_prefix = 3;</code>
*
* <pre>
*The prefix that should be used to uniquely identify the corresponding
*results table(s) in the database
* </pre>
*/
public Builder setResultsTablePrefixBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
resultsTablePrefix_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:search.RunSettings)
}
static {
defaultInstance = new RunSettings(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:search.RunSettings)
}
public interface ArgumentOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required string formal_name = 1;
/**
* <code>required string formal_name = 1;</code>
*/
boolean hasFormalName();
/**
* <code>required string formal_name = 1;</code>
*/
java.lang.String getFormalName();
/**
* <code>required string formal_name = 1;</code>
*/
com.google.protobuf.ByteString
getFormalNameBytes();
// required string value = 2;
/**
* <code>required string value = 2;</code>
*/
boolean hasValue();
/**
* <code>required string value = 2;</code>
*/
java.lang.String getValue();
/**
* <code>required string value = 2;</code>
*/
com.google.protobuf.ByteString
getValueBytes();
}
/**
* Protobuf type {@code search.Argument}
*/
public static final class Argument extends
com.google.protobuf.GeneratedMessage
implements ArgumentOrBuilder {
// Use Argument.newBuilder() to construct.
private Argument(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private Argument(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final Argument defaultInstance;
public static Argument getDefaultInstance() {
return defaultInstance;
}
public Argument getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Argument(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
formalName_ = input.readBytes();
break;
}
case 18: {
bitField0_ |= 0x00000002;
value_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return core.messages.SearcherCentricMessages.internal_static_search_Argument_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return core.messages.SearcherCentricMessages.internal_static_search_Argument_fieldAccessorTable
.ensureFieldAccessorsInitialized(
core.messages.SearcherCentricMessages.Argument.class, core.messages.SearcherCentricMessages.Argument.Builder.class);
}
public static com.google.protobuf.Parser<Argument> PARSER =
new com.google.protobuf.AbstractParser<Argument>() {
public Argument parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Argument(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<Argument> getParserForType() {
return PARSER;
}
private int bitField0_;
// required string formal_name = 1;
public static final int FORMAL_NAME_FIELD_NUMBER = 1;
private java.lang.Object formalName_;
/**
* <code>required string formal_name = 1;</code>
*/
public boolean hasFormalName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string formal_name = 1;</code>
*/
public java.lang.String getFormalName() {
java.lang.Object ref = formalName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
formalName_ = s;
}
return s;
}
}
/**
* <code>required string formal_name = 1;</code>
*/
public com.google.protobuf.ByteString
getFormalNameBytes() {
java.lang.Object ref = formalName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
formalName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// required string value = 2;
public static final int VALUE_FIELD_NUMBER = 2;
private java.lang.Object value_;
/**
* <code>required string value = 2;</code>
*/
public boolean hasValue() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string value = 2;</code>
*/
public java.lang.String getValue() {
java.lang.Object ref = value_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
value_ = s;
}
return s;
}
}
/**
* <code>required string value = 2;</code>
*/
public com.google.protobuf.ByteString
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
formalName_ = "";
value_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasFormalName()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasValue()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getFormalNameBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getValueBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getFormalNameBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getValueBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static core.messages.SearcherCentricMessages.Argument parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static core.messages.SearcherCentricMessages.Argument parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.Argument parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static core.messages.SearcherCentricMessages.Argument parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.Argument parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static core.messages.SearcherCentricMessages.Argument parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.Argument parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static core.messages.SearcherCentricMessages.Argument parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static core.messages.SearcherCentricMessages.Argument parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static core.messages.SearcherCentricMessages.Argument parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(core.messages.SearcherCentricMessages.Argument prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code search.Argument}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements core.messages.SearcherCentricMessages.ArgumentOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return core.messages.SearcherCentricMessages.internal_static_search_Argument_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return core.messages.SearcherCentricMessages.internal_static_search_Argument_fieldAccessorTable
.ensureFieldAccessorsInitialized(
core.messages.SearcherCentricMessages.Argument.class, core.messages.SearcherCentricMessages.Argument.Builder.class);
}
// Construct using core.messages.SearcherCentricMessages.Argument.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
formalName_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
value_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return core.messages.SearcherCentricMessages.internal_static_search_Argument_descriptor;
}
public core.messages.SearcherCentricMessages.Argument getDefaultInstanceForType() {
return core.messages.SearcherCentricMessages.Argument.getDefaultInstance();
}
public core.messages.SearcherCentricMessages.Argument build() {
core.messages.SearcherCentricMessages.Argument result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public core.messages.SearcherCentricMessages.Argument buildPartial() {
core.messages.SearcherCentricMessages.Argument result = new core.messages.SearcherCentricMessages.Argument(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.formalName_ = formalName_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.value_ = value_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof core.messages.SearcherCentricMessages.Argument) {
return mergeFrom((core.messages.SearcherCentricMessages.Argument)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(core.messages.SearcherCentricMessages.Argument other) {
if (other == core.messages.SearcherCentricMessages.Argument.getDefaultInstance()) return this;
if (other.hasFormalName()) {
bitField0_ |= 0x00000001;
formalName_ = other.formalName_;
onChanged();
}
if (other.hasValue()) {
bitField0_ |= 0x00000002;
value_ = other.value_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasFormalName()) {
return false;
}
if (!hasValue()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
core.messages.SearcherCentricMessages.Argument parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (core.messages.SearcherCentricMessages.Argument) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// required string formal_name = 1;
private java.lang.Object formalName_ = "";
/**
* <code>required string formal_name = 1;</code>
*/
public boolean hasFormalName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string formal_name = 1;</code>
*/
public java.lang.String getFormalName() {
java.lang.Object ref = formalName_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
formalName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string formal_name = 1;</code>
*/
public com.google.protobuf.ByteString
getFormalNameBytes() {
java.lang.Object ref = formalName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
formalName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string formal_name = 1;</code>
*/
public Builder setFormalName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
formalName_ = value;
onChanged();
return this;
}
/**
* <code>required string formal_name = 1;</code>
*/
public Builder clearFormalName() {
bitField0_ = (bitField0_ & ~0x00000001);
formalName_ = getDefaultInstance().getFormalName();
onChanged();
return this;
}
/**
* <code>required string formal_name = 1;</code>
*/
public Builder setFormalNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
formalName_ = value;
onChanged();
return this;
}
// required string value = 2;
private java.lang.Object value_ = "";
/**
* <code>required string value = 2;</code>
*/
public boolean hasValue() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string value = 2;</code>
*/
public java.lang.String getValue() {
java.lang.Object ref = value_;
if (!(ref instanceof java.lang.String)) {
java.lang.String s = ((com.google.protobuf.ByteString) ref)
.toStringUtf8();
value_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string value = 2;</code>
*/
public com.google.protobuf.ByteString
getValueBytes() {
java.lang.Object ref = value_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
value_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string value = 2;</code>
*/
public Builder setValue(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
value_ = value;
onChanged();
return this;
}
/**
* <code>required string value = 2;</code>
*/
public Builder clearValue() {
bitField0_ = (bitField0_ & ~0x00000002);
value_ = getDefaultInstance().getValue();
onChanged();
return this;
}
/**
* <code>required string value = 2;</code>
*/
public Builder setValueBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
value_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:search.Argument)
}
static {
defaultInstance = new Argument(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:search.Argument)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_search_Contract_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_search_Contract_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_search_RunSettings_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_search_RunSettings_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_search_Argument_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_search_Argument_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\024proto/contract.proto\022\006search\"Q\n\010Contra" +
"ct\022\030\n\020dispatch_address\030\001 \002(\t\022\027\n\017experime" +
"nt_port\030\002 \002(\005\022\022\n\nreply_port\030\003 \001(\005\"h\n\013Run" +
"Settings\022\"\n\010argument\030\001 \003(\0132\020.search.Argu" +
"ment\022\027\n\010terminal\030\002 \001(\010:\005false\022\034\n\024results" +
"_table_prefix\030\003 \001(\t\".\n\010Argument\022\023\n\013forma" +
"l_name\030\001 \002(\t\022\r\n\005value\030\002 \002(\tB(\n\rcore.mess" +
"agesB\027SearcherCentricMessages"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_search_Contract_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_search_Contract_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_search_Contract_descriptor,
new java.lang.String[] { "DispatchAddress", "ExperimentPort", "ReplyPort", });
internal_static_search_RunSettings_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_search_RunSettings_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_search_RunSettings_descriptor,
new java.lang.String[] { "Argument", "Terminal", "ResultsTablePrefix", });
internal_static_search_Argument_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_search_Argument_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_search_Argument_descriptor,
new java.lang.String[] { "FormalName", "Value", });
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
| apache-2.0 |
ljcservice/autumnprogram | src/main/java/com/hitzd/WebPage/Impl/BasePageBean.java | 4977 | package com.hitzd.WebPage.Impl;
import java.util.LinkedHashMap;
import com.hitzd.DBUtils.TCommonRecord;
import com.hitzd.WebPage.PageView;
import com.hitzd.WebPage.QueryResult;
import com.hitzd.DBUtils.CommonMapper;
import com.hitzd.persistent.Persistent4DB;
/**
* 分页基类
* @author Administrator
*
*/
public class BasePageBean extends Persistent4DB
{
/**
* 分页操作
* @param maxresult 一页显示记录数
* @param currentpage 页码
* @param queryCode 系统代码
* @param wheres 条件
* @param value 参数值
* @param orders 排序
* @param tableName 表名
* @param fields 字段名称
* @return
*/
@SuppressWarnings ("unchecked")
public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage, String queryCode
,String wheres,Object[] value ,LinkedHashMap<String, String> orders,String tableName,String fields)
{
setQueryCode(queryCode);
/* 分页数据集合 */
QueryResult<TCommonRecord> qr = new QueryResult<TCommonRecord>();
/* 页码 */
currentpage = currentpage < 1 ? 1 : currentpage;
/* 一页显示记录数 */
maxresult = maxresult < 1? 12 : maxresult;
PageView<TCommonRecord> pageView = new PageView<TCommonRecord>(maxresult,currentpage);
/* 数据总数 */
StringBuffer countSql = new StringBuffer();
countSql.append("select count(*) total from ").append(tableName).append(" where 1=1 ").append(wheres);
/* 数据总数 */
qr.setTotalrecord(((TCommonRecord)query.queryForObject(countSql.toString(),value == null ? new Object[]{} : value,new CommonMapper())).getInt("total"));
/* 当总页数小于当前页 当前页设置为 第一页 */
if(((qr.getTotalrecord() / maxresult) + ((qr.getTotalrecord() % maxresult) > 0 ? 1 : 0 )) < currentpage)
{
pageView.setCurrentpage(1);
}
Integer firstindex = (pageView.getCurrentpage()-1) * pageView.getMaxresult();
Integer lastindex = (pageView.getCurrentpage()) * pageView.getMaxresult();
/* 是否指定字段查询 */
fields = fields == null? "*": fields;
/* 分页数据 */
StringBuffer pageSql = new StringBuffer("select * from (select t.* ,rownum rn from (select ").append(fields).append(" from ");
pageSql.append(tableName).append(" where 1=1 ").append(wheres);
pageSql.append(getOrder(orders));
pageSql.append(") t where rownum <= ").append(lastindex.toString()).append(") b where b.rn > ").append(firstindex.toString());
/* 分页数据 */
qr.setResultlist(query.query(pageSql.toString(),value == null?new Object[]{}:value, new CommonMapper()));
pageView.setQueryResult(qr);
return pageView;
}
public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage, String queryCode
,String wheres,Object[] value ,LinkedHashMap<String, String> orders,String tableName)
{
return getScrollData( maxresult, currentpage, queryCode
, wheres, value , orders, tableName ,null);
}
public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage,String queryCode, String tableName)
{
return getScrollData(maxresult, currentpage, queryCode,null,null ,null, tableName,null);
}
public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage,String queryCode,String wheres, String tableName)
{
return getScrollData(maxresult, currentpage, queryCode,wheres,null ,null, tableName,null);
}
public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage,String queryCode,String wheres,LinkedHashMap<String
, String> orders, String tableName)
{
return getScrollData(maxresult, currentpage, queryCode,wheres,null ,orders, tableName,null);
}
public PageView<TCommonRecord> getScrollData(int maxresult, int currentpage,String queryCode,String wheres
,Object[] value , String tableName)
{
return getScrollData(maxresult, currentpage, queryCode,wheres,value ,null, tableName,null);
}
/**
* 构建排序方法
* @param orders
* @return
*/
private String getOrder(LinkedHashMap<String, String> orders)
{
StringBuffer strOrder = new StringBuffer("");
if(orders!=null&&orders.size()>0)
{
strOrder.append(" order by ");
for(String order :orders.keySet())
{
strOrder.append(order).append(" ").append(orders.get(order)).append(",");
}
strOrder.deleteCharAt(strOrder.length()-1);
}
return strOrder.toString();
}
}
| apache-2.0 |
OpenNTF/org.openntf.domino | domino/core/src/main/java/org/openntf/domino/utils/CollectionUtils.java | 17050 | /**
* Copyright © 2013-2021 The OpenNTF Domino API Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openntf.domino.utils;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.util.Vector;
import lotus.domino.NotesException;
import org.openntf.domino.Document;
import org.openntf.domino.iterators.DocumentList;
/**
* CollectionUtils (Sets and Lists) utilities library
*
* @author Devin S. Olson (dolson@czarnowski.com)
*/
@SuppressWarnings("nls")
public enum CollectionUtils {
;
public static class ChainedIterable<T> implements Iterable<T> {
private final List<Iterable<T>> iterables_;
protected static class ChainedIterator<T> implements Iterator<T> {
private final List<Iterable<T>> iterables_;
private Iterator<T> currentIterator;
private int current = 0;
ChainedIterator(final List<Iterable<T>> iterables) {
iterables_ = iterables;
currentIterator = iterables_.get(0).iterator();
}
@Override
public void remove() {
currentIterator.remove();
}
@Override
public boolean hasNext() {
while (true) {
if (currentIterator.hasNext()) {
return true;
} else {
this.current++;
if (this.current >= iterables_.size())
break;
this.currentIterator = iterables_.get(this.current).iterator();
}
}
return false;
}
@Override
public T next() {
while (true) {
if (currentIterator.hasNext()) {
return currentIterator.next();
} else {
this.current++;
if (this.current >= iterables_.size())
break;
this.currentIterator = iterables_.get(current).iterator();
}
}
throw new NoSuchElementException();
}
}
public ChainedIterable(@SuppressWarnings("unchecked") final Iterable<T>... iterables) {
if (iterables != null && iterables.length > 0) {
iterables_ = new ArrayList<Iterable<T>>(iterables.length);
for (Iterable<T> iterable : iterables) {
iterables_.add(iterable);
}
} else {
throw new IllegalArgumentException("Cannot pass a null or empty set of iterables to a ChainedIterable");
}
}
@Override
public Iterator<T> iterator() {
return new ChainedIterator<T>(iterables_);
}
}
/**
* Gets or generates an List of Strings from an Item on a Document
*
* @param source
* Document from which to get or generate the result.
*
* @param itemname
* Name of item from which to get the content
*
* @return List of Strings retrieved or generated from the input. Returns null if the document does not contain the item.
*
* @throws IllegalArgumentException
* if source document is null or itemname is blank or null.
*/
public static List<String> getListStrings(final Document source, final String itemname) {
if (null == source) {
throw new IllegalArgumentException("Source document is null");
}
if (Strings.isBlankString(itemname)) {
throw new IllegalArgumentException("ItemName is blank or null");
}
return (source.hasItem(itemname)) ? CollectionUtils.getListStrings(source.getItemValue(itemname)) : null;
}
/**
* Gets or generates an List of Strings from a Vector
*
* @param vector
* Vector from which to get or generate the result.
*
* @return List of Strings retrieved or generated from the input. Returns null on error.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<String> getListStrings(final Vector vector) {
return (null == vector) ? null : Collections.list(vector.elements());
}
/**
* Gets or generates an List of Strings from an AbstractCollection
*
* @param collection
* AbstractCollection from which to get or generate the result.
*
* @return List of Strings retrieved or generated from the input. Returns null on error.
*/
@SuppressWarnings({ "rawtypes" })
public static List<String> getListStrings(final AbstractCollection collection) {
if ((null != collection) && (collection.size() > 0)) {
final List<String> result = new ArrayList<String>();
if (collection.iterator().next() instanceof Object) {
// treat as an object
for (final Object o : collection) {
if (null != o) {
result.add(o.toString());
}
}
} else {
// treat as a primitive
final Iterator it = collection.iterator();
while (it.hasNext()) {
result.add(String.valueOf(it.next()));
}
}
return result;
}
return null;
}
/**
* Gets or generates an List of Strings from an AbstractMap
*
* @param map
* AbstractMap from which to get or generate the result. Only the Values will be retrieved, the Keys will are ignored.
*
* @return List of Strings retrieved or generated from the input. Returns null on error.
*/
@SuppressWarnings("rawtypes")
public static List<String> getListStrings(final AbstractMap map) {
return ((null != map) && (map.size() > 0)) ? CollectionUtils.getListStrings(map.values()) : null;
}
/**
* Gets or generates an List of Strings from a String
*
* @param string
* String from which to get or generate the result.
*
* @return List of Strings retrieved or generated from the input. Returns null on error.
*/
public static List<String> getListStrings(final String string) {
if (!Strings.isBlankString(string)) {
final List<String> result = new ArrayList<String>();
result.add(string);
return result;
}
return null;
}
/**
* Gets or generates an List of Strings from a array of Strings
*
* @param strings
* Array of Strings from which to get or generate the result.
*
* @return List of Strings retrieved or generated from the input. Returns null on error.
*/
public static List<String> getListStrings(final String[] strings) {
if ((null != strings) && (strings.length > 0)) {
final List<String> result = new ArrayList<String>();
for (final String s : strings) {
result.add(s);
}
return result;
}
return null;
}
/**
* Gets or generates an List of Strings from an Object
*
* @param object
* Object from which to get or generate the result. Attempts to retrieve the values from the object.
*
* @return List of Strings retrieved or generated from the input. Returns null on error.
*
*/
@SuppressWarnings("rawtypes")
public static List<String> getListStrings(final Object object) {
String classname = null;
try {
if (null != object) {
classname = object.getClass().getName();
if (object instanceof Vector) {
return CollectionUtils.getListStrings((Vector) object);
}
if (object instanceof AbstractCollection) {
return CollectionUtils.getListStrings((AbstractCollection) object);
}
if (object instanceof AbstractMap) {
return CollectionUtils.getListStrings((AbstractMap) object);
}
if (object instanceof String) {
return CollectionUtils.getListStrings((String) object);
}
if (object instanceof String[]) {
return CollectionUtils.getListStrings((String[]) object);
}
if (classname.equalsIgnoreCase("java.lang.String[]") || classname.equalsIgnoreCase("[Ljava.lang.String;")) { //$NON-NLS-1$ //$NON-NLS-2$
return CollectionUtils.getListStrings((String[]) object);
}
if (classname.equalsIgnoreCase("java.lang.String")) { //$NON-NLS-1$
return CollectionUtils.getListStrings((String) object);
}
throw new IllegalArgumentException("Unsupported Class:" + classname);
}
} catch (Exception e) {
DominoUtils.handleException(e);
}
return null;
}
/**
* Gets or generates a TreeSet of Strings from an Object
*
* @param object
* Object from which to get or generate the result. Attempts to retrieve the string values from the object.
*
* @return TreeSet of Strings retrieved or generated from the input. Returns null on error.
*
*/
public static TreeSet<String> getTreeSetStrings(final Object object) {
final List<String> al = CollectionUtils.getListStrings(object);
return (null == al) ? null : new TreeSet<String>(al);
}
/**
* Gets or generates an Array of Strings from an Object
*
* @param object
* Object from which to get or generate the result. Attempts to retrieve the string values from the object.
*
* @return Array of Strings retrieved or generated from the input. Returns null on error.
*
*/
public static String[] getStringArray(final Object object) {
final List<String> al = CollectionUtils.getListStrings(object);
return (null == al) ? null : al.toArray(new String[al.size()]);
}
/**
* Gets or generates an Array of Strings from an Object
*
* Result array will contain only unique values and will be sorted according to the String object's natural sorting method
*
* @param object
* Object from which to get or generate the result. Attempts to retrieve the string values from the object.
*
* @return Array of Strings retrieved or generated from the input. Returns null on error.
*
* @see java.lang.String#compareTo(String)
*
*/
public static String[] getSortedUnique(final Object object) {
final TreeSet<String> ts = CollectionUtils.getTreeSetStrings(object);
return ((null == ts) || (ts.size() < 1)) ? null : ts.toArray(new String[ts.size()]);
}
/**
* Compares two String[] objects
*
* Arguments are first compared by existence, then by # of elements, then by values.
*
* @param stringarray0
* First String[] to compare.
*
* @param stringarray1
* Second String[] to compare.
*
* @param descending
* flags indicating comparison order. true = descending, false = ascending.
*
* @return a negative integer, zero, or a positive integer indicating if the first object is less than, equal to, or greater than the
* second object.
*
* @see java.lang.Comparable#compareTo(Object)
* @see DominoUtils#LESS_THAN
* @see DominoUtils#EQUAL
* @see DominoUtils#GREATER_THAN
*/
public static int compareStringArrays(final String[] stringarray0, final String[] stringarray1, final boolean descending) {
if (null == stringarray0) {
return (null == stringarray1) ? DominoUtils.EQUAL : (descending) ? DominoUtils.GREATER_THAN : DominoUtils.LESS_THAN;
} else if (null == stringarray1) {
return (descending) ? DominoUtils.LESS_THAN : DominoUtils.GREATER_THAN;
}
if (stringarray0.length < stringarray1.length) {
return (descending) ? DominoUtils.GREATER_THAN : DominoUtils.LESS_THAN;
}
if (stringarray1.length < stringarray0.length) {
return (descending) ? DominoUtils.LESS_THAN : DominoUtils.GREATER_THAN;
}
for (int i = 0; i < stringarray0.length; i++) {
final int result = stringarray0[i].compareTo(stringarray1[i]);
if (DominoUtils.EQUAL != result) {
return (descending) ? -result : result;
}
}
return DominoUtils.EQUAL;
}
/**
* Compares two TreeSet<String> objects
*
* Arguments are first compared by existence, then by size, then by values.
*
* @param treeset0
* First TreeSet<String> to compare.
*
* @param treeset1
* Second TreeSet<String> to compare.
*
* @param descending
* flags indicating comparison order. true = descending, false = ascending.
*
* @return a negative integer, zero, or a positive integer indicating if the first object is less than, equal to, or greater than the
* second object.
*
* @see java.lang.Comparable#compareTo(Object)
* @see DominoUtils#LESS_THAN
* @see DominoUtils#EQUAL
* @see DominoUtils#GREATER_THAN
*/
public static int compareTreeSetStrings(final TreeSet<String> treeset0, final TreeSet<String> treeset1, final boolean descending) {
if (null == treeset0) {
return (null == treeset1) ? DominoUtils.EQUAL : (descending) ? DominoUtils.GREATER_THAN : DominoUtils.LESS_THAN;
} else if (null == treeset1) {
return (descending) ? DominoUtils.LESS_THAN : DominoUtils.GREATER_THAN;
}
if (treeset0.size() < treeset1.size()) {
return (descending) ? DominoUtils.GREATER_THAN : DominoUtils.LESS_THAN;
}
if (treeset1.size() < treeset0.size()) {
return (descending) ? DominoUtils.LESS_THAN : DominoUtils.GREATER_THAN;
}
// Compare as string arrays
return CollectionUtils.compareStringArrays(CollectionUtils.getStringArray(treeset0), CollectionUtils.getStringArray(treeset1),
descending);
}
/**
* Gets or generates a TreeSet containing Strings found in the source which begin with the prefix.
*
* Performs a case-insensitive search.
*
* @param source
* Object from which to attempt to extract and match the strings.
*
* @param prefix
* String which each extracted string must begin with.
*
* @return Strings found within source which begin with prefix.
*
* @see Strings#startsWithIgnoreCase(String, String)
*/
public static TreeSet<String> getTreeSetStringsBeginsWith(final Object source, final String prefix) {
final TreeSet<String> temp = CollectionUtils.getTreeSetStrings(source);
if ((null != temp) && (temp.size() > 0)) {
final TreeSet<String> result = new TreeSet<String>();
for (final String s : temp) {
if (Strings.startsWithIgnoreCase(s, prefix)) {
result.add(s);
}
}
return (result.size() > 0) ? result : null;
}
return null;
}
public static <T> Iterable<T> chain(@SuppressWarnings("unchecked") final Iterable<T>... iterables) {
return new ChainedIterable<T>(iterables);
}
// /**
// * Convert a Document collection to Notes Collection
// *
// * @param collection
// * @return
// */
// public static org.openntf.domino.NoteCollection toLotusNoteCollection(final lotus.domino.DocumentCollection collection) {
// org.openntf.domino.NoteCollection result = null;
// if (collection instanceof org.openntf.domino.DocumentCollection) {
// org.openntf.domino.Database db = ((org.openntf.domino.DocumentCollection) collection).getAncestorDatabase();
// result = db.createNoteCollection(false);
// result.add(collection);
// } else if (collection != null) {
// // TODO Eh?
// org.openntf.domino.Database db = ((org.openntf.domino.DocumentCollection) collection).getAncestorDatabase();
// result = db.createNoteCollection(false);
// result.add(collection);
// }
// return result;
// }
/**
* Returns the Note IDs of the given (Notes) collection
*
* @param collection
* the DocumentCollection
* @return a array of NoteIDs
*/
public static int[] getNoteIDs(final lotus.domino.DocumentCollection collection) {
int[] result = null;
try {
if (collection instanceof DocumentList) {
result = ((DocumentList) collection).getNids();
} else if (collection.isSorted()) {
if (collection instanceof org.openntf.domino.DocumentCollection) {
org.openntf.domino.DocumentCollection ocoll = (org.openntf.domino.DocumentCollection) collection;
int size = ocoll.getCount();
result = new int[size];
int i = 0;
for (org.openntf.domino.Document doc : ocoll) {
result[i++] = Integer.valueOf(doc.getNoteID(), 16);
}
} else {
int size = collection.getCount();
result = new int[size];
lotus.domino.Document doc = collection.getFirstDocument();
lotus.domino.Document next = null;
int i = 0;
while (doc != null) {
next = collection.getNextDocument(doc);
result[i++] = Integer.valueOf(doc.getNoteID(), 16);
doc.recycle();
doc = next;
}
}
} else {
lotus.domino.Database db = collection.getParent();
lotus.domino.NoteCollection nc = db.createNoteCollection(false);
result = nc.getNoteIDs();
nc.recycle();
}
} catch (NotesException e) {
DominoUtils.handleException(e);
}
return result;
}
}
| apache-2.0 |
rundeck/rundeck | rundeck-authz/rundeck-authz-yaml/src/main/java/com/dtolabs/rundeck/core/authorization/providers/BaseValidatorImpl.java | 2969 | package com.dtolabs.rundeck.core.authorization.providers;
import com.dtolabs.rundeck.core.authorization.Attribute;
import com.dtolabs.rundeck.core.authorization.AuthorizationUtil;
import com.dtolabs.rundeck.core.authorization.RuleSetValidation;
import com.dtolabs.rundeck.core.authorization.ValidationSet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
/**
* Implements BaseValidator, and provides a factory via {@link #factory()}
*/
public class BaseValidatorImpl
implements BaseValidator
{
private final String project;
public BaseValidatorImpl(final String project) {
this.project = project;
}
/**
* @return factory
*/
public static ValidatorFactory factory() {
return new ValidatorFactory() {
public BaseValidator forProjectOnly(String project) {
return new BaseValidatorImpl(project);
}
public BaseValidator create() {
return new BaseValidatorImpl(null);
}
};
}
@Override
public PoliciesValidation validateYamlPolicy(String ident, String text) throws IOException {
ValidationSet validation = new ValidationSet();
CacheableYamlSource source = YamlProvider.sourceFromString(ident, text, new Date(), validation);
PolicyCollection policies = YamlProvider.policiesFromSource(
source,
getForcedContext(),
validation
);
validation.complete();
return new PoliciesValidation(validation, policies);
}
@Override
public RuleSetValidation<PolicyCollection> validateYamlPolicy(
final String ident, final File source
) throws IOException
{
ValidationSet validation = new ValidationSet();
PolicyCollection policies = null;
try (FileInputStream stream = new FileInputStream(source)) {
policies = YamlProvider.policiesFromSource(
YamlProvider.sourceFromStream(ident, stream, new Date(), validation),
getForcedContext(),
validation
);
}
validation.complete();
return new PoliciesValidation(validation, policies);
}
private Set<Attribute> getForcedContext() {
return project != null ? AuthorizationUtil.projectContext(project) : null;
}
@Override
public PoliciesValidation validateYamlPolicy(File file) throws IOException {
ValidationSet validation = new ValidationSet();
PolicyCollection
policies =
YamlProvider.policiesFromSource(
YamlProvider.sourceFromFile(file, validation),
getForcedContext(),
validation
);
validation.complete();
return new PoliciesValidation(validation, policies);
}
}
| apache-2.0 |
midnightasgames/stranded | Stranded/src/com/stranded/game/tiles/TileFactory.java | 718 | package com.stranded.game.tiles;
import com.stranded.components.ComponentFactory;
import com.stranded.components.ComponentType;
import com.stranded.components.graphics.GraphicsType;
import com.stranded.game.world.WorldLocation;
public class TileFactory {
private ComponentFactory m_ComponentFactory;
public TileFactory(ComponentFactory p_ComponentFactory)
{
this.m_ComponentFactory = p_ComponentFactory;
}
public Tile createTile(WorldLocation p_Location)
{
Tile l_Tile = new Block(Material.GRASS, p_Location);
l_Tile.registerComponent(ComponentType.RENDER, this.m_ComponentFactory.createRenderComponent(Material.GRASS.getPath(), GraphicsType.IMAGE));
return l_Tile;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-clouddirectory/src/main/java/com/amazonaws/services/clouddirectory/model/transform/AttachPolicyRequestProtocolMarshaller.java | 2667 | /*
* 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.clouddirectory.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.clouddirectory.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* AttachPolicyRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AttachPolicyRequestProtocolMarshaller implements Marshaller<Request<AttachPolicyRequest>, AttachPolicyRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/amazonclouddirectory/2017-01-11/policy/attach").httpMethodName(HttpMethodName.PUT).hasExplicitPayloadMember(false)
.hasPayloadMembers(true).serviceName("AmazonCloudDirectory").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public AttachPolicyRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<AttachPolicyRequest> marshall(AttachPolicyRequest attachPolicyRequest) {
if (attachPolicyRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<AttachPolicyRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
attachPolicyRequest);
protocolMarshaller.startMarshalling();
AttachPolicyRequestMarshaller.getInstance().marshall(attachPolicyRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
leapframework/framework | base/lang/src/test/java/leap/lang/http/client/HttpClientTest.java | 4662 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.lang.http.client;
import leap.junit.TestBase;
import leap.junit.contexual.Contextual;
import leap.junit.contexual.ContextualProvider;
import leap.junit.contexual.ContextualRule;
import leap.lang.Charsets;
import leap.lang.New;
import leap.lang.http.client.apache.ApacheHttpClient;
import leap.lang.io.IO;
import leap.lang.path.Paths;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.Description;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Contextual
public class HttpClientTest extends TestBase {
private static int port = 10999;
private static String baseUrl = "http://127.0.0.1:" + port;
private static Server server;
private static Map<String, HttpClient> clients = new HashMap<>();
private static Map<String, Handler> handlers = new HashMap<>();
@Rule
public ContextualRule rule = new ContextualRule(new ContextualProvider() {
@Override
public Iterable<String> names(Description description) {
return New.arrayList("jdk","apache");
}
@Override
public void beforeTest(Description description, String name) throws Exception {
client = clients.get(name);
}
});
private HttpClient client;
@Test
public void testNotFound() throws IOException {
assertEquals(404, client.request(url("/")).get().getStatus());
}
@Test
public void testSimpleGet() throws IOException {
handle("/simple_get", (req,resp) -> resp.getWriter().write("Hello"));
HttpResponse response = client.request(url("/simple_get")).get();
assertTrue(response.isOk());
assertEquals("Hello", response.getString());
client.request(url("/simple_get")).sendAsync((req, resp) -> {
assertTrue(resp.isOk());
assertEquals("Hello", IO.readStringAndClose(resp.getInputStream(), Charsets.UTF_8));
});
}
private static void handle(String path, Handler handler) {
handlers.put(path, handler);
}
@BeforeClass
public static void startServer() throws Exception {
clients.put("jdk", createJdkClient());
clients.put("apache", createApacheClient());
server = new Server(port);
server.setHandler(new AbstractHandler() {
@Override
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
Handler handler = handlers.get(Paths.suffixWithoutSlash(target));
if(null != handler){
handler.handle(request, response);
if(response.getStatus() == 0) {
response.setStatus(200);
}
baseRequest.setHandled(true);
}
}
});
server.start();
}
@AfterClass
public static void stopServer() throws Exception {
server.stop();
}
private static String url(String path) {
return baseUrl + Paths.suffixWithSlash(path);
}
private static HttpClient createJdkClient() {
return new JdkHttpClient();
}
private static HttpClient createApacheClient() {
ApacheHttpClient client = new ApacheHttpClient();
client.setMaxTotal(2);
client.setDefaultMaxPerRoute(2);
client.init();
return client;
}
private interface Handler {
void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException,ServletException;
}
}
| apache-2.0 |
googleapis/java-compute | proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/InsertRegionDiskRequestOrBuilder.java | 6487 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
package com.google.cloud.compute.v1;
public interface InsertRegionDiskRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.InsertRegionDiskRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.Disk disk_resource = 25880688 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the diskResource field is set.
*/
boolean hasDiskResource();
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.Disk disk_resource = 25880688 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The diskResource.
*/
com.google.cloud.compute.v1.Disk getDiskResource();
/**
*
*
* <pre>
* The body resource for this request
* </pre>
*
* <code>
* .google.cloud.compute.v1.Disk disk_resource = 25880688 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.cloud.compute.v1.DiskOrBuilder getDiskResourceOrBuilder();
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
java.lang.String getProject();
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
com.google.protobuf.ByteString getProjectBytes();
/**
*
*
* <pre>
* Name of the region for this request.
* </pre>
*
* <code>
* string region = 138946292 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "region"];
* </code>
*
* @return The region.
*/
java.lang.String getRegion();
/**
*
*
* <pre>
* Name of the region for this request.
* </pre>
*
* <code>
* string region = 138946292 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "region"];
* </code>
*
* @return The bytes for region.
*/
com.google.protobuf.ByteString getRegionBytes();
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
boolean hasRequestId();
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
java.lang.String getRequestId();
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
com.google.protobuf.ByteString getRequestIdBytes();
/**
*
*
* <pre>
* Source image to restore onto a disk. This field is optional.
* </pre>
*
* <code>optional string source_image = 50443319;</code>
*
* @return Whether the sourceImage field is set.
*/
boolean hasSourceImage();
/**
*
*
* <pre>
* Source image to restore onto a disk. This field is optional.
* </pre>
*
* <code>optional string source_image = 50443319;</code>
*
* @return The sourceImage.
*/
java.lang.String getSourceImage();
/**
*
*
* <pre>
* Source image to restore onto a disk. This field is optional.
* </pre>
*
* <code>optional string source_image = 50443319;</code>
*
* @return The bytes for sourceImage.
*/
com.google.protobuf.ByteString getSourceImageBytes();
}
| apache-2.0 |
griffon/griffon-pivot-plugin | src/main/griffon/pivot/support/adapters/ButtonAdapter.java | 4655 | /*
* Copyright 2012 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 griffon.pivot.support.adapters;
import groovy.lang.Closure;
/**
* @author Andres Almiray
*/
public class ButtonAdapter implements GriffonPivotAdapter, org.apache.pivot.wtk.ButtonListener {
private Closure actionChanged;
private Closure buttonDataChanged;
private Closure dataRendererChanged;
private Closure toggleButtonChanged;
private Closure triStateChanged;
private Closure buttonGroupChanged;
public Closure getActionChanged() {
return this.actionChanged;
}
public Closure getButtonDataChanged() {
return this.buttonDataChanged;
}
public Closure getDataRendererChanged() {
return this.dataRendererChanged;
}
public Closure getToggleButtonChanged() {
return this.toggleButtonChanged;
}
public Closure getTriStateChanged() {
return this.triStateChanged;
}
public Closure getButtonGroupChanged() {
return this.buttonGroupChanged;
}
public void setActionChanged(Closure actionChanged) {
this.actionChanged = actionChanged;
if (this.actionChanged != null) {
this.actionChanged.setDelegate(this);
this.actionChanged.setResolveStrategy(Closure.DELEGATE_FIRST);
}
}
public void setButtonDataChanged(Closure buttonDataChanged) {
this.buttonDataChanged = buttonDataChanged;
if (this.buttonDataChanged != null) {
this.buttonDataChanged.setDelegate(this);
this.buttonDataChanged.setResolveStrategy(Closure.DELEGATE_FIRST);
}
}
public void setDataRendererChanged(Closure dataRendererChanged) {
this.dataRendererChanged = dataRendererChanged;
if (this.dataRendererChanged != null) {
this.dataRendererChanged.setDelegate(this);
this.dataRendererChanged.setResolveStrategy(Closure.DELEGATE_FIRST);
}
}
public void setToggleButtonChanged(Closure toggleButtonChanged) {
this.toggleButtonChanged = toggleButtonChanged;
if (this.toggleButtonChanged != null) {
this.toggleButtonChanged.setDelegate(this);
this.toggleButtonChanged.setResolveStrategy(Closure.DELEGATE_FIRST);
}
}
public void setTriStateChanged(Closure triStateChanged) {
this.triStateChanged = triStateChanged;
if (this.triStateChanged != null) {
this.triStateChanged.setDelegate(this);
this.triStateChanged.setResolveStrategy(Closure.DELEGATE_FIRST);
}
}
public void setButtonGroupChanged(Closure buttonGroupChanged) {
this.buttonGroupChanged = buttonGroupChanged;
if (this.buttonGroupChanged != null) {
this.buttonGroupChanged.setDelegate(this);
this.buttonGroupChanged.setResolveStrategy(Closure.DELEGATE_FIRST);
}
}
public void actionChanged(org.apache.pivot.wtk.Button arg0, org.apache.pivot.wtk.Action arg1) {
if (actionChanged != null) {
actionChanged.call(arg0, arg1);
}
}
public void buttonDataChanged(org.apache.pivot.wtk.Button arg0, java.lang.Object arg1) {
if (buttonDataChanged != null) {
buttonDataChanged.call(arg0, arg1);
}
}
public void dataRendererChanged(org.apache.pivot.wtk.Button arg0, org.apache.pivot.wtk.Button.DataRenderer arg1) {
if (dataRendererChanged != null) {
dataRendererChanged.call(arg0, arg1);
}
}
public void toggleButtonChanged(org.apache.pivot.wtk.Button arg0) {
if (toggleButtonChanged != null) {
toggleButtonChanged.call(arg0);
}
}
public void triStateChanged(org.apache.pivot.wtk.Button arg0) {
if (triStateChanged != null) {
triStateChanged.call(arg0);
}
}
public void buttonGroupChanged(org.apache.pivot.wtk.Button arg0, org.apache.pivot.wtk.ButtonGroup arg1) {
if (buttonGroupChanged != null) {
buttonGroupChanged.call(arg0, arg1);
}
}
}
| apache-2.0 |
quarkusio/quarkus | integration-tests/smallrye-context-propagation/src/test/java/io/quarkus/context/test/CustomProducersTest.java | 1229 | package io.quarkus.context.test;
import javax.inject.Inject;
import org.eclipse.microprofile.context.ManagedExecutor;
import org.eclipse.microprofile.context.ThreadContext;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.arc.ClientProxy;
import io.quarkus.test.QuarkusUnitTest;
/**
* Tests that user can override default beans for {@code ManagedExecutor} and {@code ThreadContext}.
* Default beans are singletons (no proxy) whereas the newly defined beans here are application scoped.
* Therefore it is enough to check that the injected values are proxied.
*/
public class CustomProducersTest {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(ProducerBean.class));
@Inject
ManagedExecutor me;
@Inject
ThreadContext tc;
@Test
public void testDefaultBeansCanBeOverriden() {
Assertions.assertNotNull(me);
Assertions.assertNotNull(tc);
Assertions.assertTrue(me instanceof ClientProxy);
Assertions.assertTrue(tc instanceof ClientProxy);
}
}
| apache-2.0 |
geosolutions-it/jeo | core/src/main/java/org/jeo/JEO.java | 2003 | package org.jeo;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JEO {
public static Logger LOG = LoggerFactory.getLogger(JEO.class);
/**
* Returns the version of this build.
*/
public static String version() {
return property("version");
}
/**
* Returns the git revision of this build.
*/
public static String revision() {
return property("revision");
}
/**
* Returns the timestamp of this build.
*/
public static Date buildDate() {
String buildDate = property("buildDate");
try {
return buildDate != null ? dateFormat().parse(buildDate) : null;
} catch (ParseException e) {
LOG.debug("Error parsing build date: " + buildDate, e);
}
return null;
}
static SimpleDateFormat dateFormat() {
return new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ssZ");
}
static String property(String key) {
try {
InputStream in = JEO.class.getResourceAsStream("build.properties");
try {
Properties props = new Properties();
props.load(in);
return props.getProperty(key);
}
finally {
in.close();
}
}
catch(IOException e) {
LOG.debug("Error getting build property " + key, e);
}
return null;
}
/**
* Prints version info to stdout.
*/
public static void main(String[] args) {
printVersionInfo(System.out);
}
/**
* Prints version info for the library.
*/
public static void printVersionInfo(PrintStream out) {
out.println(String.format("jeo %s (%s)", version(), revision()));
}
}
| apache-2.0 |
yliu120/ErrorCorrection | src/edu/jhu/cs/cs439/project/evaluation/package-info.java | 297 | /**
* The evaluation of the count
* In this package, we will implement some tools to compare
* the exact count and the approximate count given by the
* count min sketch
* @author Yunlong Liu
* @author Yijie Li
* @version 1.0
* @since 1.0
*/
package edu.jhu.cs.cs439.project.evaluation; | apache-2.0 |
Greg3dot14D/PageObjectWithLocatorCorrector | src/main/java/ru/greg3d/factory/elements/ElementFactory.java | 205 | package ru.greg3d.factory.elements;
import org.openqa.selenium.WebElement;
public interface ElementFactory {
<E extends TypifiedElement> E create(Class<E> elementClass, WebElement wrappedElement);
}
| apache-2.0 |
dimir2/vivanov | part2/ch2/src/main/java/ru/job4j/multithreading/monitor/package-info.java | 169 | /**
* Package for ru.job4j.multithreading.monitor task.
*
* @author Vladimir Ivanov
* @version 0.1
* @since 28.11.2017
*/
package ru.job4j.multithreading.monitor; | apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p81/Production1621.java | 2129 | package org.gradle.test.performance.mediummonolithicjavaproject.p81;
import org.gradle.test.performance.mediummonolithicjavaproject.p80.Production1618;
import org.gradle.test.performance.mediummonolithicjavaproject.p80.Production1619;
public class Production1621 {
private Production1618 property0;
public Production1618 getProperty0() {
return property0;
}
public void setProperty0(Production1618 value) {
property0 = value;
}
private Production1619 property1;
public Production1619 getProperty1() {
return property1;
}
public void setProperty1(Production1619 value) {
property1 = value;
}
private Production1620 property2;
public Production1620 getProperty2() {
return property2;
}
public void setProperty2(Production1620 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 |
arnost-starosta/midpoint | model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestCaseManagement.java | 3802 | /*
* Copyright (c) 2010-2017 Evolveum
*
* 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.evolveum.midpoint.model.impl.misc;
import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest;
import com.evolveum.midpoint.model.impl.controller.ModelController;
import com.evolveum.midpoint.model.impl.lens.Clockwork;
import com.evolveum.midpoint.model.impl.lens.projector.Projector;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.SearchResultList;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.test.util.MidPointTestConstants;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseWorkItemType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.Test;
import java.io.File;
import static org.testng.AssertJUnit.assertEquals;
/**
* @author mederly
*
*/
@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestCaseManagement extends AbstractInternalModelIntegrationTest {
protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "misc");
protected static final File USER1_FILE = new File(TEST_DIR, "user1.xml");
protected static final File USER2_FILE = new File(TEST_DIR, "user2.xml");
protected static final File CASE1_FILE = new File(TEST_DIR, "case1.xml");
protected static final File CASE2_FILE = new File(TEST_DIR, "case2.xml");
protected static final File CASE3_FILE = new File(TEST_DIR, "case3.xml");
@Autowired protected ModelController controller;
@Autowired protected Projector projector;
@Autowired protected Clockwork clockwork;
@Autowired protected TaskManager taskManager;
private PrismObject<UserType> user1, user2;
private PrismObject<CaseType> case1, case2, case3;
@Override
public void initSystem(Task initTask, OperationResult initResult) throws Exception {
super.initSystem(initTask, initResult);
user1 = repoAddObjectFromFile(USER1_FILE, initResult);
user2 = repoAddObjectFromFile(USER2_FILE, initResult);
case1 = repoAddObjectFromFile(CASE1_FILE, initResult);
case2 = repoAddObjectFromFile(CASE2_FILE, initResult);
case3 = repoAddObjectFromFile(CASE3_FILE, initResult);
}
@Test
public void test100SearchCases() throws Exception {
final String TEST_NAME = "test100CreateCase";
Task task = taskManager.createTaskInstance(TEST_NAME);
OperationResult result = task.getResult();
login(userAdministrator);
SearchResultList<PrismObject<CaseType>> cases = controller.searchObjects(CaseType.class, null, null, task, result);
assertEquals(3, cases.size());
SearchResultList<CaseWorkItemType> workItems = controller.searchContainers(CaseWorkItemType.class, null, null, task, result);
assertEquals(4, workItems.size());
}
}
| apache-2.0 |
lefou/asciidoctorj | asciidoctorj-core/src/main/java/org/asciidoctor/extension/JavaExtensionRegistry.java | 2846 | package org.asciidoctor.extension;
public interface JavaExtensionRegistry {
JavaExtensionRegistry docinfoProcessor(Class<? extends DocinfoProcessor> docInfoProcessor);
JavaExtensionRegistry docinfoProcessor(DocinfoProcessor docInfoProcessor);
JavaExtensionRegistry docinfoProcessor(String docInfoProcessor);
JavaExtensionRegistry preprocessor(Class<? extends Preprocessor> preprocessor);
JavaExtensionRegistry preprocessor(Preprocessor preprocessor);
JavaExtensionRegistry preprocessor(String preprocessor);
JavaExtensionRegistry postprocessor(String postprocessor);
JavaExtensionRegistry postprocessor(Class<? extends Postprocessor> postprocessor);
JavaExtensionRegistry postprocessor(Postprocessor postprocessor);
JavaExtensionRegistry includeProcessor(String includeProcessor);
JavaExtensionRegistry includeProcessor(
Class<? extends IncludeProcessor> includeProcessor);
JavaExtensionRegistry includeProcessor(IncludeProcessor includeProcessor);
JavaExtensionRegistry treeprocessor(Treeprocessor treeprocessor);
JavaExtensionRegistry treeprocessor(Class<? extends Treeprocessor> abstractTreeProcessor);
JavaExtensionRegistry treeprocessor(String treeProcessor);
JavaExtensionRegistry block(String blockName,
String blockProcessor);
JavaExtensionRegistry block(String blockProcessor);
JavaExtensionRegistry block(String blockName,
Class<? extends BlockProcessor> blockProcessor);
JavaExtensionRegistry block(Class<? extends BlockProcessor> blockProcessor);
JavaExtensionRegistry block(BlockProcessor blockProcessor);
JavaExtensionRegistry block(String blockName,
BlockProcessor blockProcessor);
JavaExtensionRegistry blockMacro(String blockName,
Class<? extends BlockMacroProcessor> blockMacroProcessor);
JavaExtensionRegistry blockMacro(Class<? extends BlockMacroProcessor> blockMacroProcessor);
JavaExtensionRegistry blockMacro(String blockName,
String blockMacroProcessor);
JavaExtensionRegistry blockMacro(String blockMacroProcessor);
JavaExtensionRegistry blockMacro(BlockMacroProcessor blockMacroProcessor);
JavaExtensionRegistry inlineMacro(InlineMacroProcessor inlineMacroProcessor);
JavaExtensionRegistry inlineMacro(String blockName,
Class<? extends InlineMacroProcessor> inlineMacroProcessor);
JavaExtensionRegistry inlineMacro(Class<? extends InlineMacroProcessor> inlineMacroProcessor);
JavaExtensionRegistry inlineMacro(String blockName, String inlineMacroProcessor);
JavaExtensionRegistry inlineMacro(String inlineMacroProcessor);
}
| apache-2.0 |
akarnokd/Reactive4JavaFlow | src/main/java/hu/akarnokd/reactive4javaflow/impl/consumers/BlockingConsumerIgnore.java | 1898 | /*
* Copyright 2017 David Karnok
*
* 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 hu.akarnokd.reactive4javaflow.impl.consumers;
import hu.akarnokd.reactive4javaflow.*;
import hu.akarnokd.reactive4javaflow.functionals.AutoDisposable;
import hu.akarnokd.reactive4javaflow.impl.*;
import hu.akarnokd.reactive4javaflow.impl.util.SpscCountDownLatch;
import java.lang.invoke.*;
import java.util.concurrent.Flow;
public final class BlockingConsumerIgnore extends SpscCountDownLatch implements FolyamSubscriber<Object>, AutoDisposable {
Flow.Subscription upstream;
static final VarHandle UPSTREAM = VH.find(MethodHandles.lookup(), BlockingConsumerIgnore.class, "upstream", Flow.Subscription.class);
public BlockingConsumerIgnore() {
super();
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
if (SubscriptionHelper.replace(this, UPSTREAM, subscription)) {
subscription.request(Long.MAX_VALUE);
}
}
@Override
public void onNext(Object item) {
// deliberately ignored
}
@Override
public void onError(Throwable throwable) {
FolyamPlugins.onError(throwable);
countDown();
}
@Override
public void onComplete() {
countDown();
}
@Override
public void close() {
SubscriptionHelper.cancel(this, UPSTREAM);
}
}
| apache-2.0 |
dayutianfei/impala-Q | fe/generated-sources/gen-java/com/cloudera/impala/thrift/TReportExecStatusResult.java | 12391 | /**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.cloudera.impala.thrift;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TReportExecStatusResult implements org.apache.thrift.TBase<TReportExecStatusResult, TReportExecStatusResult._Fields>, java.io.Serializable, Cloneable {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TReportExecStatusResult");
private static final org.apache.thrift.protocol.TField STATUS_FIELD_DESC = new org.apache.thrift.protocol.TField("status", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new TReportExecStatusResultStandardSchemeFactory());
schemes.put(TupleScheme.class, new TReportExecStatusResultTupleSchemeFactory());
}
public com.cloudera.impala.thrift.TStatus status; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
STATUS((short)1, "status");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // STATUS
return STATUS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private _Fields optionals[] = {_Fields.STATUS};
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.STATUS, new org.apache.thrift.meta_data.FieldMetaData("status", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, com.cloudera.impala.thrift.TStatus.class)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TReportExecStatusResult.class, metaDataMap);
}
public TReportExecStatusResult() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public TReportExecStatusResult(TReportExecStatusResult other) {
if (other.isSetStatus()) {
this.status = new com.cloudera.impala.thrift.TStatus(other.status);
}
}
public TReportExecStatusResult deepCopy() {
return new TReportExecStatusResult(this);
}
@Override
public void clear() {
this.status = null;
}
public com.cloudera.impala.thrift.TStatus getStatus() {
return this.status;
}
public TReportExecStatusResult setStatus(com.cloudera.impala.thrift.TStatus status) {
this.status = status;
return this;
}
public void unsetStatus() {
this.status = null;
}
/** Returns true if field status is set (has been assigned a value) and false otherwise */
public boolean isSetStatus() {
return this.status != null;
}
public void setStatusIsSet(boolean value) {
if (!value) {
this.status = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case STATUS:
if (value == null) {
unsetStatus();
} else {
setStatus((com.cloudera.impala.thrift.TStatus)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case STATUS:
return getStatus();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case STATUS:
return isSetStatus();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof TReportExecStatusResult)
return this.equals((TReportExecStatusResult)that);
return false;
}
public boolean equals(TReportExecStatusResult that) {
if (that == null)
return false;
boolean this_present_status = true && this.isSetStatus();
boolean that_present_status = true && that.isSetStatus();
if (this_present_status || that_present_status) {
if (!(this_present_status && that_present_status))
return false;
if (!this.status.equals(that.status))
return false;
}
return true;
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
boolean present_status = true && (isSetStatus());
builder.append(present_status);
if (present_status)
builder.append(status);
return builder.toHashCode();
}
public int compareTo(TReportExecStatusResult other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
TReportExecStatusResult typedOther = (TReportExecStatusResult)other;
lastComparison = Boolean.valueOf(isSetStatus()).compareTo(typedOther.isSetStatus());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetStatus()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.status, typedOther.status);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TReportExecStatusResult(");
boolean first = true;
if (isSetStatus()) {
sb.append("status:");
if (this.status == null) {
sb.append("null");
} else {
sb.append(this.status);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (status != null) {
status.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class TReportExecStatusResultStandardSchemeFactory implements SchemeFactory {
public TReportExecStatusResultStandardScheme getScheme() {
return new TReportExecStatusResultStandardScheme();
}
}
private static class TReportExecStatusResultStandardScheme extends StandardScheme<TReportExecStatusResult> {
public void read(org.apache.thrift.protocol.TProtocol iprot, TReportExecStatusResult struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // STATUS
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.status = new com.cloudera.impala.thrift.TStatus();
struct.status.read(iprot);
struct.setStatusIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, TReportExecStatusResult struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.status != null) {
if (struct.isSetStatus()) {
oprot.writeFieldBegin(STATUS_FIELD_DESC);
struct.status.write(oprot);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class TReportExecStatusResultTupleSchemeFactory implements SchemeFactory {
public TReportExecStatusResultTupleScheme getScheme() {
return new TReportExecStatusResultTupleScheme();
}
}
private static class TReportExecStatusResultTupleScheme extends TupleScheme<TReportExecStatusResult> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, TReportExecStatusResult struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetStatus()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetStatus()) {
struct.status.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, TReportExecStatusResult struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.status = new com.cloudera.impala.thrift.TStatus();
struct.status.read(iprot);
struct.setStatusIsSet(true);
}
}
}
}
| apache-2.0 |
tianyaTTY/renren-security-master | renren-web/src/main/java/io/renren/controller/YlSpecialistController.java | 3310 | package io.renren.controller;
import io.renren.annotation.SysLog;
import io.renren.entity.YlDepartmentEntity;
import io.renren.entity.YlHospitalEntity;
import io.renren.entity.YlOrganizationEntity;
import io.renren.entity.YlSpecialistEntity;
import io.renren.service.YlDepartmentService;
import io.renren.service.YlHospitalService;
import io.renren.service.YlOrganizationService;
import io.renren.service.YlSpecialistService;
import io.renren.utils.PageUtils;
import io.renren.utils.Query;
import io.renren.utils.R;
import io.renren.validator.ValidatorUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 专家信息
*
* @author tangty
* @email tianyaTTY@gmail.com
* @date 2017年7月11日 下午6:43:36
*/
@RestController
@RequestMapping("/yl/specialist")
public class YlSpecialistController extends AbstractController {
@Autowired
private YlSpecialistService ylSpecialistService;
@Autowired
private YlDepartmentService ylDepartmentService;
@Autowired
private YlHospitalService ylHospitalService;
@Autowired
private YlOrganizationService ylOrganizationService;
/**
* 所有专家信息列表
*/
@RequestMapping("/list")
@RequiresPermissions("yl:specialist:list")
public R list(@RequestParam Map<String, Object> params){
//查询列表数据
Query query = new Query(params);
List<YlSpecialistEntity> specialistList = ylSpecialistService.queryList(query);
int total = ylSpecialistService.queryTotal(query);
PageUtils pageUtil = new PageUtils(specialistList, total, query.getLimit(), query.getPage());
return R.ok().put("page", pageUtil);
}
/**
* 配置专家信息
*/
@RequestMapping("/info/{id}")
@RequiresPermissions("yl:specialist:info")
public R info(@PathVariable("id") Integer id){
YlSpecialistEntity specialist = ylSpecialistService.queryObject(id);
YlDepartmentEntity department = ylDepartmentService.queryObject(specialist.getDepartment());
YlHospitalEntity hospital = ylHospitalService.queryObject(department.getHospitalId());
YlOrganizationEntity organization = ylOrganizationService.queryObject(hospital.getOrgId());
return R.ok().put("specialist",specialist).put("department", department).put("hospital",hospital).put("organization",organization);
}
/**
* 保存专家信息
*/
@SysLog("保存专家信息")
@RequestMapping("/save")
@RequiresPermissions("yl:specialist:save")
public R save(@RequestBody YlSpecialistEntity specialist){
ValidatorUtils.validateEntity(specialist);
ylSpecialistService.save(specialist);
return R.ok();
}
/**
* 修改专家信息
*/
@SysLog("修改专家信息")
@RequestMapping("/update")
@RequiresPermissions("yl:specialist:update")
public R update(@RequestBody YlSpecialistEntity specialist){
ValidatorUtils.validateEntity(specialist);
ylSpecialistService.update(specialist);
return R.ok();
}
/**
* 删除专家信息
*/
@SysLog("删除科室信息")
@RequestMapping("/delete")
@RequiresPermissions("yl:specialist:delete")
public R delete(@RequestBody Integer[] ids){
//TODO 关联删除需要做
ylSpecialistService.deleteBatch(ids);
return R.ok();
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-documentai/v1beta3/1.30.1/com/google/api/services/documentai/v1beta3/model/GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue.java | 7120 | /*
* 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.documentai.v1beta3.model;
/**
* Parsed and normalized entity value.
*
* <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 Document AI 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 GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue extends com.google.api.client.json.GenericJson {
/**
* Postal address. See also: https: //github.com/googleapis/googleapis/blob/ //
* master/google/type/postal_address.proto
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleTypePostalAddress addressValue;
/**
* Date value. Includes year, month, day. See also: https:
* //github.com/googleapis/googleapis/blob/master/google/type/date.proto
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleTypeDate dateValue;
/**
* DateTime value. Includes date, time, and timezone. See also: https:
* //github.com/googleapis/googleapis/blob/ // master/google/type/datetime.proto
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleTypeDateTime datetimeValue;
/**
* Money value. See also: https: //github.com/googleapis/googleapis/blob/ //
* master/google/type/money.proto
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleTypeMoney moneyValue;
/**
* Required. Normalized entity value stored as a string. This field is populated for supported
* document type (e.g. Invoice). For some entity types, one of respective 'structured_value'
* fields may also be populated. - Money/Currency type (`money_value`) is in the ISO 4217 text
* format. - Date type (`date_value`) is in the ISO 8601 text format. - Datetime type
* (`datetime_value`) is in the ISO 8601 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String text;
/**
* Postal address. See also: https: //github.com/googleapis/googleapis/blob/ //
* master/google/type/postal_address.proto
* @return value or {@code null} for none
*/
public GoogleTypePostalAddress getAddressValue() {
return addressValue;
}
/**
* Postal address. See also: https: //github.com/googleapis/googleapis/blob/ //
* master/google/type/postal_address.proto
* @param addressValue addressValue or {@code null} for none
*/
public GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue setAddressValue(GoogleTypePostalAddress addressValue) {
this.addressValue = addressValue;
return this;
}
/**
* Date value. Includes year, month, day. See also: https:
* //github.com/googleapis/googleapis/blob/master/google/type/date.proto
* @return value or {@code null} for none
*/
public GoogleTypeDate getDateValue() {
return dateValue;
}
/**
* Date value. Includes year, month, day. See also: https:
* //github.com/googleapis/googleapis/blob/master/google/type/date.proto
* @param dateValue dateValue or {@code null} for none
*/
public GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue setDateValue(GoogleTypeDate dateValue) {
this.dateValue = dateValue;
return this;
}
/**
* DateTime value. Includes date, time, and timezone. See also: https:
* //github.com/googleapis/googleapis/blob/ // master/google/type/datetime.proto
* @return value or {@code null} for none
*/
public GoogleTypeDateTime getDatetimeValue() {
return datetimeValue;
}
/**
* DateTime value. Includes date, time, and timezone. See also: https:
* //github.com/googleapis/googleapis/blob/ // master/google/type/datetime.proto
* @param datetimeValue datetimeValue or {@code null} for none
*/
public GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue setDatetimeValue(GoogleTypeDateTime datetimeValue) {
this.datetimeValue = datetimeValue;
return this;
}
/**
* Money value. See also: https: //github.com/googleapis/googleapis/blob/ //
* master/google/type/money.proto
* @return value or {@code null} for none
*/
public GoogleTypeMoney getMoneyValue() {
return moneyValue;
}
/**
* Money value. See also: https: //github.com/googleapis/googleapis/blob/ //
* master/google/type/money.proto
* @param moneyValue moneyValue or {@code null} for none
*/
public GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue setMoneyValue(GoogleTypeMoney moneyValue) {
this.moneyValue = moneyValue;
return this;
}
/**
* Required. Normalized entity value stored as a string. This field is populated for supported
* document type (e.g. Invoice). For some entity types, one of respective 'structured_value'
* fields may also be populated. - Money/Currency type (`money_value`) is in the ISO 4217 text
* format. - Date type (`date_value`) is in the ISO 8601 text format. - Datetime type
* (`datetime_value`) is in the ISO 8601 text format.
* @return value or {@code null} for none
*/
public java.lang.String getText() {
return text;
}
/**
* Required. Normalized entity value stored as a string. This field is populated for supported
* document type (e.g. Invoice). For some entity types, one of respective 'structured_value'
* fields may also be populated. - Money/Currency type (`money_value`) is in the ISO 4217 text
* format. - Date type (`date_value`) is in the ISO 8601 text format. - Datetime type
* (`datetime_value`) is in the ISO 8601 text format.
* @param text text or {@code null} for none
*/
public GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue setText(java.lang.String text) {
this.text = text;
return this;
}
@Override
public GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue set(String fieldName, Object value) {
return (GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue) super.set(fieldName, value);
}
@Override
public GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue clone() {
return (GoogleCloudDocumentaiV1beta2DocumentEntityNormalizedValue) super.clone();
}
}
| apache-2.0 |
Microbule/microbule | timeout/src/test/java/org/microbule/timeout/decorator/DelayResourceImpl.java | 1521 | /*
* Copyright (c) 2017 The Microbule Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.microbule.timeout.decorator;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.awaitility.Awaitility.await;
public class DelayResourceImpl implements DelayResource {
//----------------------------------------------------------------------------------------------------------------------
// DelayResource Implementation
//----------------------------------------------------------------------------------------------------------------------
private static final Logger LOGGER = LoggerFactory.getLogger(DelayResourceImpl.class);
@Override
public String delay(long value) {
LOGGER.info("Delaying {} ms...", value);
final long expiration = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(value);
await().until(() -> System.nanoTime() >= expiration);
return String.valueOf(value);
}
}
| apache-2.0 |
m0wfo/osprey | src/main/java/com/logentries/osprey/Client.java | 2622 | package com.logentries.osprey;
import akka.actor.ActorRef;
import akka.actor.UntypedActor;
import akka.io.Tcp;
import akka.io.Tcp.*;
import akka.io.TcpMessage;
import akka.japi.Procedure;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import scala.Option;
import java.io.Serializable;
import java.net.InetSocketAddress;
/**
* Forwards messages onto a backend.
*/
class Client extends UntypedActor {
/**
* Exception used to signify the failure of a backend connection.
*
* <p>This indicates to a supervising actor/router that it should restart this client.</p>
*/
static class ClientException extends RuntimeException implements Serializable {
}
private static final String BACKEND_PORT = "backend.port";
private final DynamicIntProperty backendPort;
/**
* A connected client assumes the behaviour of this connection handler
* when a connection is successfully established with its backend.
*/
private class ConnectionHandler implements Procedure<Object> {
private final ActorRef connection;
private ActorRef receiver;
public ConnectionHandler(ActorRef connection) {
this.connection = connection;
}
@Override
public void apply(Object msg) {
if (msg instanceof CommandFailed) {
// OS kernel socket buffer was full
throw new ClientException();
} else if (msg instanceof ClientRequest) {
ClientRequest request = (ClientRequest) msg;
receiver = sender();
connection.tell(TcpMessage.write(request.getReceived().data()), self());
} else if (msg instanceof Received) {
receiver.tell((ClientResponse) () -> (Received) msg, self());
} else if (msg instanceof ConnectionClosed) {
throw new ClientException();
}
}
}
private final ActorRef ioActor;
public Client() {
this.backendPort = DynamicPropertyFactory.getInstance().getIntProperty(BACKEND_PORT, 0);
this.ioActor = Tcp.get(context().system()).manager();
}
@Override
public void preStart() {
ioActor.tell(TcpMessage.connect(new InetSocketAddress("localhost", backendPort.get())), self());
}
@Override
public void preRestart(Throwable err, Option<Object> msg) {
ioActor.tell(TcpMessage.close(), self());
}
@Override
public void onReceive(Object message) {
if (message instanceof CommandFailed) {
throw new ClientException();
} else if (message instanceof Connected) {
sender().tell(TcpMessage.register(self()), self());
getContext().become(new ConnectionHandler(sender()));
} else if (message instanceof ConnectionClosed) {
throw new ClientException();
} else {
unhandled(message);
}
}
}
| apache-2.0 |
erichwang/presto | presto-parquet/src/main/java/io/prestosql/parquet/ParquetReaderOptions.java | 3385 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.parquet;
import io.airlift.units.DataSize;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.util.Objects.requireNonNull;
public class ParquetReaderOptions
{
private static final DataSize DEFAULT_MAX_READ_BLOCK_SIZE = DataSize.of(16, MEGABYTE);
private static final DataSize DEFAULT_MAX_MERGE_DISTANCE = DataSize.of(1, MEGABYTE);
private static final DataSize DEFAULT_MAX_BUFFER_SIZE = DataSize.of(8, MEGABYTE);
private final boolean ignoreStatistics;
private final DataSize maxReadBlockSize;
private final DataSize maxMergeDistance;
private final DataSize maxBufferSize;
public ParquetReaderOptions()
{
ignoreStatistics = false;
maxReadBlockSize = DEFAULT_MAX_READ_BLOCK_SIZE;
maxMergeDistance = DEFAULT_MAX_MERGE_DISTANCE;
maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
}
private ParquetReaderOptions(
boolean ignoreStatistics,
DataSize maxReadBlockSize,
DataSize maxMergeDistance,
DataSize maxBufferSize)
{
this.ignoreStatistics = ignoreStatistics;
this.maxReadBlockSize = requireNonNull(maxReadBlockSize, "maxMergeDistance is null");
this.maxMergeDistance = requireNonNull(maxMergeDistance, "maxMergeDistance is null");
this.maxBufferSize = requireNonNull(maxBufferSize, "maxBufferSize is null");
}
public boolean isIgnoreStatistics()
{
return ignoreStatistics;
}
public DataSize getMaxReadBlockSize()
{
return maxReadBlockSize;
}
public DataSize getMaxMergeDistance()
{
return maxMergeDistance;
}
public DataSize getMaxBufferSize()
{
return maxBufferSize;
}
public ParquetReaderOptions withIgnoreStatistics(boolean ignoreStatistics)
{
return new ParquetReaderOptions(
ignoreStatistics,
maxReadBlockSize,
maxMergeDistance,
maxBufferSize);
}
public ParquetReaderOptions withMaxReadBlockSize(DataSize maxReadBlockSize)
{
return new ParquetReaderOptions(
ignoreStatistics,
maxReadBlockSize,
maxMergeDistance,
maxBufferSize);
}
public ParquetReaderOptions withMaxMergeDistance(DataSize maxMergeDistance)
{
return new ParquetReaderOptions(
ignoreStatistics,
maxReadBlockSize,
maxMergeDistance,
maxBufferSize);
}
public ParquetReaderOptions withMaxBufferSize(DataSize maxBufferSize)
{
return new ParquetReaderOptions(
ignoreStatistics,
maxReadBlockSize,
maxMergeDistance,
maxBufferSize);
}
}
| apache-2.0 |
jdillon/gshell | gshell-commands/gshell-file/src/main/java/com/planet57/gshell/commands/file/FileCommandActionSupport.java | 1282 | /*
* Copyright (c) 2009-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.planet57.gshell.commands.file;
import static com.google.common.base.Preconditions.checkState;
import javax.inject.Inject;
import com.planet57.gshell.command.CommandActionSupport;
import com.planet57.gshell.util.io.FileSystemAccess;
/**
* Support file {@code file} actions.
*
* @since 3.0
*/
public abstract class FileCommandActionSupport
extends CommandActionSupport
{
private FileSystemAccess fileSystem;
@Inject
public void setFileSystem(final FileSystemAccess fileSystem) {
this.fileSystem = fileSystem;
}
protected FileSystemAccess getFileSystem() {
checkState(fileSystem != null);
return fileSystem;
}
}
| apache-2.0 |
oehf/ipf | commons/ihe/xds/src/main/java/org/openehealth/ipf/commons/ihe/xds/core/stub/ebrs30/query/PersonQueryType.java | 5743 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1.9-03/31/2009 04:14 PM(snajper)-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.04.30 at 06:20:20 PM CEST
//
package org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.query;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for PersonQueryType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PersonQueryType">
* <complexContent>
* <extension base="{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}RegistryObjectQueryType">
* <sequence>
* <element name="AddressFilter" type="{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}FilterType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="PersonNameFilter" type="{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}FilterType" minOccurs="0"/>
* <element name="TelephoneNumberFilter" type="{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}FilterType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="EmailAddressFilter" type="{urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0}FilterType" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PersonQueryType", propOrder = {
"addressFilter",
"personNameFilter",
"telephoneNumberFilter",
"emailAddressFilter"
})
@XmlSeeAlso({
UserQueryType.class
})
public class PersonQueryType
extends RegistryObjectQueryType
{
@XmlElement(name = "AddressFilter")
protected List<FilterType> addressFilter;
@XmlElement(name = "PersonNameFilter")
protected FilterType personNameFilter;
@XmlElement(name = "TelephoneNumberFilter")
protected List<FilterType> telephoneNumberFilter;
@XmlElement(name = "EmailAddressFilter")
protected List<FilterType> emailAddressFilter;
/**
* Gets the value of the addressFilter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the addressFilter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAddressFilter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FilterType }
*
*
*/
public List<FilterType> getAddressFilter() {
if (addressFilter == null) {
addressFilter = new ArrayList<>();
}
return this.addressFilter;
}
/**
* Gets the value of the personNameFilter property.
*
* @return
* possible object is
* {@link FilterType }
*
*/
public FilterType getPersonNameFilter() {
return personNameFilter;
}
/**
* Sets the value of the personNameFilter property.
*
* @param value
* allowed object is
* {@link FilterType }
*
*/
public void setPersonNameFilter(FilterType value) {
this.personNameFilter = value;
}
/**
* Gets the value of the telephoneNumberFilter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the telephoneNumberFilter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTelephoneNumberFilter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FilterType }
*
*
*/
public List<FilterType> getTelephoneNumberFilter() {
if (telephoneNumberFilter == null) {
telephoneNumberFilter = new ArrayList<>();
}
return this.telephoneNumberFilter;
}
/**
* Gets the value of the emailAddressFilter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the emailAddressFilter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEmailAddressFilter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FilterType }
*
*
*/
public List<FilterType> getEmailAddressFilter() {
if (emailAddressFilter == null) {
emailAddressFilter = new ArrayList<>();
}
return this.emailAddressFilter;
}
}
| apache-2.0 |
hrovira/addama-googlecode | local-svcs/script-execution-svc/src/main/java/org/systemsbiology/addama/services/execution/dao/impls/jdbc/ResetJobPreparedStatementSetter.java | 806 | package org.systemsbiology.addama.services.execution.dao.impls.jdbc;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.systemsbiology.addama.services.execution.jobs.JobStatus;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @author hrovira
*/
public class ResetJobPreparedStatementSetter implements PreparedStatementSetter {
private final JobStatus currentStatus;
private final JobStatus newStatus;
public ResetJobPreparedStatementSetter(JobStatus currentStatus, JobStatus newstatus) {
this.currentStatus = currentStatus;
this.newStatus = newstatus;
}
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, newStatus.name());
ps.setString(2, currentStatus.name());
}
}
| apache-2.0 |
Zhangshunyu/incubator-carbondata | integration/spark/src/main/java/org/apache/carbondata/integration/spark/merger/RowResultMerger.java | 13600 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.carbondata.integration.spark.merger;
import java.io.File;
import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.carbon.CarbonTableIdentifier;
import org.apache.carbondata.core.carbon.datastore.block.SegmentProperties;
import org.apache.carbondata.core.carbon.metadata.CarbonMetadata;
import org.apache.carbondata.core.carbon.metadata.schema.table.CarbonTable;
import org.apache.carbondata.core.carbon.metadata.schema.table.column.CarbonDimension;
import org.apache.carbondata.core.carbon.metadata.schema.table.column.CarbonMeasure;
import org.apache.carbondata.core.carbon.metadata.schema.table.column.ColumnSchema;
import org.apache.carbondata.core.carbon.path.CarbonStorePath;
import org.apache.carbondata.core.carbon.path.CarbonTablePath;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.keygenerator.KeyGenException;
import org.apache.carbondata.core.util.ByteUtil;
import org.apache.carbondata.core.util.CarbonUtil;
import org.apache.carbondata.core.util.DataTypeUtil;
import org.apache.carbondata.processing.datatypes.GenericDataType;
import org.apache.carbondata.processing.merger.exeception.SliceMergerException;
import org.apache.carbondata.processing.store.CarbonDataFileAttributes;
import org.apache.carbondata.processing.store.CarbonFactDataHandlerColumnar;
import org.apache.carbondata.processing.store.CarbonFactDataHandlerModel;
import org.apache.carbondata.processing.store.CarbonFactHandler;
import org.apache.carbondata.processing.store.writer.exception.CarbonDataWriterException;
import org.apache.carbondata.scan.result.iterator.RawResultIterator;
import org.apache.carbondata.scan.wrappers.ByteArrayWrapper;
import org.apache.carbondata.spark.load.CarbonLoadModel;
/**
* This is the Merger class responsible for the merging of the segments.
*/
public class RowResultMerger {
private final String databaseName;
private final String tableName;
private final String tempStoreLocation;
private final int measureCount;
private final String factStoreLocation;
private CarbonFactHandler dataHandler;
private List<RawResultIterator> rawResultIteratorList =
new ArrayList<RawResultIterator>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);
private SegmentProperties segprop;
/**
* record holder heap
*/
private AbstractQueue<RawResultIterator> recordHolderHeap;
private TupleConversionAdapter tupleConvertor;
private static final LogService LOGGER =
LogServiceFactory.getLogService(RowResultMerger.class.getName());
public RowResultMerger(List<RawResultIterator> iteratorList, String databaseName,
String tableName, SegmentProperties segProp, String tempStoreLocation,
CarbonLoadModel loadModel, int[] colCardinality) {
this.rawResultIteratorList = iteratorList;
// create the List of RawResultIterator.
recordHolderHeap = new PriorityQueue<RawResultIterator>(rawResultIteratorList.size(),
new RowResultMerger.CarbonMdkeyComparator());
this.segprop = segProp;
this.tempStoreLocation = tempStoreLocation;
this.factStoreLocation = loadModel.getStorePath();
if (!new File(tempStoreLocation).mkdirs()) {
LOGGER.error("Error while new File(tempStoreLocation).mkdirs() ");
}
this.databaseName = databaseName;
this.tableName = tableName;
this.measureCount = segprop.getMeasures().size();
CarbonFactDataHandlerModel carbonFactDataHandlerModel =
getCarbonFactDataHandlerModel(loadModel);
carbonFactDataHandlerModel.setPrimitiveDimLens(segprop.getDimColumnsCardinality());
CarbonDataFileAttributes carbonDataFileAttributes =
new CarbonDataFileAttributes(Integer.parseInt(loadModel.getTaskNo()),
loadModel.getFactTimeStamp());
carbonFactDataHandlerModel.setCarbonDataFileAttributes(carbonDataFileAttributes);
if (segProp.getNumberOfNoDictionaryDimension() > 0
|| segProp.getComplexDimensions().size() > 0) {
carbonFactDataHandlerModel.setMdKeyIndex(measureCount + 1);
} else {
carbonFactDataHandlerModel.setMdKeyIndex(measureCount);
}
carbonFactDataHandlerModel.setColCardinality(colCardinality);
dataHandler = new CarbonFactDataHandlerColumnar(carbonFactDataHandlerModel);
tupleConvertor = new TupleConversionAdapter(segProp);
}
/**
* Merge function
*
*/
public boolean mergerSlice() {
boolean mergeStatus = false;
int index = 0;
try {
dataHandler.initialise();
// add all iterators to the queue
for (RawResultIterator leaftTupleIterator : this.rawResultIteratorList) {
this.recordHolderHeap.add(leaftTupleIterator);
index++;
}
RawResultIterator iterator = null;
while (index > 1) {
// iterator the top record
iterator = this.recordHolderHeap.poll();
Object[] convertedRow = iterator.next();
if(null == convertedRow){
throw new SliceMergerException("Unable to generate mdkey during compaction.");
}
// get the mdkey
addRow(convertedRow);
// if there is no record in the leaf and all then decrement the
// index
if (!iterator.hasNext()) {
index--;
continue;
}
// add record to heap
this.recordHolderHeap.add(iterator);
}
// if record holder is not empty then iterator the slice holder from
// heap
iterator = this.recordHolderHeap.poll();
while (true) {
Object[] convertedRow = iterator.next();
if(null == convertedRow){
throw new SliceMergerException("Unable to generate mdkey during compaction.");
}
addRow(convertedRow);
// check if leaf contains no record
if (!iterator.hasNext()) {
break;
}
}
this.dataHandler.finish();
mergeStatus = true;
} catch (Exception e) {
LOGGER.error("Exception in compaction merger " + e.getMessage());
mergeStatus = false;
} finally {
try {
this.dataHandler.closeHandler();
} catch (CarbonDataWriterException e) {
LOGGER.error("Exception while closing the handler in compaction merger " + e.getMessage());
mergeStatus = false;
}
}
return mergeStatus;
}
/**
* Below method will be used to add sorted row
*
* @throws SliceMergerException
*/
protected void addRow(Object[] carbonTuple) throws SliceMergerException {
Object[] rowInWritableFormat;
rowInWritableFormat = tupleConvertor.getObjectArray(carbonTuple);
try {
this.dataHandler.addDataToStore(rowInWritableFormat);
} catch (CarbonDataWriterException e) {
throw new SliceMergerException("Problem in merging the slice", e);
}
}
/**
* This method will create a model object for carbon fact data handler
*
* @param loadModel
* @return
*/
private CarbonFactDataHandlerModel getCarbonFactDataHandlerModel(CarbonLoadModel loadModel) {
CarbonFactDataHandlerModel carbonFactDataHandlerModel = new CarbonFactDataHandlerModel();
carbonFactDataHandlerModel.setDatabaseName(databaseName);
carbonFactDataHandlerModel.setTableName(tableName);
carbonFactDataHandlerModel.setMeasureCount(segprop.getMeasures().size());
carbonFactDataHandlerModel.setCompactionFlow(true);
carbonFactDataHandlerModel
.setMdKeyLength(segprop.getDimensionKeyGenerator().getKeySizeInBytes());
carbonFactDataHandlerModel.setStoreLocation(tempStoreLocation);
carbonFactDataHandlerModel.setDimLens(segprop.getDimColumnsCardinality());
carbonFactDataHandlerModel.setSegmentProperties(segprop);
carbonFactDataHandlerModel.setNoDictionaryCount(segprop.getNumberOfNoDictionaryDimension());
carbonFactDataHandlerModel.setDimensionCount(
segprop.getDimensions().size() - carbonFactDataHandlerModel.getNoDictionaryCount());
CarbonTable carbonTable = CarbonMetadata.getInstance()
.getCarbonTable(databaseName + CarbonCommonConstants.UNDERSCORE + tableName);
List<ColumnSchema> wrapperColumnSchema = CarbonUtil
.getColumnSchemaList(carbonTable.getDimensionByTableName(tableName),
carbonTable.getMeasureByTableName(tableName));
carbonFactDataHandlerModel.setWrapperColumnSchema(wrapperColumnSchema);
//TO-DO Need to handle complex types here .
Map<Integer, GenericDataType> complexIndexMap =
new HashMap<Integer, GenericDataType>(segprop.getComplexDimensions().size());
carbonFactDataHandlerModel.setComplexIndexMap(complexIndexMap);
carbonFactDataHandlerModel.setDataWritingRequest(true);
char[] aggType = new char[segprop.getMeasures().size()];
Arrays.fill(aggType, 'n');
int i = 0;
for (CarbonMeasure msr : segprop.getMeasures()) {
aggType[i++] = DataTypeUtil.getAggType(msr.getDataType());
}
carbonFactDataHandlerModel.setAggType(aggType);
carbonFactDataHandlerModel.setFactDimLens(segprop.getDimColumnsCardinality());
String carbonDataDirectoryPath =
checkAndCreateCarbonStoreLocation(this.factStoreLocation, databaseName, tableName,
loadModel.getPartitionId(), loadModel.getSegmentId());
carbonFactDataHandlerModel.setCarbonDataDirectoryPath(carbonDataDirectoryPath);
List<CarbonDimension> dimensionByTableName =
loadModel.getCarbonDataLoadSchema().getCarbonTable().getDimensionByTableName(tableName);
boolean[] isUseInvertedIndexes = new boolean[dimensionByTableName.size()];
int index = 0;
for (CarbonDimension dimension : dimensionByTableName) {
isUseInvertedIndexes[index++] = dimension.isUseInvertedIndnex();
}
carbonFactDataHandlerModel.setIsUseInvertedIndex(isUseInvertedIndexes);
return carbonFactDataHandlerModel;
}
/**
* This method will get the store location for the given path, segment id and partition id
*
* @return data directory path
*/
private String checkAndCreateCarbonStoreLocation(String factStoreLocation, String databaseName,
String tableName, String partitionId, String segmentId) {
String carbonStorePath = factStoreLocation;
CarbonTable carbonTable = CarbonMetadata.getInstance()
.getCarbonTable(databaseName + CarbonCommonConstants.UNDERSCORE + tableName);
CarbonTableIdentifier carbonTableIdentifier = carbonTable.getCarbonTableIdentifier();
CarbonTablePath carbonTablePath =
CarbonStorePath.getCarbonTablePath(carbonStorePath, carbonTableIdentifier);
String carbonDataDirectoryPath =
carbonTablePath.getCarbonDataDirectoryPath(partitionId, segmentId);
CarbonUtil.checkAndCreateFolder(carbonDataDirectoryPath);
return carbonDataDirectoryPath;
}
/**
* Comparator class for comparing 2 raw row result.
*/
private class CarbonMdkeyComparator implements Comparator<RawResultIterator> {
@Override public int compare(RawResultIterator o1, RawResultIterator o2) {
Object[] row1 = new Object[0];
Object[] row2 = new Object[0];
try {
row1 = o1.fetchConverted();
row2 = o2.fetchConverted();
} catch (KeyGenException e) {
LOGGER.error(e.getMessage());
}
if (null == row1 || null == row2) {
return 0;
}
ByteArrayWrapper key1 = (ByteArrayWrapper) row1[0];
ByteArrayWrapper key2 = (ByteArrayWrapper) row2[0];
int compareResult = 0;
int[] columnValueSizes = segprop.getEachDimColumnValueSize();
int dictionaryKeyOffset = 0;
byte[] dimCols1 = key1.getDictionaryKey();
byte[] dimCols2 = key2.getDictionaryKey();
int noDicIndex = 0;
for (int eachColumnValueSize : columnValueSizes) {
// case of dictionary cols
if (eachColumnValueSize > 0) {
compareResult = ByteUtil.UnsafeComparer.INSTANCE
.compareTo(dimCols1, dictionaryKeyOffset, eachColumnValueSize, dimCols2,
dictionaryKeyOffset, eachColumnValueSize);
dictionaryKeyOffset += eachColumnValueSize;
} else { // case of no dictionary
byte[] noDictionaryDim1 = key1.getNoDictionaryKeyByIndex(noDicIndex);
byte[] noDictionaryDim2 = key2.getNoDictionaryKeyByIndex(noDicIndex);
compareResult =
ByteUtil.UnsafeComparer.INSTANCE.compareTo(noDictionaryDim1, noDictionaryDim2);
noDicIndex++;
}
if (0 != compareResult) {
return compareResult;
}
}
return 0;
}
}
}
| apache-2.0 |
IHTSDO/snow-owl | snomed/com.b2international.snowowl.snomed.ecl/src-gen/com/b2international/snowowl/snomed/ecl/ecl/impl/DecimalValueNotEqualsImpl.java | 4534 | /**
* Copyright 2011-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.snomed.ecl.ecl.impl;
import com.b2international.snowowl.snomed.ecl.ecl.DecimalValueNotEquals;
import com.b2international.snowowl.snomed.ecl.ecl.EclPackage;
import java.math.BigDecimal;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Decimal Value Not Equals</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link com.b2international.snowowl.snomed.ecl.ecl.impl.DecimalValueNotEqualsImpl#getValue <em>Value</em>}</li>
* </ul>
*
* @generated
*/
public class DecimalValueNotEqualsImpl extends DataTypeComparisonImpl implements DecimalValueNotEquals
{
/**
* The default value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected static final BigDecimal VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected BigDecimal value = VALUE_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DecimalValueNotEqualsImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return EclPackage.Literals.DECIMAL_VALUE_NOT_EQUALS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BigDecimal getValue()
{
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setValue(BigDecimal newValue)
{
BigDecimal oldValue = value;
value = newValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EclPackage.DECIMAL_VALUE_NOT_EQUALS__VALUE, oldValue, value));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case EclPackage.DECIMAL_VALUE_NOT_EQUALS__VALUE:
return getValue();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case EclPackage.DECIMAL_VALUE_NOT_EQUALS__VALUE:
setValue((BigDecimal)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case EclPackage.DECIMAL_VALUE_NOT_EQUALS__VALUE:
setValue(VALUE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case EclPackage.DECIMAL_VALUE_NOT_EQUALS__VALUE:
return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (value: ");
result.append(value);
result.append(')');
return result.toString();
}
} //DecimalValueNotEqualsImpl
| apache-2.0 |
DavideD/hibernate-validator | engine/src/main/java/org/hibernate/validator/cfg/context/PropertyConstraintMappingContext.java | 976 | /*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.cfg.context;
/**
* Constraint mapping creational context representing a property of a bean. Allows
* to place constraints on the property, mark the property as cascadable and to
* navigate to other constraint targets.
*
* @author Gunnar Morling
* @author Kevin Pollet <kevin.pollet@serli.com> (C) 2011 SERLI
*/
public interface PropertyConstraintMappingContext extends Constrainable<PropertyConstraintMappingContext>,
TypeTarget,
PropertyTarget,
ConstructorTarget,
MethodTarget,
Cascadable<PropertyConstraintMappingContext>,
Unwrapable<PropertyConstraintMappingContext>,
AnnotationProcessingOptions<PropertyConstraintMappingContext>,
AnnotationIgnoreOptions<PropertyConstraintMappingContext> {
}
| apache-2.0 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/api/reactive/RedisTransactionalReactiveCommands.java | 2122 | /*
* Copyright 2017-2022 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 io.lettuce.core.api.reactive;
import reactor.core.publisher.Mono;
import io.lettuce.core.TransactionResult;
/**
* Reactive executed commands for Transactions.
*
* @param <K> Key type.
* @param <V> Value type.
* @author Mark Paluch
* @since 4.0
* @generated by io.lettuce.apigenerator.CreateReactiveApi
*/
public interface RedisTransactionalReactiveCommands<K, V> {
/**
* Discard all commands issued after MULTI.
*
* @return String simple-string-reply always {@code OK}.
*/
Mono<String> discard();
/**
* Execute all commands issued after MULTI.
*
* @return Object array-reply each element being the reply to each of the commands in the atomic transaction.
*
* When using {@code WATCH}, {@code EXEC} can return a {@link TransactionResult#wasDiscarded discarded
* TransactionResult}.
* @see TransactionResult#wasDiscarded
*/
Mono<TransactionResult> exec();
/**
* Mark the start of a transaction block.
*
* @return String simple-string-reply always {@code OK}.
*/
Mono<String> multi();
/**
* Watch the given keys to determine execution of the MULTI/EXEC block.
*
* @param keys the key.
* @return String simple-string-reply always {@code OK}.
*/
Mono<String> watch(K... keys);
/**
* Forget about all watched keys.
*
* @return String simple-string-reply always {@code OK}.
*/
Mono<String> unwatch();
}
| apache-2.0 |
zjshen/hadoop-YARN-2928-POC | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice/src/test/java/org/apache/hadoop/yarn/server/timelineservice/collector/TestNMTimelineCollectorManager.java | 5940 |
/**
* 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.yarn.server.timelineservice.collector;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.api.CollectorNodemanagerProtocol;
import org.apache.hadoop.yarn.server.api.protocolrecords.GetTimelineCollectorContextRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.GetTimelineCollectorContextResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestNMTimelineCollectorManager {
private NodeTimelineCollectorManager collectorManager;
@Before
public void setup() throws Exception {
collectorManager = createCollectorManager();
collectorManager.init(new YarnConfiguration());
collectorManager.start();
}
@After
public void tearDown() throws Exception {
if (collectorManager != null) {
collectorManager.stop();
}
}
@Test
public void testStartWebApp() throws Exception {
assertNotNull(collectorManager.getRestServerBindAddress());
String address = collectorManager.getRestServerBindAddress();
String[] parts = address.split(":");
assertEquals(2, parts.length);
assertNotNull(parts[0]);
assertTrue(Integer.valueOf(parts[1]) > 0);
}
@Test(timeout=60000)
public void testMultithreadedAdd() throws Exception {
final int NUM_APPS = 5;
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
for (int i = 0; i < NUM_APPS; i++) {
final ApplicationId appId = ApplicationId.newInstance(0L, i);
Callable<Boolean> task = new Callable<Boolean>() {
public Boolean call() {
AppLevelTimelineCollector collector =
new AppLevelTimelineCollector(appId);
return (collectorManager.putIfAbsent(appId, collector) == collector);
}
};
tasks.add(task);
}
ExecutorService executor = Executors.newFixedThreadPool(NUM_APPS);
try {
List<Future<Boolean>> futures = executor.invokeAll(tasks);
for (Future<Boolean> future: futures) {
assertTrue(future.get());
}
} finally {
executor.shutdownNow();
}
// check the keys
for (int i = 0; i < NUM_APPS; i++) {
final ApplicationId appId = ApplicationId.newInstance(0L, i);
assertTrue(collectorManager.containsTimelineCollector(appId));
}
}
@Test
public void testMultithreadedAddAndRemove() throws Exception {
final int NUM_APPS = 5;
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>();
for (int i = 0; i < NUM_APPS; i++) {
final ApplicationId appId = ApplicationId.newInstance(0L, i);
Callable<Boolean> task = new Callable<Boolean>() {
public Boolean call() {
AppLevelTimelineCollector collector =
new AppLevelTimelineCollector(appId);
boolean successPut =
(collectorManager.putIfAbsent(appId, collector) == collector);
return successPut && collectorManager.remove(appId);
}
};
tasks.add(task);
}
ExecutorService executor = Executors.newFixedThreadPool(NUM_APPS);
try {
List<Future<Boolean>> futures = executor.invokeAll(tasks);
for (Future<Boolean> future: futures) {
assertTrue(future.get());
}
} finally {
executor.shutdownNow();
}
// check the keys
for (int i = 0; i < NUM_APPS; i++) {
final ApplicationId appId = ApplicationId.newInstance(0L, i);
assertFalse(collectorManager.containsTimelineCollector(appId));
}
}
private NodeTimelineCollectorManager createCollectorManager() {
final NodeTimelineCollectorManager collectorManager =
spy(new NodeTimelineCollectorManager());
doReturn(new Configuration()).when(collectorManager).getConfig();
CollectorNodemanagerProtocol nmCollectorService =
mock(CollectorNodemanagerProtocol.class);
GetTimelineCollectorContextResponse response =
GetTimelineCollectorContextResponse.newInstance(null, null, null, 0L);
try {
when(nmCollectorService.getTimelineCollectorContext(any(
GetTimelineCollectorContextRequest.class))).thenReturn(response);
} catch (YarnException | IOException e) {
fail();
}
doReturn(nmCollectorService).when(collectorManager).getNMCollectorService();
return collectorManager;
}
}
| apache-2.0 |
tzou24/BPS | BPS/src/com/frameworkset/platform/sysmgrcore/web/tag/DiscreteUserList.java | 4287 | package com.frameworkset.platform.sysmgrcore.web.tag;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import com.frameworkset.common.poolman.ConfigSQLExecutor;
import com.frameworkset.common.poolman.Record;
import com.frameworkset.common.poolman.handle.RowHandler;
import com.frameworkset.common.tag.pager.DataInfoImpl;
import com.frameworkset.orm.transaction.TransactionManager;
import com.frameworkset.platform.sysmgrcore.entity.User;
import com.frameworkset.platform.sysmgrcore.manager.SecurityDatabase;
import com.frameworkset.platform.sysmgrcore.manager.UserManager;
import com.frameworkset.util.ListInfo;
/**
* 离散用户的列表
* select count(*) from td_sm_user user0_
where user0_.user_id in ( select user1_.USER_ID from td_sm_user user1_
minus select userjoborg1_.user_id from td_sm_userjoborg userjoborg1_ )
* @author
* @file DiscreteUserList.java Created on: Apr 26, 2006
*/
public class DiscreteUserList extends DataInfoImpl implements Serializable {
ConfigSQLExecutor executor_ = new ConfigSQLExecutor("com/frameworkset/platform/sysmgrcore/web/tag/userListSn.xml");
protected ListInfo getDataList(String sortKey, boolean desc, long offset,
int maxPagesize) {
ListInfo listInfo = null;
TransactionManager tm = new TransactionManager();
try {
Map params = new HashMap();
String userName = request.getParameter("userName");
String userRealname = request.getParameter("userRealname");
if (userName != null && userName.length() > 0) {
params.put("userName", "%" + userName + "%");
}
if (userRealname != null && userRealname.length() > 0) {
params.put("userRealname", "%" + userRealname + "%");
}
final UserManager userManager = SecurityDatabase.getUserManager();
// System.out.println(hsql.toString());
tm.begin();
listInfo = executor_.queryListInfoBeanByRowHandler(new RowHandler<User>(){
@Override
public void handleRow(User user, Record dbUtil) throws Exception {
user.setUserId(new Integer(dbUtil.getInt( "user_id")));
user.setUserName(dbUtil.getString( "user_name"));
user.setUserRealname(dbUtil.getString( "user_realname"));
user.setUserType(dbUtil.getString( "user_type"));
user.setUserEmail(dbUtil.getString( "user_email"));
user.setUserIdcard(dbUtil.getString("USER_IDCARD"));
user.setUserWorknumber(dbUtil.getString("USER_WORKNUMBER"));
user.setUserMobiletel1(dbUtil.getString("USER_MOBILETEL1"));
user.setPasswordUpdatetime(dbUtil.getTimestamp("password_updatetime"));
user.setPasswordDualedTime(dbUtil.getInt( "Password_DualTime"));
user.setPasswordExpiredTime((Timestamp)userManager.getPasswordExpiredTime(user.getPasswordUpdatetime(),user.getPasswordDualedTime()));
}
}, User.class, "DiscreteUserList", offset, maxPagesize, params);
tm.commit();
} catch (Exception e) {
e.printStackTrace();
}
finally
{
tm.release();
}
// String userName = request.getParameter("userName");
// String userRealname = request.getParameter("userRealname");
// try {
// StringBuffer hsql = new StringBuffer("from User u where 1=1 ");
// if (userName != null && userName.length() > 0) {
// hsql.append(" and u.userName like '%" + userName + "%' ");
// }
// if (userRealname != null && userRealname.length() > 0) {
// hsql
// .append(" and u.userRealname like '%" + userRealname
// + "%'");
// }
//// hsql
//// .append(" and u.userId not in (select distinct ujo.id.userId from Userjoborg ujo"
//// + ")");
// hsql
// .append(" and u.userId in (select u1.userId from User u1 minus select ujo.id.userId from Userjoborg ujo"
// + ")");
// UserManager userManager = SecurityDatabase.getUserManager();
//
// List list = null;
//
// PageConfig pageConfig = userManager.getPageConfig();
// pageConfig.setPageSize(maxPagesize);
// pageConfig.setStartIndex((int) offset);
// list = userManager.getUserList(hsql.toString());
//
// listInfo.setTotalSize(pageConfig.getTotalSize());
//
// listInfo.setDatas(list);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
return listInfo;
}
protected ListInfo getDataList(String arg0, boolean arg1) {
return null;
}
}
| apache-2.0 |
xinmei365/Emojier-Andriod | emojsdk/src/main/java/com/xinmei365/emojsdk/contoller/EMTranslateController.java | 8904 | package com.xinmei365.emojsdk.contoller;
import com.xinmei365.emojsdk.domain.Constant;
import com.xinmei365.emojsdk.domain.EMCharacterEntity;
import com.xinmei365.emojsdk.domain.EMTranslatEntity;
import com.xinmei365.emojsdk.notify.INotifyCallback;
import com.xinmei365.emojsdk.notify.NotifyEntity;
import com.xinmei365.emojsdk.notify.NotifyKeys;
import com.xinmei365.emojsdk.notify.NotifyManager;
import com.xinmei365.emojsdk.orm.EMDBMagager;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by xinmei on 15/12/14.
*/
public class EMTranslateController implements INotifyCallback {
private final String TAG = EMTranslateController.class.getSimpleName();
private static EMTranslateController mInstance;
private static final char mEmojHolder = 0xfffc;
private static final char mSpace = 0x20;
private IEMTranslateCallback mEMTranslateCallback;
private EMTranslateController() {
registerNotify();
}
private void registerNotify() {
NotifyManager.getInstance().registerNotifyCallback(NotifyKeys.ALL_EMOJ_HAS_DOWNLOAD, this);
}
private void unRegisterNotify() {
NotifyManager.getInstance().removeNotifyCallback(NotifyKeys.ALL_EMOJ_HAS_DOWNLOAD, this);
}
public static EMTranslateController getInstance() {
if (mInstance == null) {
synchronized (EMTranslateController.class) {
if (mInstance == null) {
mInstance = new EMTranslateController();
}
}
}
return mInstance;
}
/**
* Translate user input content to emoji
*/
public void translateMsg(CharSequence content,IEMTranslateCallback translateCallback) {
setEMTranslateCallback(translateCallback);
MessageQueueManager.getInstance().clear();
ArrayList<EMCharacterEntity> emTransEntries = splitAllContent(content);
Map<String, ArrayList<EMCharacterEntity>> jonAndTranMap = EMDBMagager.getInstance().filterTranslateWord(emTransEntries);
ArrayList<EMCharacterEntity> translateArr = jonAndTranMap.get(Constant.KEY_EMOJ_TRANSLATE_ASSEMBLE_ARR);
ArrayList<EMCharacterEntity> joinArr = jonAndTranMap.get(Constant.KEY_EMOJ_ALL_ASSEMBLE_ARR);
if (translateArr.size() == 0) {
if (mEMTranslateCallback != null) {
mEMTranslateCallback.onEmptyMsgTranslate();
}
} else {
MessageQueueManager.getInstance().putNeedAssebleKeys(joinArr);
MessageQueueManager.getInstance().putAllNeedTransEmojKey(translateArr);
}
}
private ArrayList<EMCharacterEntity> splitAllContent(CharSequence content) {
String regex = "\\b\\w+-\\w+\\b|\\b\\w+\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
ArrayList<EMCharacterEntity> wordArrs = new ArrayList<EMCharacterEntity>();
ArrayList<EMCharacterEntity> allArrs = new ArrayList<EMCharacterEntity>();
while (matcher.find()) {
int wordStart = matcher.start();
int wordEnd = matcher.end();
CharSequence word = matcher.group();
EMCharacterEntity transEntry = new EMCharacterEntity(wordStart, wordEnd, word, EMCharacterEntity.CharacterType.Normal);
wordArrs.add(transEntry);
}
for (int i = 0; i < wordArrs.size(); i++) {
EMCharacterEntity befEntry = wordArrs.get(i);
EMCharacterEntity afterEntry = null;
if (i + 1 < wordArrs.size()) {
afterEntry = wordArrs.get(i + 1);
}
//process the content before first word, it is possible emoji or whitespace, possible more than one
if (i == 0 && befEntry.mWordStart != 0) {
CharSequence tempStr = content.subSequence(0, befEntry.mWordStart);
for (int k = 0; k < tempStr.length(); k++) {
if (tempStr.charAt(k) == mEmojHolder) {
EMCharacterEntity transEntry = new EMCharacterEntity(k, k + 1, tempStr.subSequence(k,k+1), EMCharacterEntity.CharacterType.Emoj);
allArrs.add(transEntry);
} else if (tempStr.charAt(k) == mSpace) {
EMCharacterEntity transEntry = new EMCharacterEntity(k, k + 1, tempStr.subSequence(k,k+1), EMCharacterEntity.CharacterType.Space);
allArrs.add(transEntry);
} else {
EMCharacterEntity transEntry = new EMCharacterEntity(k, k + 1, tempStr.subSequence(k,k+1), EMCharacterEntity.CharacterType.Other);
allArrs.add(transEntry);
}
}
}
//process content of each word
if (afterEntry != null && afterEntry.mWordStart - befEntry.mWordEnd > 0) {
for (int k = 0; k < afterEntry.mWordStart - befEntry.mWordEnd; k++) {
int tempStart = befEntry.mWordEnd + k;
int tempEnd = tempStart + 1;
CharSequence tempStr = content.subSequence(tempStart, tempEnd);
if (tempStr.equals(String.valueOf(mEmojHolder))) {
EMCharacterEntity transEntry = new EMCharacterEntity(tempStart, tempEnd, tempStr, EMCharacterEntity.CharacterType.Emoj);
allArrs.add(transEntry);
} else if (tempStr.equals(String.valueOf(mSpace))) {
EMCharacterEntity transEntry = new EMCharacterEntity(tempStart, tempEnd, tempStr, EMCharacterEntity.CharacterType.Space);
allArrs.add(transEntry);
} else {
EMCharacterEntity transEntry = new EMCharacterEntity(tempStart, tempEnd, tempStr, EMCharacterEntity.CharacterType.Other);
allArrs.add(transEntry);
}
}
}
if (i == wordArrs.size() - 1) {
if (befEntry.mWordEnd != content.length()) {
for (int k = 0; k < content.length() - befEntry.mWordEnd; k++) {
int tempStart = befEntry.mWordEnd + k;
int tempEnd = tempStart + 1;
CharSequence tempStr = content.subSequence(tempStart, tempEnd);
if (tempStr.equals(String.valueOf(mEmojHolder))) {
EMCharacterEntity transEntry = new EMCharacterEntity(tempStart, tempEnd, tempStr, EMCharacterEntity.CharacterType.Emoj);
allArrs.add(transEntry);
} else if (tempStr.equals(String.valueOf(mSpace))) {
EMCharacterEntity transEntry = new EMCharacterEntity(tempStart, tempEnd, tempStr, EMCharacterEntity.CharacterType.Space);
allArrs.add(transEntry);
} else {
EMCharacterEntity transEntry = new EMCharacterEntity(tempStart, tempEnd, tempStr, EMCharacterEntity.CharacterType.Other);
allArrs.add(transEntry);
}
}
}
}
}
allArrs.addAll(wordArrs);
Collections.sort(allArrs, new Comparator<EMCharacterEntity>() {
@Override
public int compare(EMCharacterEntity lhs, EMCharacterEntity rhs) {
if (lhs.mWordStart > rhs.mWordStart) {
return 1;
} else if (lhs.mWordStart < rhs.mWordStart) {
return -1;
}
return 0;
}
});
return allArrs;
}
public void setEMTranslateCallback(IEMTranslateCallback emojTranCallback) {
this.mEMTranslateCallback = emojTranCallback;
}
@Override
public void notifyCallback(NotifyEntity entity) {
try {
String key = entity.getKey();
if (key.equals(NotifyKeys.ALL_EMOJ_HAS_DOWNLOAD)) {
//all waiting translated emoji key's image has been downloaded, notify UI to update, assemble
ArrayList<EMCharacterEntity> allAssembleArr = (ArrayList<EMCharacterEntity>) entity.getObject();
if (allAssembleArr.size() > 0 && mEMTranslateCallback != null) {
EMTranslatEntity translatEntity = EMAssembleController.getInstance().assembleSpan(allAssembleArr);
mEMTranslateCallback.onEmojTransferSuccess(translatEntity);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void destroy() {
unRegisterNotify();
}
}
| apache-2.0 |
dump247/aws-sdk-java | aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/transform/GetApplicationRequestMarshaller.java | 3201 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.codedeploy.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.codedeploy.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* GetApplicationRequest Marshaller
*/
public class GetApplicationRequestMarshaller implements
Marshaller<Request<GetApplicationRequest>, GetApplicationRequest> {
public Request<GetApplicationRequest> marshall(
GetApplicationRequest getApplicationRequest) {
if (getApplicationRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<GetApplicationRequest> request = new DefaultRequest<GetApplicationRequest>(
getApplicationRequest, "AmazonCodeDeploy");
request.addHeader("X-Amz-Target", "CodeDeploy_20141006.GetApplication");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator();
jsonGenerator.writeStartObject();
if (getApplicationRequest.getApplicationName() != null) {
jsonGenerator.writeFieldName("applicationName").writeValue(
getApplicationRequest.getApplicationName());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", "application/x-amz-json-1.1");
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
| apache-2.0 |
Netflix/staash | staash-astyanax/src/main/java/com/netflix/paas/dao/astyanax/IndexerException.java | 1113 | /*******************************************************************************
* /***
* *
* * Copyright 2013 Netflix, 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.netflix.paas.dao.astyanax;
public class IndexerException extends Exception {
public IndexerException(String message, Exception e) {
super(message, e);
}
public IndexerException(String message) {
super(message);
}
}
| apache-2.0 |
cbrown06/fslink | src/main/io/github/cbrown06/fslink/CreateLinkTask.java | 873 | package io.github.cbrown06.fslink;
import java.io.File;
/**
* {@code createlink} task for Apache Ant.
*
* @author <a href="http://cbrown06.github.io/fslink/">Christopher Brown</a>
* @since 1.0.0
*/
public final class CreateLinkTask extends FslinkTask
{
/**
* Used by Apache Ant to constructs a new instance of this task.
*/
public CreateLinkTask()
{
super(ACTION_CREATE);
}
/**
* Sets the {@code overwrite} property.
* This is optional, defaulting to {@code false}.
*
* @param overwrite the property value, as specified in the build file.
*/
public void setOverwrite(boolean overwrite)
{
_overwrite = overwrite;
}
/**
* Sets the {@code resource} property.
* This is mandatory.
*
* @param resource the property value, as specified in the build file.
*/
public void setResource(File resource)
{
_resource = resource;
}
} | apache-2.0 |
rma350/kidneyExchange | kidneyMatching/src/statistics/StatUtil.java | 483 | package statistics;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
public class StatUtil {
public static SummaryStatistics asStatistic(int[] values){
SummaryStatistics ans = new SummaryStatistics();
for(int val: values){
ans.addValue(val);
}
return ans;
}
public static SummaryStatistics asStatistic(double[] values){
SummaryStatistics ans = new SummaryStatistics();
for(double val: values){
ans.addValue(val);
}
return ans;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/transform/FrameCaptureSettingsJsonUnmarshaller.java | 3587 | /*
* 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.mediaconvert.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.mediaconvert.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* FrameCaptureSettings JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class FrameCaptureSettingsJsonUnmarshaller implements Unmarshaller<FrameCaptureSettings, JsonUnmarshallerContext> {
public FrameCaptureSettings unmarshall(JsonUnmarshallerContext context) throws Exception {
FrameCaptureSettings frameCaptureSettings = new FrameCaptureSettings();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("framerateDenominator", targetDepth)) {
context.nextToken();
frameCaptureSettings.setFramerateDenominator(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("framerateNumerator", targetDepth)) {
context.nextToken();
frameCaptureSettings.setFramerateNumerator(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("maxCaptures", targetDepth)) {
context.nextToken();
frameCaptureSettings.setMaxCaptures(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("quality", targetDepth)) {
context.nextToken();
frameCaptureSettings.setQuality(context.getUnmarshaller(Integer.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return frameCaptureSettings;
}
private static FrameCaptureSettingsJsonUnmarshaller instance;
public static FrameCaptureSettingsJsonUnmarshaller getInstance() {
if (instance == null)
instance = new FrameCaptureSettingsJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
danigiri/morfeu | src/test/java/cat/calidos/morfeu/webapp/injection/HttpFilterModuleTest.java | 7698 | package cat.calidos.morfeu.webapp.injection;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.function.BiFunction;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import cat.calidos.morfeu.problems.MorfeuRuntimeException;
/**
* @author daniel giribet
*///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class HttpFilterModuleTest {
private FilterChain chain;
private HttpServletRequest request;
private HttpServletResponse response;
@BeforeEach
public void setup() {
chain = Mockito.mock(FilterChain.class);
request = Mockito.mock(HttpServletRequest.class);
response = Mockito.mock(HttpServletResponse.class);
}
@Test @DisplayName("Handling exceptions test")
public void testHandledExceptions() throws Exception {
doThrow(new ServletException()).when(chain).doFilter(null, null);
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f0 = (req, resp) -> true;
LinkedList<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> filters
= new LinkedList<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>();
filters.add(f0);
assertThrows(MorfeuRuntimeException.class, () -> HttpFilterModule.process(filters, filters, null, null, chain));
}
@Test @DisplayName("Right order of filters test")
public void testFilterOrder() {
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f0 = (req, resp) -> true;
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f1 = (req, resp) -> true;
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f2 = (req, resp) -> true;
HashMap<Integer, BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> filters
= new HashMap<Integer, BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>(3);
filters.put(HttpFilterModule.IDENTITY_INDEX, HttpFilterModule.identity());
filters.put(0, f0);
filters.put(1, f1);
filters.put(2, f2);
List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> filterList
= HttpFilterModule.preFilters(filters);
assertAll("Testing filter order",
() -> assertNotNull(filterList),
() -> assertEquals(3, filterList.size(), "Wrong filter list size"),
() -> assertEquals(f0, filterList.get(0), "f0 should be the first filter"),
() -> assertEquals(f1, filterList.get(1), "f1 should be the second filter"),
() -> assertEquals(f2, filterList.get(2), "f2 should be the third filter")
);
}
@Test @DisplayName("Test processing")
public void testProcess() throws Exception {
when(request.getHeader(anyString())).then(returnsFirstArg());
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f0 = (req, resp) -> {
resp.setHeader("foo0", req.getHeader("foo0"));
return true;
};
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f1 = (req, resp) -> {
resp.setHeader("foo1", req.getHeader("foo1"));
return true;
};
List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> preFilters
= new LinkedList<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>();
preFilters.add(f0);
preFilters.add(f1);
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f2 = (req, resp) -> {
resp.setHeader("foo2", req.getHeader("foo2"));
return true;
};
List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> postFilters
= new LinkedList<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>();
postFilters.add(f2);
boolean continue_ = HttpFilterModule.process(preFilters, postFilters, request, response, chain);
assertTrue(continue_,"filter chain was not stopped");
InOrder requestVerifier = Mockito.inOrder(request);
requestVerifier.verify(request).getHeader("foo0");
requestVerifier.verify(request).getHeader("foo1");
requestVerifier.verify(request).getHeader("foo2");
InOrder responseVerifier = Mockito.inOrder(response);
responseVerifier.verify(response).setHeader("foo0", "foo0");
responseVerifier.verify(response).setHeader("foo1", "foo1");
responseVerifier.verify(response).setHeader("foo2", "foo2");
}
@Test @DisplayName("Test stopping filter chain")
public void testStopping() throws Exception {
when(request.getHeader(anyString())).then(returnsFirstArg());
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f0 = (req, resp) -> {
req.getHeader("foo0");
return true;
};
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f1 = (req, resp) -> {
req.getHeader("foo1");
return false; // this will stop
};
List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> preFilters
= new LinkedList<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>();
preFilters.add(f0);
preFilters.add(f1);
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f2 = (req, resp) -> {
req.getHeader("foo2");
return true;
};
List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> postFilters
= new LinkedList<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>();
postFilters.add(f2);
boolean continue_ = HttpFilterModule.process(preFilters, postFilters, request, response, chain);
assertAll("Checking filter stopped",
() -> assertFalse(continue_,"filter chain continued when it should have stopped"),
() -> assertEquals(2, Mockito.mockingDetails(request).getInvocations().size(), "ran 3 filters and not 2")
);
verify(request).getHeader("foo0");
verify(request).getHeader("foo1");
}
@Test @DisplayName("Test pre and post filter")
public void testPrePost() throws Exception {
StringBuffer testBuffer = new StringBuffer("");
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f0 = (req, resp) -> {
testBuffer.append("0");
return true;
};
BiFunction<HttpServletRequest, HttpServletResponse, Boolean> f1 = (req, resp) -> {
testBuffer.append("1");
return true;
};
List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> preFilters
= new LinkedList<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>();
preFilters.add(f0);
List<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>> postFilters
= new LinkedList<BiFunction<HttpServletRequest, HttpServletResponse, Boolean>>();
postFilters.add(f1);
boolean continue_ = HttpFilterModule.process(preFilters, postFilters, request, response, chain);
assertAll("Checking filter stopped",
() -> assertTrue(continue_,"filter chain stopped when it should continue"),
() -> assertEquals("01", testBuffer.toString(), "Should have ran the two filters")
);
}
}
/*
* Copyright 2019 Daniel Giribet
*
* 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.
*/
| apache-2.0 |
talsma-ict/umldoclet | src/plantuml-asl/src/h/ST_dtlink_s.java | 3882 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2022, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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 h;
import smetana.core.OFFSET;
import smetana.core.UnsupportedStarStruct;
import smetana.core.__ptr__;
import smetana.core.__struct__;
public class ST_dtlink_s extends UnsupportedStarStruct {
public ST_dtlink_s right;
public ST_dtlink_s _left;
private final __ptr__ container;
@Override
public void ___(__struct__ other) {
ST_dtlink_s this2 = (ST_dtlink_s) other;
this.right = this2.right;
this._left = this2._left;
}
public ST_dtlink_s() {
this(null);
}
public ST_dtlink_s(__ptr__ parent) {
this.container = parent;
}
public __ptr__ getParent() {
return container;
}
@Override
public __ptr__ castTo(Class dest) {
if (dest == ST_dtlink_s.class) {
return this;
}
if (dest == ST_dthold_s.class && getParent() instanceof ST_dthold_s) {
return (ST_dthold_s) getParent();
}
System.err.println("dest=" + dest);
return super.castTo(dest);
}
@Override
public Object getTheField(OFFSET offset) {
if (offset == null || offset.getSign() == 0) {
return this;
}
if (offset.getField().equals("s") && container instanceof ST_refstr_t) {
return ((ST_refstr_t) container).s;
}
// Negative because we go back to the parent
offset = offset.negative();
return container;
// if (offset.getKey().equals("h.ST_Agsubnode_s::id_link")) {
// return ((ST_Agsubnode_s) parent);
// }
// if (offset.getKey().equals("h.ST_Agsubnode_s::seq_link")) {
// return ((ST_Agsubnode_s) parent);
// }
// if (offset.getKey().equals("h.ST_Agsym_s::link")) {
// return ((ST_Agsym_s) parent);
// }
// if (offset.getKey().equals("h.ST_Agedge_s::seq_link")) {
// return ((ST_Agedge_s) parent);
// }
// if (offset.getKey().equals("h.ST_Agedge_s::id_link")) {
// return ((ST_Agedge_s) parent);
// }
// if (offset.getKey().equals("h.ST_Agraph_s::link")) {
// return ((ST_Agraph_s) parent);
// }
}
}
// struct _dtlink_s
// { Dtlink_t* right; /* right child */
// union
// { unsigned int _hash; /* hash value */
// Dtlink_t* _left; /* left child */
// } hl;
// }; | apache-2.0 |
GwtDomino/domino | domino-test/domino-client-test/src/main/java/org/dominokit/domino/test/api/client/ListenerHandler.java | 236 | package org.dominokit.domino.test.api.client;
import org.dominokit.domino.api.shared.extension.DominoEventListener;
@FunctionalInterface
public interface ListenerHandler<L extends DominoEventListener> {
void handle(L listener);
}
| apache-2.0 |
ua-eas/ua-rice-2.1.9 | impl/src/main/java/org/kuali/rice/krad/service/impl/DataDictionaryServiceImpl.java | 39080 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.service.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.core.api.util.ClassLoaderUtils;
import org.kuali.rice.core.web.format.Formatter;
import org.kuali.rice.kew.api.KewApiServiceLocator;
import org.kuali.rice.kew.api.doctype.DocumentType;
import org.kuali.rice.kew.api.doctype.DocumentTypeService;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.datadictionary.AttributeDefinition;
import org.kuali.rice.krad.datadictionary.AttributeSecurity;
import org.kuali.rice.krad.datadictionary.BusinessObjectEntry;
import org.kuali.rice.krad.datadictionary.CollectionDefinition;
import org.kuali.rice.krad.datadictionary.DataDictionary;
import org.kuali.rice.krad.datadictionary.DataDictionaryEntryBase;
import org.kuali.rice.krad.datadictionary.DataObjectEntry;
import org.kuali.rice.krad.datadictionary.DocumentEntry;
import org.kuali.rice.krad.datadictionary.InactivationBlockingMetadata;
import org.kuali.rice.krad.datadictionary.PrimitiveAttributeDefinition;
import org.kuali.rice.krad.datadictionary.RelationshipDefinition;
import org.kuali.rice.krad.datadictionary.control.ControlDefinition;
import org.kuali.rice.krad.datadictionary.exception.UnknownBusinessClassAttributeException;
import org.kuali.rice.krad.datadictionary.exception.UnknownDocumentTypeException;
import org.kuali.rice.krad.datadictionary.validation.ValidationPattern;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.krad.keyvalues.KeyValuesFinder;
import org.kuali.rice.krad.service.DataDictionaryService;
import org.kuali.rice.krad.service.KualiModuleService;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.view.View;
import org.kuali.rice.krad.uif.UifConstants.ViewType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Service implementation for a DataDictionary. It is a thin wrapper around creating, initializing, and
* returning a DataDictionary. This is the default, Kuali delivered implementation
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class DataDictionaryServiceImpl implements DataDictionaryService {
private static final Logger LOG = Logger.getLogger(DataDictionaryServiceImpl.class);
private DataDictionary dataDictionary;
private ConfigurationService kualiConfigurationService;
private KualiModuleService kualiModuleService;
private volatile DocumentTypeService documentTypeService;
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#setBaselinePackages(java.lang.String)
*/
public void setBaselinePackages(List baselinePackages) throws IOException {
this.addDataDictionaryLocations(baselinePackages);
}
/**
* Default constructor.
*/
public DataDictionaryServiceImpl() {
this.dataDictionary = new DataDictionary();
}
public DataDictionaryServiceImpl(DataDictionary dataDictionary) {
this.dataDictionary = dataDictionary;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getDataDictionary()
*/
public DataDictionary getDataDictionary() {
return dataDictionary;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeControlDefinition(java.lang.String)
*/
public ControlDefinition getAttributeControlDefinition(String entryName, String attributeName) {
ControlDefinition controlDefinition = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
controlDefinition = attributeDefinition.getControl();
}
return controlDefinition;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeSize(java.lang.String)
*/
public Integer getAttributeSize(String entryName, String attributeName) {
Integer size = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
ControlDefinition controlDefinition = attributeDefinition.getControl();
if (controlDefinition.isText() || controlDefinition.isCurrency()) {
size = controlDefinition.getSize();
}
}
return size;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeMinLength(java.lang.String)
*/
public Integer getAttributeMinLength(String entryName, String attributeName) {
Integer minLength = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
minLength = attributeDefinition.getMinLength();
}
return minLength;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeMaxLength(java.lang.String)
*/
public Integer getAttributeMaxLength(String entryName, String attributeName) {
Integer maxLength = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
maxLength = attributeDefinition.getMaxLength();
}
return maxLength;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeExclusiveMin
*/
public String getAttributeExclusiveMin(String entryName, String attributeName) {
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
return attributeDefinition == null ? null : attributeDefinition.getExclusiveMin();
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeInclusiveMax
*/
public String getAttributeInclusiveMax(String entryName, String attributeName) {
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
return attributeDefinition == null ? null : attributeDefinition.getInclusiveMax();
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeValidatingExpression(java.lang.String)
*/
public Pattern getAttributeValidatingExpression(String entryName, String attributeName) {
Pattern regex = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
if (attributeDefinition.hasValidationPattern()) {
regex = attributeDefinition.getValidationPattern().getRegexPattern();
} else {
// workaround for existing calls which don't bother checking for null return values
regex = Pattern.compile(".*");
}
}
return regex;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeLabel(java.lang.String)
*/
public String getAttributeLabel(String entryName, String attributeName) {
String label = "";
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
// KULRICE-4445 prevent NullPointerException by ensuring a label is set
label = attributeDefinition.getLabel();
if (!StringUtils.isEmpty(attributeDefinition.getDisplayLabelAttribute())) {
attributeDefinition = getAttributeDefinition(entryName, attributeDefinition.getDisplayLabelAttribute());
if (attributeDefinition != null) {
label = attributeDefinition.getLabel();
}
}
}
return label;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeShortLabel(java.lang.String)
*/
public String getAttributeShortLabel(String entryName, String attributeName) {
String shortLabel = "";
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
if (!StringUtils.isEmpty(attributeDefinition.getDisplayLabelAttribute())) {
attributeDefinition = getAttributeDefinition(entryName, attributeDefinition.getDisplayLabelAttribute());
if (attributeDefinition != null) {
shortLabel = attributeDefinition.getShortLabel();
}
} else {
shortLabel = attributeDefinition.getShortLabel();
}
}
return shortLabel;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeErrorLabel(java.lang.String)
*/
public String getAttributeErrorLabel(String entryName, String attributeName) {
String longAttributeLabel = this.getAttributeLabel(entryName, attributeName);
String shortAttributeLabel = this.getAttributeShortLabel(entryName, attributeName);
return longAttributeLabel + " (" + shortAttributeLabel + ")";
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeFormatter(java.lang.String)
*/
public Class<? extends Formatter> getAttributeFormatter(String entryName, String attributeName) {
Class formatterClass = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
if (attributeDefinition.hasFormatterClass()) {
formatterClass = ClassLoaderUtils.getClass(attributeDefinition.getFormatterClass());
}
}
return formatterClass;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeForceUppercase(java.lang.String)
*/
public Boolean getAttributeForceUppercase(String entryName,
String attributeName) throws UnknownBusinessClassAttributeException {
Boolean forceUppercase = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition == null) {
throw new UnknownBusinessClassAttributeException(
"Could not find a matching data dictionary business class attribute entry for " + entryName + "." +
attributeName);
}
forceUppercase = attributeDefinition.getForceUppercase();
return forceUppercase;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeDisplayMask(java.lang.String, java.lang.String)
*/
public AttributeSecurity getAttributeSecurity(String entryName, String attributeName) {
AttributeSecurity attributeSecurity = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
attributeSecurity = attributeDefinition.getAttributeSecurity();
}
return attributeSecurity;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeSummary(java.lang.String)
*/
public String getAttributeSummary(String entryName, String attributeName) {
String summary = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
summary = attributeDefinition.getSummary();
}
return summary;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeDescription(java.lang.String)
*/
public String getAttributeDescription(String entryName, String attributeName) {
String description = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
description = attributeDefinition.getDescription();
}
return description;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#isAttributeRequired(java.lang.Class, java.lang.String)
*/
public Boolean isAttributeRequired(String entryName, String attributeName) {
Boolean required = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
required = attributeDefinition.isRequired();
}
return required;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#isAttributeDefined(java.lang.Class, java.lang.String)
*/
public Boolean isAttributeDefined(String entryName, String attributeName) {
boolean isDefined = false;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
isDefined = true;
}
return isDefined;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeValuesScopeId(java.lang.Class,
* java.lang.String)
*/
public Class<? extends KeyValuesFinder> getAttributeValuesFinderClass(String entryName, String attributeName) {
Class valuesFinderClass = null;
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
String valuesFinderClassName = attributeDefinition.getControl().getValuesFinderClass();
valuesFinderClass = ClassLoaderUtils.getClass(valuesFinderClassName);
}
return valuesFinderClass;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionLabel(java.lang.Class, java.lang.String)
*/
public String getCollectionLabel(String entryName, String collectionName) {
String label = "";
CollectionDefinition collectionDefinition = getCollectionDefinition(entryName, collectionName);
if (collectionDefinition != null) {
label = collectionDefinition.getLabel();
}
return label;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionShortLabel(java.lang.Class, java.lang.String)
*/
public String getCollectionShortLabel(String entryName, String collectionName) {
String shortLabel = "";
CollectionDefinition collectionDefinition = getCollectionDefinition(entryName, collectionName);
if (collectionDefinition != null) {
shortLabel = collectionDefinition.getShortLabel();
}
return shortLabel;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionElementLabel(java.lang.Class,
* java.lang.String)
*/
public String getCollectionElementLabel(String entryName, String collectionName, Class dataObjectClass) {
String elementLabel = "";
CollectionDefinition collectionDefinition = getCollectionDefinition(entryName, collectionName);
if (collectionDefinition != null) {
elementLabel = collectionDefinition.getElementLabel();
if (StringUtils.isEmpty(elementLabel)) {
BusinessObjectEntry boe = getDataDictionary().getBusinessObjectEntry(dataObjectClass.getName());
if (boe != null) {
elementLabel = boe.getObjectLabel();
}
}
}
return elementLabel;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionSummary(java.lang.Class, java.lang.String)
*/
public String getCollectionSummary(String entryName, String collectionName) {
String summary = null;
CollectionDefinition collectionDefinition = getCollectionDefinition(entryName, collectionName);
if (collectionDefinition != null) {
summary = collectionDefinition.getSummary();
}
return summary;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionDescription(java.lang.Class,
* java.lang.String)
*/
public String getCollectionDescription(String entryName, String collectionName) {
String description = null;
CollectionDefinition collectionDefinition = getCollectionDefinition(entryName, collectionName);
if (collectionDefinition != null) {
description = collectionDefinition.getDescription();
}
return description;
}
public Class<? extends BusinessObject> getRelationshipSourceClass(String entryName, String relationshipName) {
Class sourceClass = null;
RelationshipDefinition rd = getRelationshipDefinition(entryName, relationshipName);
if (rd != null) {
sourceClass = rd.getSourceClass();
}
return sourceClass;
}
public Class<? extends BusinessObject> getRelationshipTargetClass(String entryName, String relationshipName) {
Class targetClass = null;
RelationshipDefinition rd = getRelationshipDefinition(entryName, relationshipName);
if (rd != null) {
targetClass = rd.getTargetClass();
}
return targetClass;
}
public List<String> getRelationshipSourceAttributes(String entryName, String relationshipName) {
List<String> sourceAttributes = null;
RelationshipDefinition rd = getRelationshipDefinition(entryName, relationshipName);
if (rd != null) {
sourceAttributes = new ArrayList<String>();
for (PrimitiveAttributeDefinition pad : rd.getPrimitiveAttributes()) {
sourceAttributes.add(pad.getSourceName());
}
}
return sourceAttributes;
}
public List<String> getRelationshipTargetAttributes(String entryName, String relationshipName) {
List<String> targetAttributes = null;
RelationshipDefinition rd = getRelationshipDefinition(entryName, relationshipName);
if (rd != null) {
targetAttributes = new ArrayList<String>();
for (PrimitiveAttributeDefinition pad : rd.getPrimitiveAttributes()) {
targetAttributes.add(pad.getTargetName());
}
}
return targetAttributes;
}
public List<String> getRelationshipEntriesForSourceAttribute(String entryName, String sourceAttributeName) {
List<String> relationships = new ArrayList<String>();
DataDictionaryEntryBase entry =
(DataDictionaryEntryBase) getDataDictionary().getDictionaryObjectEntry(entryName);
for (RelationshipDefinition def : entry.getRelationships()) {
for (PrimitiveAttributeDefinition pddef : def.getPrimitiveAttributes()) {
if (StringUtils.equals(sourceAttributeName, pddef.getSourceName())) {
relationships.add(def.getObjectAttributeName());
break;
}
}
}
return relationships;
}
public List<String> getRelationshipEntriesForTargetAttribute(String entryName, String targetAttributeName) {
List<String> relationships = new ArrayList<String>();
DataDictionaryEntryBase entry =
(DataDictionaryEntryBase) getDataDictionary().getDictionaryObjectEntry(entryName);
for (RelationshipDefinition def : entry.getRelationships()) {
for (PrimitiveAttributeDefinition pddef : def.getPrimitiveAttributes()) {
if (StringUtils.equals(targetAttributeName, pddef.getTargetName())) {
relationships.add(def.getObjectAttributeName());
break;
}
}
}
return relationships;
}
/**
* @param objectClass
* @param attributeName
* @return AttributeDefinition for the given dataObjectClass and attribute name, or null if there is none
* @throws IllegalArgumentException if the given Class is null or is not a BusinessObject class
*/
public AttributeDefinition getAttributeDefinition(String entryName, String attributeName) {
if (StringUtils.isBlank(attributeName)) {
throw new IllegalArgumentException("invalid (blank) attributeName");
}
AttributeDefinition attributeDefinition = null;
DataDictionaryEntryBase entry =
(DataDictionaryEntryBase) getDataDictionary().getDictionaryObjectEntry(entryName);
if (entry != null) {
attributeDefinition = entry.getAttributeDefinition(attributeName);
}
return attributeDefinition;
}
/**
* @param entryName
* @param collectionName
* @return CollectionDefinition for the given entryName and collectionName, or null if there is none
*/
private CollectionDefinition getCollectionDefinition(String entryName, String collectionName) {
if (StringUtils.isBlank(collectionName)) {
throw new IllegalArgumentException("invalid (blank) collectionName");
}
CollectionDefinition collectionDefinition = null;
DataDictionaryEntryBase entry =
(DataDictionaryEntryBase) getDataDictionary().getDictionaryObjectEntry(entryName);
if (entry != null) {
collectionDefinition = entry.getCollectionDefinition(collectionName);
}
return collectionDefinition;
}
/**
* @param entryName
* @param relationshipName
* @return RelationshipDefinition for the given entryName and relationshipName, or null if there is none
*/
private RelationshipDefinition getRelationshipDefinition(String entryName, String relationshipName) {
if (StringUtils.isBlank(relationshipName)) {
throw new IllegalArgumentException("invalid (blank) relationshipName");
}
RelationshipDefinition relationshipDefinition = null;
DataDictionaryEntryBase entry =
(DataDictionaryEntryBase) getDataDictionary().getDictionaryObjectEntry(entryName);
if (entry != null) {
relationshipDefinition = entry.getRelationshipDefinition(relationshipName);
}
return relationshipDefinition;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getRelationshipAttributeMap(java.lang.String, java.lang.String)
*/
public Map<String, String> getRelationshipAttributeMap(String entryName, String relationshipName) {
Map<String, String> attributeMap = new HashMap<String, String>();
RelationshipDefinition relationshipDefinition = getRelationshipDefinition(entryName, relationshipName);
for (Iterator iter = relationshipDefinition.getPrimitiveAttributes().iterator(); iter.hasNext(); ) {
PrimitiveAttributeDefinition attribute = (PrimitiveAttributeDefinition) iter.next();
attributeMap.put(attribute.getTargetName(), attribute.getSourceName());
}
return attributeMap;
}
public boolean hasRelationship(String entryName, String relationshipName) {
return getRelationshipDefinition(entryName, relationshipName) != null;
}
public List<String> getRelationshipNames(String entryName) {
DataDictionaryEntryBase entry =
(DataDictionaryEntryBase) getDataDictionary().getDictionaryObjectEntry(entryName);
List<String> relationshipNames = new ArrayList<String>();
for (RelationshipDefinition def : entry.getRelationships()) {
relationshipNames.add(def.getObjectAttributeName());
}
return relationshipNames;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeControlDefinition(java.lang.String, java.lang.String)
*/
public ControlDefinition getAttributeControlDefinition(Class dataObjectClass, String attributeName) {
return getAttributeControlDefinition(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeDescription(java.lang.String, java.lang.String)
*/
public String getAttributeDescription(Class dataObjectClass, String attributeName) {
return getAttributeDescription(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeForceUppercase(java.lang.String, java.lang.String)
*/
public Boolean getAttributeForceUppercase(Class dataObjectClass, String attributeName) {
return getAttributeForceUppercase(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeFormatter(java.lang.String, java.lang.String)
*/
public Class<? extends Formatter> getAttributeFormatter(Class dataObjectClass, String attributeName) {
return getAttributeFormatter(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeLabel(java.lang.String, java.lang.String)
*/
public String getAttributeLabel(Class dataObjectClass, String attributeName) {
return getAttributeLabel(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeMaxLength(java.lang.String, java.lang.String)
*/
public Integer getAttributeMaxLength(Class dataObjectClass, String attributeName) {
return getAttributeMaxLength(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeShortLabel(java.lang.String, java.lang.String)
*/
public String getAttributeShortLabel(Class dataObjectClass, String attributeName) {
return getAttributeShortLabel(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeErrorLabel(java.lang.String, java.lang.String)
*/
public String getAttributeErrorLabel(Class dataObjectClass, String attributeName) {
return getAttributeErrorLabel(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeSize(java.lang.String, java.lang.String)
*/
public Integer getAttributeSize(Class dataObjectClass, String attributeName) {
return getAttributeSize(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeSummary(java.lang.String, java.lang.String)
*/
public String getAttributeSummary(Class dataObjectClass, String attributeName) {
return getAttributeSummary(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeValidatingExpression(java.lang.String, java.lang.String)
*/
public Pattern getAttributeValidatingExpression(Class dataObjectClass, String attributeName) {
return getAttributeValidatingExpression(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeValuesFinderClass(java.lang.String, java.lang.String)
*/
public Class getAttributeValuesFinderClass(Class dataObjectClass, String attributeName) {
return getAttributeValuesFinderClass(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeValidatingErrorMessageKey(java.lang.String, java.lang.String)
*/
public String getAttributeValidatingErrorMessageKey(String entryName, String attributeName) {
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
if (attributeDefinition.hasValidationPattern()) {
ValidationPattern validationPattern = attributeDefinition.getValidationPattern();
return validationPattern.getValidationErrorMessageKey();
}
}
return null;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getAttributeValidatingErrorMessageParameters(java.lang.String, java.lang.String)
*/
public String[] getAttributeValidatingErrorMessageParameters(String entryName, String attributeName) {
AttributeDefinition attributeDefinition = getAttributeDefinition(entryName, attributeName);
if (attributeDefinition != null) {
if (attributeDefinition.hasValidationPattern()) {
ValidationPattern validationPattern = attributeDefinition.getValidationPattern();
String attributeLabel = getAttributeErrorLabel(entryName, attributeName);
return validationPattern.getValidationErrorMessageParameters(attributeLabel);
}
}
return null;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionDescription(java.lang.String, java.lang.String)
*/
public String getCollectionDescription(Class dataObjectClass, String collectionName) {
return getCollectionDescription(dataObjectClass.getName(), collectionName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionLabel(java.lang.String, java.lang.String)
*/
public String getCollectionLabel(Class dataObjectClass, String collectionName) {
return getCollectionLabel(dataObjectClass.getName(), collectionName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionShortLabel(java.lang.String, java.lang.String)
*/
public String getCollectionShortLabel(Class dataObjectClass, String collectionName) {
return getCollectionShortLabel(dataObjectClass.getName(), collectionName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getCollectionSummary(java.lang.String, java.lang.String)
*/
public String getCollectionSummary(Class dataObjectClass, String collectionName) {
return getCollectionSummary(dataObjectClass.getName(), collectionName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#isAttributeDefined(java.lang.String, java.lang.String)
*/
public Boolean isAttributeDefined(Class dataObjectClass, String attributeName) {
return isAttributeDefined(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#isAttributeRequired(java.lang.String, java.lang.String)
*/
public Boolean isAttributeRequired(Class dataObjectClass, String attributeName) {
return isAttributeRequired(dataObjectClass.getName(), attributeName);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getDocumentLabelByClass(java.lang.Class)
*/
public String getDocumentLabelByClass(Class documentOrBusinessObjectClass) {
return getDocumentLabelByTypeName(getDocumentTypeNameByClass(documentOrBusinessObjectClass));
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getDocumentLabelByTypeName(java.lang.String)
*/
public String getDocumentLabelByTypeName(String documentTypeName) {
String label = null;
if (StringUtils.isNotBlank(documentTypeName)) {
DocumentType documentType = getDocumentTypeService().getDocumentTypeByName(documentTypeName);
if (documentType != null) {
label = documentType.getLabel();
}
}
return label;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getDocumentTypeNameByClass(java.lang.Class)
*/
public String getDocumentTypeNameByClass(Class documentClass) {
if (documentClass == null) {
throw new IllegalArgumentException("invalid (null) documentClass");
}
if (!Document.class.isAssignableFrom(documentClass)) {
throw new IllegalArgumentException("invalid (non-Document) documentClass");
}
String documentTypeName = null;
DocumentEntry documentEntry = getDataDictionary().getDocumentEntry(documentClass.getName());
if (documentEntry != null) {
documentTypeName = documentEntry.getDocumentTypeName();
}
return documentTypeName;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getValidDocumentTypeNameByClass(java.lang.Class)
*/
public String getValidDocumentTypeNameByClass(Class documentClass) {
String documentTypeName = getDocumentTypeNameByClass(documentClass);
if (StringUtils.isBlank(documentTypeName)) {
throw new UnknownDocumentTypeException(
"unable to get documentTypeName for unknown documentClass '" + documentClass.getName() + "'");
}
return documentTypeName;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getDocumentClassByTypeName(java.lang.String)
*/
public Class<? extends Document> getDocumentClassByTypeName(String documentTypeName) {
Class clazz = null;
DocumentEntry documentEntry = getDataDictionary().getDocumentEntry(documentTypeName);
if (documentEntry != null) {
clazz = documentEntry.getDocumentClass();
}
return clazz;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getValidDocumentClassByTypeName(java.lang.String)
*/
public Class<? extends Document> getValidDocumentClassByTypeName(String documentTypeName) {
Class clazz = getDocumentClassByTypeName(documentTypeName);
if (clazz == null) {
throw new UnknownDocumentTypeException(
"unable to get class for unknown documentTypeName '" + documentTypeName + "'");
}
return clazz;
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getViewById(java.lang.String)
*/
public View getViewById(String viewId) {
return dataDictionary.getViewById(viewId);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getDictionaryObject(java.lang.String)
*/
public Object getDictionaryObject(String id) {
return dataDictionary.getDictionaryObject(id);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#containsDictionaryObject(java.lang.String)
*/
public boolean containsDictionaryObject(String id) {
return dataDictionary.containsDictionaryObject(id);
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getViewByTypeIndex(java.lang.String,
* java.util.Map)
*/
public View getViewByTypeIndex(ViewType viewTypeName, Map<String, String> indexKey) {
return dataDictionary.getViewByTypeIndex(viewTypeName, indexKey);
}
public void addDataDictionaryLocation(String location) throws IOException {
dataDictionary.addConfigFileLocation(location);
}
public void addDataDictionaryLocations(List<String> locations) throws IOException {
for (String location : locations) {
addDataDictionaryLocation(location);
}
}
/**
* @see org.kuali.rice.krad.service.DataDictionaryService#getGroupByAttributesForEffectiveDating(java.lang.Class)
*/
public List<String> getGroupByAttributesForEffectiveDating(Class dataObjectClass) {
List<String> groupByList = null;
DataObjectEntry objectEntry = getDataDictionary().getDataObjectEntry(dataObjectClass.getName());
if (objectEntry != null) {
groupByList = objectEntry.getGroupByAttributesForEffectiveDating();
}
return groupByList;
}
/**
* Returns all of the inactivation blocks registered for a particular business object
*
* @see org.kuali.rice.krad.service.DataDictionaryService#getAllInactivationBlockingDefinitions(java.lang.Class)
*/
public Set<InactivationBlockingMetadata> getAllInactivationBlockingDefinitions(
Class inactivationBlockedBusinessObjectClass) {
Set<InactivationBlockingMetadata> blockingClasses =
dataDictionary.getAllInactivationBlockingMetadatas(inactivationBlockedBusinessObjectClass);
if (blockingClasses == null) {
return Collections.emptySet();
}
return blockingClasses;
}
public DocumentTypeService getDocumentTypeService() {
if (documentTypeService == null) {
documentTypeService = KewApiServiceLocator.getDocumentTypeService();
}
return documentTypeService;
}
public void setKualiConfigurationService(ConfigurationService kualiConfigurationService) {
this.kualiConfigurationService = kualiConfigurationService;
}
public ConfigurationService getKualiConfigurationService() {
return kualiConfigurationService;
}
public KualiModuleService getKualiModuleService() {
return kualiModuleService;
}
public void setKualiModuleService(KualiModuleService kualiModuleService) {
this.kualiModuleService = kualiModuleService;
}
}
| apache-2.0 |
lithiumtech/rdbi | rdbi-recipes/src/main/java/com/lithium/dbi/rdbi/recipes/scheduler/MultiChannelScheduler.java | 21071 | package com.lithium.dbi.rdbi.recipes.scheduler;
import com.google.common.primitives.Ints;
import com.lithium.dbi.rdbi.Handle;
import com.lithium.dbi.rdbi.RDBI;
import redis.clients.jedis.Tuple;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.LongSupplier;
import java.util.stream.Collectors;
/**
* This is similar to {@link StateDedupedJobScheduler}, except that it includes a separate "channel"
* dimension and attempts to maintain fairness across channels among jobs in a particular "tube".
* <p>
* Includes support for methods from {@link StateDedupedJobScheduler} and it's abstract hierarchy,
* however does not extend from that tree because some methods now require the channel parameter
* <p>
* Definitions:
* "tube" here means the same as it means in other scheduler variations. A tube corresponds
* to a specific set of sorted sets in redis and represents a grouping of a particular type of
* job. All calls must reference a tube. Jobs are scheduled for a particular tube, and when
* {@link #reserveMulti(String, long, int)} is called, they are pulled from that referenced tube.
* <p>
* "channel" here is a new dimension, and a single tube can hold jobs for multiple channels (implemented
* as distinct sorted sets in redis). jobs for a single channel will be reserved in FIFO order
* for that particular channel, but jobs in the same tube for a different channel will be
* reserved by round-robin through all active channels. Thus a glut of jobs in one channel
* should not adversely affect other channels. The possibility, of course, still exists that
* one channel can delay itself....
* <p>
* it may prove useful to create a MultiChannelScheduler.ForChannel that extends from the {@link AbstractDedupJobScheduler} hierarchy
* // TODO This doesn't yet incorporate concepts from https://github.com/lithiumtech/rdbi/commit/6bbf2eeb49b87b71655f24fa9b797300b37b6797, that will be tackled separately
*/
public class MultiChannelScheduler {
private final RDBI rdbi;
private final String prefix;
private final LongSupplier clock;
public MultiChannelScheduler(RDBI rdbi, String redisPrefixKey, LongSupplier clock) {
this.rdbi = rdbi;
this.prefix = redisPrefixKey;
this.clock = clock;
}
public MultiChannelScheduler(RDBI rdbi, String redisPrefixKey) {
this(rdbi, redisPrefixKey, System::currentTimeMillis);
}
/**
* see {@link AbstractDedupJobScheduler#schedule(String, String, int)}
*
* @return true if the job was scheduled.
* false indicates the job already exists in the ready queue.
*/
public boolean schedule(String channel, String tube, final String job, final int runInMillis) {
try (Handle handle = rdbi.open()) {
return 1 == handle.attach(MultiChannelSchedulerDAO.class)
.scheduleJob(
getMultiChannelCircularBuffer(tube),
getMultiChannelSet(tube),
getReadyQueue(channel, tube),
getPausedKey(channel, tube),
getTubePrefix(channel, tube),
job,
clock.getAsLong() + runInMillis);
}
}
/**
* see {@link AbstractDedupJobScheduler#reserveMulti(String, long, int)}
*/
public List<TimeJobInfo> reserveMulti(String tube, long considerExpiredAfterMillis, final int maxNumberOfJobs) {
return reserveMulti(tube, considerExpiredAfterMillis, maxNumberOfJobs, 0);
}
/**
* attempt to reserve 1 or more jobs while also specifying a global running limit on jobs for this tube.
* <p>
* if the current # of running jobs + maxNumberOfJobs attempted to reserve is > runningLimit, no jobs
* will be reserved.
* <p>
* see also {@link AbstractDedupJobScheduler#reserveMulti(String, long, int)}
*
* @param tube job group. we will only grab ready jobs from this group.
* @param considerExpiredAfterMillis if jobs haven't been deleted after being reserved for this many millis, consider them expired.
* @param maxNumberOfJobs number of jobs to reserve.
* @param runningLimit if > 0, a limit of jobs we want to allow running for this particular tube type. If <= 0, no limit will be enforced.
* @return list of jobs reserved (now considered "running",) or empty list if none.
*/
public List<TimeJobInfo> reserveMulti(String tube, long considerExpiredAfterMillis, final int maxNumberOfJobs, final int runningLimit) {
return reserveMulti(tube, considerExpiredAfterMillis, maxNumberOfJobs, runningLimit, 0);
}
/**
* attempt to reserve 1 or more jobs while also specifying a global running limit on jobs for this tube.
* <p>
* if the current # of running jobs + maxNumberOfJobs attempted to reserve is > runningLimit, no jobs
* will be reserved.
* <p>
* see also {@link AbstractDedupJobScheduler#reserveMulti(String, long, int)}
*
* @param tube job group. we will only grab ready jobs from this group.
* @param considerExpiredAfterMillis if jobs haven't been deleted after being reserved for this many millis, consider them expired.
* @param maxNumberOfJobs number of jobs to reserve.
* @param runningLimit if > 0, a limit of jobs we want to allow running for this particular tube type. If <= 0, no limit will be enforced.
* @param perChannelLimit if > 0, a limit of jobs we want to allow running for any particular channel / tube combination. If <= 0, no limit will be enforced.
* Note that prior to using this, you must have called {@link #enablePerChannelTracking()}, otherwise this parameter will be ignored.
* Before enabling this, all scheduler clients should be upgraded to a version that supports per-channel tracking & limits
* @return list of jobs reserved (now considered "running",) or empty list if none.
*/
public List<TimeJobInfo> reserveMulti(String tube, long considerExpiredAfterMillis, final int maxNumberOfJobs, final int runningLimit, final int perChannelLimit) {
try (Handle handle = rdbi.open()) {
return handle.attach(MultiChannelSchedulerDAO.class).reserveJobs(
getMultiChannelCircularBuffer(tube),
getMultiChannelSet(tube),
getRunningQueue(tube),
getPerChannelTrackingEnabled(),
maxNumberOfJobs,
runningLimit,
perChannelLimit,
clock.getAsLong(),
clock.getAsLong() + considerExpiredAfterMillis);
}
}
public List<TimeJobInfo> reserveMultiForChannel(String channel, String tube, long considerExpiredAfterMillis, final int maxNumberOfJobs, final int runningLimit) {
try (Handle handle = rdbi.open()) {
return handle.attach(MultiChannelSchedulerDAO.class).reserveJobsForChannel(
getReadyQueue(channel, tube),
getRunningQueue(tube),
getPerChannelTrackingEnabled(),
getPausedKey(channel, tube),
getRunningCountKey(channel, tube),
maxNumberOfJobs,
runningLimit,
clock.getAsLong(),
clock.getAsLong() + considerExpiredAfterMillis);
}
}
public List<String> getAllReadyChannels(final String tube) {
try (Handle handle = rdbi.open()) {
// mc buffer holds the prefixes, we have to
// decompose them to get the channel only
return handle.jedis().lrange(getMultiChannelCircularBuffer(tube), 0, -1)
.stream()
// rm our prefix
.map(chPrefix -> chPrefix.replaceFirst(prefix + ":", ""))
// rm tube suffix
.map(channelAndTube -> channelAndTube.replace(":" + tube, ""))
.collect(Collectors.toList());
}
}
public long getAllReadyJobCount(String tube) {
try (Handle handle = rdbi.open()) {
return handle.attach(MultiChannelSchedulerDAO.class)
.getAllReadyJobCount(
getMultiChannelCircularBuffer(tube),
clock.getAsLong());
}
}
/**
* See {@link StateDedupedJobScheduler#ackJob(java.lang.String, java.lang.String)}
*/
public boolean ackJob(String channel, String tube, String job) {
try (Handle handle = rdbi.open()) {
return 1 == handle.attach(MultiChannelSchedulerDAO.class)
.ackJob(getRunningQueue(tube),
getRunningCountKey(channel, tube),
job);
}
}
/**
* See {@link StateDedupedJobScheduler#removeExpiredRunningJobs(java.lang.String)}
* <p>
* <b>IMPORTANT:</b> in addition, clients should iterate through the results of these, and call {@link #decrementRunningCount(String, String)}
* for each job that was expired. RDBI scheduler is at present unable to positively match up a job id with the
* channel / tube that it was scheduled for, so it cannot decrement that value on its own. Failure to do this
* will result in overcounting of running jobs by channel and tube, and possibly lead to inability to reserve
* jobs if you are also attempting to limit jobs by type and company.
* <p>
* {@link #removeExpiredRunningJobsAndDecrementCount(String, Function)} is provided as a convenience to
* bundle these operations - it is recommended to use that method instead of this one.
**/
public List<TimeJobInfo> removeExpiredRunningJobs(String tube) {
try (Handle handle = rdbi.open()) {
return handle.attach(MultiChannelSchedulerDAO.class)
.removeExpiredRunningJobs(getRunningQueue(tube),
clock.getAsLong());
}
}
/**
* Attempts to decrement the running count for a channel/tube combo, unless the count is already at zero
* <p>
* most likely to be used after calling {@link #removeExpiredRunningJobs(String)}
* <p>
* It is not recommended to use this directly, but use {@link #removeExpiredRunningJobsAndDecrementCount(String, Function)}
* instead.
* <p>
*
* @param channel the channel to operate on
* @param tube the tube to operate on
* @return the amount the running count was decremented by (1 or 0)
*/
public long decrementRunningCount(String channel, String tube) {
try (Handle handle = rdbi.open()) {
return handle.attach(MultiChannelSchedulerDAO.class)
.decrementRunningCount(getRunningCountKey(channel, tube));
}
}
/**
* will remove any expired running jobs and update the associated counters for those jobs
* so that we can keep accurate track by channel and tube of what's running.
*
* @param tube the tube to operate on
* @param jobToChannelFunction client-provided function to convert a TimeJobInfo object into a channel that must be used to
* update running counts
* @return
*/
public List<TimeJobInfo> removeExpiredRunningJobsAndDecrementCount(String tube, Function<TimeJobInfo, String> jobToChannelFunction) {
final List<TimeJobInfo> timeJobInfoList = removeExpiredRunningJobs(tube);
timeJobInfoList.stream()
.map(jobToChannelFunction)
.forEach(channel -> decrementRunningCount(channel, tube));
return timeJobInfoList;
}
/**
* if your job is running longer than you indicated when you reserved it,
* you will want to call this to update the job timeout, so that you can run it longer
* and the system will not expire it in the meantime, and possibly reschedule it
* for another worker to pick up.
*
* @param channel the channel to operate on
* @param tube the tube
* @param job the job identifier
* @param ttlIncrement the amount in ms you want to increment the ttl by
* @return boolean if the item was updated, false means it didn't exist
*/
public boolean incrementRunningTTL(String channel, String tube, String job, long ttlIncrement) {
try (Handle handle = rdbi.open()) {
return handle.attach(MultiChannelSchedulerDAO.class).incrementTTL(
getRunningQueue(tube),
ttlIncrement,
job) == 1;
}
}
/**
* removes expired ready jobs across all channels
*/
public List<TimeJobInfo> removeExpiredReadyJobs(String tube, long expirationPeriodInMillis) {
try (Handle handle = rdbi.open()) {
return handle.attach(MultiChannelSchedulerDAO.class)
.removeAllExpiredReadyJobs(getMultiChannelCircularBuffer(tube),
getMultiChannelSet(tube),
clock.getAsLong() - expirationPeriodInMillis);
}
}
/**
* Deletes a job from either ready or running queue (or both)
*/
public boolean deleteJob(String channel, String tube, String job) {
try (Handle handle = rdbi.open()) {
return 1 == handle.attach(MultiChannelSchedulerDAO.class)
.deleteJob(getMultiChannelCircularBuffer(tube),
getMultiChannelSet(tube),
getReadyQueue(channel, tube),
getRunningQueue(tube),
getRunningCountKey(channel, tube),
getTubePrefix(channel, tube),
job
);
}
}
/**
* Delete job only from the ready queue
*/
public boolean deleteJobFromReady(String channel, String tube, String job) {
try (Handle handle = rdbi.open()) {
return 1 == handle.attach(MultiChannelSchedulerDAO.class)
.deleteJobFromReady(
getMultiChannelCircularBuffer(tube),
getMultiChannelSet(tube),
getReadyQueue(channel, tube),
getTubePrefix(channel, tube),
job);
}
}
/**
* This will "pause" the system for the specified tube / channel combo, preventing any new jobs from being scheduled
* or reserved.
*
* @param tube the name of related jobs
*/
public void pause(String channel, String tube) {
rdbi.withHandle(handle -> {
handle.jedis().set(getPausedKey(channel, tube), String.valueOf(clock.getAsLong() / 1000));
return null;
});
}
public boolean isPaused(String channel, String tube) {
return rdbi.withHandle(handle -> handle.jedis().get(getPausedKey(channel, tube)) != null);
}
/**
* This returns the value for the pause key. If that value was created through this library
* it will be a unix timestamp (seconds since the epoch).
*/
public String getPauseStart(String channel, String tube) {
return rdbi.withHandle(handle -> handle.jedis().get(getPausedKey(channel, tube)));
}
/**
* This will resume / un-pause the system for the specified tube, allowing jobs to be scheduled and reserved.
*/
public void resume(String channel, String tube) {
rdbi.withHandle(handle -> {
handle.jedis().del(getPausedKey(channel, tube));
return null;
});
}
public long getReadyJobCount(String channel, String tube) {
final String queue = getReadyQueue(channel, tube);
return rdbi.withHandle(handle -> handle.jedis().zcount(queue, 0, clock.getAsLong()));
}
public long getRunningJobCount(String tube) {
final String queue = getRunningQueue(tube);
return rdbi.withHandle(handle -> handle.jedis().zcard(queue));
}
/**
* returns a list of jobs scheduled with a delay - to run in the future
*/
public List<TimeJobInfo> peekDelayed(String channel, String tube, int offset, int count) {
return peekInternal(getReadyQueue(channel, tube), (double) clock.getAsLong(), Double.MAX_VALUE, offset, count);
}
public List<TimeJobInfo> peekReady(String channel, String tube, int offset, int count) {
return peekInternal(getReadyQueue(channel, tube), 0.0d, (double) clock.getAsLong(), offset, count);
}
public List<TimeJobInfo> peekRunning(String tube, int offset, int count) {
return peekInternal(getRunningQueue(tube), (double) clock.getAsLong(), Double.MAX_VALUE, offset, count);
}
public List<TimeJobInfo> peekExpired(String tube, int offset, int count) {
return peekInternal(getRunningQueue(tube), 0.0d, (double) clock.getAsLong(), offset, count);
}
public Integer getRunningCountForChannel(String channel, String tube) {
final String key = getRunningCountKey(channel, tube);
final String count = rdbi.withHandle(h -> h.jedis().get(key));
return Optional.ofNullable(count)
.map(Ints::tryParse)
.orElse(0);
}
private List<TimeJobInfo> peekInternal(String queue, Double min, Double max, int offset, int count) {
try (Handle handle = rdbi.open()) {
Set<Tuple> tupleSet = handle.jedis().zrangeByScoreWithScores(queue, min, max, offset, count);
return tupleSet.stream()
.map(t -> new TimeJobInfo(t.getElement(), t.getScore()))
.collect(Collectors.toList());
}
}
public boolean inReadyQueue(String channel, String tube, String job) {
return inQueue(getReadyQueue(channel, tube), job);
}
public boolean inRunningQueue(String tube, String job) {
return inQueue(getRunningQueue(tube), job);
}
public boolean isPerChannelTrackingEnabled() {
return rdbi.withHandle(h -> h.jedis().get(getPerChannelTrackingEnabled()) != null);
}
/**
* enables per-channel tracking. This must be called before per channel limits can be honored
* Before enabling this, all scheduler clients should be upgraded to a version that supports per-channel tracking & limits
*
* @return true if tracking was previously disabled, false if the tracking had already been enabled
*/
public boolean enablePerChannelTracking() {
return rdbi.withHandle(h -> h.jedis().setnx(getPerChannelTrackingEnabled(), "1") == 1);
}
/**
* disabled per-channel tracking.
*
* @return true if tracking was previously enabled, false if the tracking had already been disabled
*/
public boolean disablePerChannelTracking() {
return rdbi.withHandle(h -> h.jedis().del(getPerChannelTrackingEnabled()) != 0);
}
private boolean inQueue(String queueName, String job) {
try (Handle handle = rdbi.open()) {
return 1 == handle.attach(MultiChannelSchedulerDAO.class)
.inQueue(queueName, job);
}
}
private String getMultiChannelCircularBuffer(String tube) {
return prefix + ":multichannel:" + tube + ":circular_buffer";
}
private String getMultiChannelSet(String tube) {
return prefix + ":multichannel:" + tube + ":set";
}
private String getTubePrefix(String channel, String tube) {
return prefix + ":" + channel + ":" + tube;
}
private String getReadyQueue(String channel, String tube) {
return getTubePrefix(channel, tube) + ":ready_queue";
}
private String getRunningQueue(String tube) {
return prefix + ":multichannel:" + tube + ":running_queue";
}
private String getPausedKey(String channel, String tube) {
return getTubePrefix(channel, tube) + ":paused";
}
private String getRunningCountKey(String channel, String tube) {
return getTubePrefix(channel, tube) + ":running_count";
}
private String getPerChannelTrackingEnabled() {
return prefix + ":per_channel_tracking_enabled";
}
}
| apache-2.0 |
christophd/camel | components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowHttpPojoInOutTest.java | 3035 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.undertow.rest;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.undertow.BaseUndertowTest;
import org.apache.camel.model.rest.RestBindingMode;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class RestUndertowHttpPojoInOutTest extends BaseUndertowTest {
@Test
public void testUndertowPojoInOut() throws Exception {
String body = "{\"id\": 123, \"name\": \"Donald Duck\"}";
String out = template.requestBody("undertow:http://localhost:{{port}}/users/lives", body, String.class);
assertNotNull(out);
assertEquals("{\"iso\":\"EN\",\"country\":\"England\"}", out);
}
@Test
public void testUndertowGetRequest() throws Exception {
String out = template.requestBody("undertow:http://localhost:{{port}}/users/lives", null, String.class);
assertNotNull(out);
assertEquals("{\"iso\":\"EN\",\"country\":\"England\"}", out);
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// configure to use undertow on localhost with the given port
// and enable auto binding mode
restConfiguration().component("undertow").host("localhost").port(getPort()).bindingMode(RestBindingMode.auto);
// use the rest DSL to define the rest services
rest("/users/")
// just return the default country here
.get("lives").to("direct:start")
.post("lives").type(UserPojo.class).outType(CountryPojo.class)
.to("direct:lives");
from("direct:lives")
.bean(new UserService(), "livesWhere");
CountryPojo country = new CountryPojo();
country.setIso("EN");
country.setCountry("England");
from("direct:start").transform().constant(country);
}
};
}
}
| apache-2.0 |
tuenti/android-deferred | deferred/src/main/java/com/tuenti/deferred/Logger.java | 719 | /*
* Copyright (c) Tuenti Technologies S.L. 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.tuenti.deferred;
public interface Logger {
void error(String s, Exception e);
}
| apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201308/DeviceCapabilityTargeting.java | 8113 | /**
* DeviceCapabilityTargeting.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.v201308;
/**
* Represents device capabilities that are being targeted or excluded
* by the {@link LineItem}.
*/
public class DeviceCapabilityTargeting implements java.io.Serializable {
/* Device capabilities that are being targeted by the {@link LineItem}. */
private com.google.api.ads.dfp.axis.v201308.Technology[] targetedDeviceCapabilities;
/* Device capabilities that are being excluded by the {@link LineItem}. */
private com.google.api.ads.dfp.axis.v201308.Technology[] excludedDeviceCapabilities;
public DeviceCapabilityTargeting() {
}
public DeviceCapabilityTargeting(
com.google.api.ads.dfp.axis.v201308.Technology[] targetedDeviceCapabilities,
com.google.api.ads.dfp.axis.v201308.Technology[] excludedDeviceCapabilities) {
this.targetedDeviceCapabilities = targetedDeviceCapabilities;
this.excludedDeviceCapabilities = excludedDeviceCapabilities;
}
/**
* Gets the targetedDeviceCapabilities value for this DeviceCapabilityTargeting.
*
* @return targetedDeviceCapabilities * Device capabilities that are being targeted by the {@link LineItem}.
*/
public com.google.api.ads.dfp.axis.v201308.Technology[] getTargetedDeviceCapabilities() {
return targetedDeviceCapabilities;
}
/**
* Sets the targetedDeviceCapabilities value for this DeviceCapabilityTargeting.
*
* @param targetedDeviceCapabilities * Device capabilities that are being targeted by the {@link LineItem}.
*/
public void setTargetedDeviceCapabilities(com.google.api.ads.dfp.axis.v201308.Technology[] targetedDeviceCapabilities) {
this.targetedDeviceCapabilities = targetedDeviceCapabilities;
}
public com.google.api.ads.dfp.axis.v201308.Technology getTargetedDeviceCapabilities(int i) {
return this.targetedDeviceCapabilities[i];
}
public void setTargetedDeviceCapabilities(int i, com.google.api.ads.dfp.axis.v201308.Technology _value) {
this.targetedDeviceCapabilities[i] = _value;
}
/**
* Gets the excludedDeviceCapabilities value for this DeviceCapabilityTargeting.
*
* @return excludedDeviceCapabilities * Device capabilities that are being excluded by the {@link LineItem}.
*/
public com.google.api.ads.dfp.axis.v201308.Technology[] getExcludedDeviceCapabilities() {
return excludedDeviceCapabilities;
}
/**
* Sets the excludedDeviceCapabilities value for this DeviceCapabilityTargeting.
*
* @param excludedDeviceCapabilities * Device capabilities that are being excluded by the {@link LineItem}.
*/
public void setExcludedDeviceCapabilities(com.google.api.ads.dfp.axis.v201308.Technology[] excludedDeviceCapabilities) {
this.excludedDeviceCapabilities = excludedDeviceCapabilities;
}
public com.google.api.ads.dfp.axis.v201308.Technology getExcludedDeviceCapabilities(int i) {
return this.excludedDeviceCapabilities[i];
}
public void setExcludedDeviceCapabilities(int i, com.google.api.ads.dfp.axis.v201308.Technology _value) {
this.excludedDeviceCapabilities[i] = _value;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof DeviceCapabilityTargeting)) return false;
DeviceCapabilityTargeting other = (DeviceCapabilityTargeting) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.targetedDeviceCapabilities==null && other.getTargetedDeviceCapabilities()==null) ||
(this.targetedDeviceCapabilities!=null &&
java.util.Arrays.equals(this.targetedDeviceCapabilities, other.getTargetedDeviceCapabilities()))) &&
((this.excludedDeviceCapabilities==null && other.getExcludedDeviceCapabilities()==null) ||
(this.excludedDeviceCapabilities!=null &&
java.util.Arrays.equals(this.excludedDeviceCapabilities, other.getExcludedDeviceCapabilities())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getTargetedDeviceCapabilities() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getTargetedDeviceCapabilities());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getTargetedDeviceCapabilities(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getExcludedDeviceCapabilities() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getExcludedDeviceCapabilities());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getExcludedDeviceCapabilities(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(DeviceCapabilityTargeting.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "DeviceCapabilityTargeting"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("targetedDeviceCapabilities");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "targetedDeviceCapabilities"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "Technology"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("excludedDeviceCapabilities");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "excludedDeviceCapabilities"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201308", "Technology"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
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 |
psbateman/org-treewalk-scms | org-treewalk-scms-integration/org-treewalk-scms-integration-maven-central/src/test/java/org/treewalk/scms/integration/maven/central/MavenComponentTransformationTest.java | 104 | package org.treewalk.scms.integration.maven.central;
public class MavenComponentTransformationTest {
}
| apache-2.0 |
zhaoshiling1017/SSM-Platform | src/main/java/com/ducetech/app/model/Role.java | 1072 | package com.ducetech.app.model;
import com.ducetech.framework.model.BaseModel;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class Role extends BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
private String roleId; //角色ID
private String roleName; //角色名称
private String comment; //备注
private String deptId; //部门ID
private String permissionIds; //菜单权限IDS
private String permissionMajorIds; //菜单权限专业IDS
private String permissionDeptIds; //菜单权限部门IDS
private String groupIds; //审批组IDS
private List<Permission> permissions;
private List<User> users; //已配人员
private String userNames; //已配人员名字
private String creatorId; //创建人ID
private User creator; //创建人
private String createdAt; //创建时间
private String isDeleted; //删除标记 0启用 1停用 默认0启用
}
| apache-2.0 |
leafcoin/leafcoinj-alice | core/src/main/java/com/google/leafcoin/protocols/channels/PaymentChannelServer.java | 20832 | package com.google.leafcoin.protocols.channels;
import com.google.leafcoin.core.*;
import com.google.leafcoin.protocols.channels.PaymentChannelCloseException.CloseReason;
import com.google.leafcoin.utils.Threading;
import com.google.protobuf.ByteString;
import net.jcip.annotations.GuardedBy;
import org.bitcoin.paymentchannel.Protos;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* <p>A handler class which handles most of the complexity of creating a payment channel connection by providing a
* simple in/out interface which is provided with protobufs from the client and which generates protobufs which should
* be sent to the client.</p>
*
* <p>Does all required verification of messages and properly stores state objects in the wallet-attached
* {@link StoredPaymentChannelServerStates} so that they are automatically closed when necessary and payment
* transactions are not lost if the application crashes before it unlocks.</p>
*/
public class PaymentChannelServer {
//TODO: Update JavaDocs with notes for communication over stateless protocols
private static final org.slf4j.Logger log = LoggerFactory.getLogger(PaymentChannelServer.class);
protected final ReentrantLock lock = Threading.lock("channelserver");
// The step in the initialization process we are in, some of this is duplicated in the PaymentChannelServerState
private enum InitStep {
WAITING_ON_CLIENT_VERSION,
WAITING_ON_UNSIGNED_REFUND,
WAITING_ON_CONTRACT,
WAITING_ON_MULTISIG_ACCEPTANCE,
CHANNEL_OPEN
}
@GuardedBy("lock") private InitStep step = InitStep.WAITING_ON_CLIENT_VERSION;
/**
* Implements the connection between this server and the client, providing an interface which allows messages to be
* sent to the client, requests for the connection to the client to be closed, and callbacks which occur when the
* channel is fully open or the client completes a payment.
*/
public interface ServerConnection {
/**
* <p>Requests that the given message be sent to the client. There are no blocking requirements for this method,
* however the order of messages must be preserved.</p>
*
* <p>If the send fails, no exception should be thrown, however
* {@link PaymentChannelServer#connectionClosed()} should be called immediately.</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelServer} object - be careful about reentrancy</p>
*/
public void sendToClient(Protos.TwoWayChannelMessage msg);
/**
* <p>Requests that the connection to the client be closed</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelServer} object - be careful about reentrancy</p>
*
* @param reason The reason for the closure, see the individual values for more details.
* It is usually safe to ignore this value.
*/
public void destroyConnection(CloseReason reason);
/**
* <p>Triggered when the channel is opened and payments can begin</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelServer} object - be careful about reentrancy</p>
*
* @param contractHash A unique identifier which represents this channel (actually the hash of the multisig contract)
*/
public void channelOpen(Sha256Hash contractHash);
/**
* <p>Called when the payment in this channel was successfully incremented by the client</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelServer} object - be careful about reentrancy</p>
*
* @param by The increase in total payment
* @param to The new total payment to us (not including fees which may be required to claim the payment)
*/
public void paymentIncrease(BigInteger by, BigInteger to);
}
@GuardedBy("lock") private final ServerConnection conn;
// Used to keep track of whether or not the "socket" ie connection is open and we can generate messages
@GuardedBy("lock") private boolean connectionOpen = false;
// Indicates that no further messages should be sent and we intend to close the connection
@GuardedBy("lock") private boolean connectionClosing = false;
// The wallet and peergroup which are used to complete/broadcast transactions
private final Wallet wallet;
private final TransactionBroadcaster broadcaster;
// The key used for multisig in this channel
@GuardedBy("lock") private ECKey myKey;
// The minimum accepted channel value
private final BigInteger minAcceptedChannelSize;
// The state manager for this channel
@GuardedBy("lock") private PaymentChannelServerState state;
// The time this channel expires (ie the refund transaction's locktime)
@GuardedBy("lock") private long expireTime;
/**
* <p>The amount of time we request the client lock in their funds.</p>
*
* <p>The value defaults to 24 hours - 60 seconds and should always be greater than 2 hours plus the amount of time
* the channel is expected to be used and smaller than 24 hours minus the client <-> server latency minus some
* factor to account for client clock inaccuracy.</p>
*/
public long timeWindow = 24*60*60 - 60;
/**
* Creates a new server-side state manager which handles a single client connection.
*
* @param broadcaster The PeerGroup on which transactions will be broadcast - should have multiple connections.
* @param wallet The wallet which will be used to complete transactions.
* Unlike {@link PaymentChannelClient}, this does not have to already contain a StoredState manager
* @param minAcceptedChannelSize The minimum value the client must lock into this channel. A value too large will be
* rejected by clients, and a value too low will require excessive channel reopening
* and may cause fees to be require to close the channel. A reasonable value depends
* entirely on the expected maximum for the channel, and should likely be somewhere
* between a few bitcents and a leafcoin.
* @param conn A callback listener which represents the connection to the client (forwards messages we generate to
* the client and will close the connection on request)
*/
public PaymentChannelServer(TransactionBroadcaster broadcaster, Wallet wallet,
BigInteger minAcceptedChannelSize, ServerConnection conn) {
this.broadcaster = checkNotNull(broadcaster);
this.wallet = checkNotNull(wallet);
this.minAcceptedChannelSize = checkNotNull(minAcceptedChannelSize);
this.conn = checkNotNull(conn);
}
@GuardedBy("lock")
private void receiveVersionMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
Protos.ServerVersion.Builder versionNegotiationBuilder = Protos.ServerVersion.newBuilder()
.setMajor(0).setMinor(1);
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.SERVER_VERSION)
.setServerVersion(versionNegotiationBuilder)
.build());
ByteString reopenChannelContractHash = msg.getClientVersion().getPreviousChannelContractHash();
if (reopenChannelContractHash != null && reopenChannelContractHash.size() == 32) {
Sha256Hash contractHash = new Sha256Hash(reopenChannelContractHash.toByteArray());
log.info("New client that wants to resume {}", contractHash);
StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates)
wallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID);
if (channels != null) {
StoredServerChannel storedServerChannel = channels.getChannel(contractHash);
if (storedServerChannel != null) {
final PaymentChannelServer existingHandler = storedServerChannel.setConnectedHandler(this, false);
if (existingHandler != this) {
log.warn(" ... and that channel is already in use, disconnecting other user.");
existingHandler.close();
storedServerChannel.setConnectedHandler(this, true);
}
log.info("Got resume version message, responding with VERSIONS and CHANNEL_OPEN");
state = storedServerChannel.getOrCreateState(wallet, broadcaster);
step = InitStep.CHANNEL_OPEN;
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.CHANNEL_OPEN)
.build());
conn.channelOpen(contractHash);
return;
} else {
log.error(" ... but we do not have any record of that contract! Resume failed.");
}
} else {
log.error(" ... but we do not have any stored channels! Resume failed.");
}
}
log.info("Got initial version message, responding with VERSIONS and INITIATE");
myKey = new ECKey();
wallet.addKey(myKey);
expireTime = Utils.now().getTime() / 1000 + timeWindow;
step = InitStep.WAITING_ON_UNSIGNED_REFUND;
Protos.Initiate.Builder initiateBuilder = Protos.Initiate.newBuilder()
.setMultisigKey(ByteString.copyFrom(myKey.getPubKey()))
.setExpireTimeSecs(expireTime)
.setMinAcceptedChannelSize(minAcceptedChannelSize.longValue());
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setInitiate(initiateBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.INITIATE)
.build());
}
@GuardedBy("lock")
private void receiveRefundMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
checkState(step == InitStep.WAITING_ON_UNSIGNED_REFUND && msg.hasProvideRefund());
log.info("Got refund transaction, returning signature");
Protos.ProvideRefund providedRefund = msg.getProvideRefund();
state = new PaymentChannelServerState(broadcaster, wallet, myKey, expireTime);
byte[] signature = state.provideRefundTransaction(new Transaction(wallet.getParams(), providedRefund.getTx().toByteArray()),
providedRefund.getMultisigKey().toByteArray());
step = InitStep.WAITING_ON_CONTRACT;
Protos.ReturnRefund.Builder returnRefundBuilder = Protos.ReturnRefund.newBuilder()
.setSignature(ByteString.copyFrom(signature));
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setReturnRefund(returnRefundBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.RETURN_REFUND)
.build());
}
private void multisigContractPropogated(Sha256Hash contractHash) {
lock.lock();
try {
if (!connectionOpen || connectionClosing)
return;
state.storeChannelInWallet(PaymentChannelServer.this);
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.CHANNEL_OPEN)
.build());
step = InitStep.CHANNEL_OPEN;
conn.channelOpen(contractHash);
} finally {
lock.unlock();
}
}
@GuardedBy("lock")
private void receiveContractMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
checkState(step == InitStep.WAITING_ON_CONTRACT && msg.hasProvideContract());
log.info("Got contract, broadcasting and responding with CHANNEL_OPEN");
Protos.ProvideContract providedContract = msg.getProvideContract();
//TODO notify connection handler that timeout should be significantly extended as we wait for network propagation?
final Transaction multisigContract = new Transaction(wallet.getParams(), providedContract.getTx().toByteArray());
step = InitStep.WAITING_ON_MULTISIG_ACCEPTANCE;
state.provideMultiSigContract(multisigContract)
.addListener(new Runnable() {
@Override
public void run() {
multisigContractPropogated(multisigContract.getHash());
}
}, Threading.SAME_THREAD);
}
@GuardedBy("lock")
private void receiveUpdatePaymentMessage(Protos.TwoWayChannelMessage msg) throws VerificationException, ValueOutOfRangeException {
checkState(step == InitStep.CHANNEL_OPEN && msg.hasUpdatePayment());
log.info("Got a payment update");
Protos.UpdatePayment updatePayment = msg.getUpdatePayment();
BigInteger lastBestPayment = state.getBestValueToMe();
state.incrementPayment(BigInteger.valueOf(updatePayment.getClientChangeValue()), updatePayment.getSignature().toByteArray());
BigInteger bestPaymentChange = state.getBestValueToMe().subtract(lastBestPayment);
if (bestPaymentChange.compareTo(BigInteger.ZERO) > 0)
conn.paymentIncrease(bestPaymentChange, state.getBestValueToMe());
}
/**
* Called when a message is received from the client. Processes the given message and generates events based on its
* content.
*/
public void receiveMessage(Protos.TwoWayChannelMessage msg) {
lock.lock();
try {
checkState(connectionOpen);
if (connectionClosing)
return;
// If we generate an error, we set errorBuilder and closeReason and break, otherwise we return
Protos.Error.Builder errorBuilder;
CloseReason closeReason;
try {
switch (msg.getType()) {
case CLIENT_VERSION:
checkState(step == InitStep.WAITING_ON_CLIENT_VERSION && msg.hasClientVersion());
if (msg.getClientVersion().getMajor() != 0) {
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.NO_ACCEPTABLE_VERSION);
closeReason = CloseReason.NO_ACCEPTABLE_VERSION;
break;
}
receiveVersionMessage(msg);
return;
case PROVIDE_REFUND:
receiveRefundMessage(msg);
return;
case PROVIDE_CONTRACT:
receiveContractMessage(msg);
return;
case UPDATE_PAYMENT:
receiveUpdatePaymentMessage(msg);
return;
case CLOSE:
log.info("Got CLOSE message, closing channel");
connectionClosing = true;
if (state != null)
state.close();
conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
return;
case ERROR:
checkState(msg.hasError());
log.error("Client sent ERROR {} with explanation {}", msg.getError().getCode().name(),
msg.getError().hasExplanation() ? msg.getError().getExplanation() : "");
conn.destroyConnection(CloseReason.REMOTE_SENT_ERROR);
return;
default:
log.error("Got unknown message type or type that doesn't apply to servers.");
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.SYNTAX_ERROR);
closeReason = CloseReason.REMOTE_SENT_INVALID_MESSAGE;
break;
}
} catch (VerificationException e) {
log.error("Caught verification exception handling message from client {}", e);
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.BAD_TRANSACTION)
.setExplanation(e.getMessage());
closeReason = CloseReason.REMOTE_SENT_INVALID_MESSAGE;
} catch (ValueOutOfRangeException e) {
log.error("Caught value out of range exception handling message from client {}", e);
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.BAD_TRANSACTION)
.setExplanation(e.getMessage());
closeReason = CloseReason.REMOTE_SENT_INVALID_MESSAGE;
} catch (IllegalStateException e) {
log.error("Caught illegal state exception handling message from client {}", e);
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.SYNTAX_ERROR);
closeReason = CloseReason.REMOTE_SENT_INVALID_MESSAGE;
}
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setError(errorBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.ERROR)
.build());
conn.destroyConnection(closeReason);
} finally {
lock.unlock();
}
}
/**
* <p>Called when the connection terminates. Notifies the {@link StoredServerChannel} object that we can attempt to
* resume this channel in the future and stops generating messages for the client.</p>
*
* <p>Note that this <b>MUST</b> still be called even after either
* {@link ServerConnection#destroyConnection(CloseReason)} or
* {@link PaymentChannelServer#close()} is called to actually handle the connection close logic.</p>
*/
public void connectionClosed() {
lock.lock();
try {
log.info("Server channel closed.");
connectionOpen = false;
try {
if (state != null && state.getMultisigContract() != null) {
StoredPaymentChannelServerStates channels = (StoredPaymentChannelServerStates)
wallet.getExtensions().get(StoredPaymentChannelServerStates.EXTENSION_ID);
if (channels != null) {
StoredServerChannel storedServerChannel = channels.getChannel(state.getMultisigContract().getHash());
if (storedServerChannel != null) {
storedServerChannel.clearConnectedHandler();
}
}
}
} catch (IllegalStateException e) {
// Expected when we call getMultisigContract() sometimes
}
} finally {
lock.unlock();
}
}
/**
* Called to indicate the connection has been opened and messages can now be generated for the client.
*/
public void connectionOpen() {
lock.lock();
try {
log.info("New server channel active.");
connectionOpen = true;
} finally {
lock.unlock();
}
}
/**
* <p>Closes the connection by generating a close message for the client and calls
* {@link ServerConnection#destroyConnection(CloseReason)}. Note that this does not broadcast
* the payment transaction and the client may still resume the same channel if they reconnect</p>
*
* <p>Note that {@link PaymentChannelServer#connectionClosed()} must still be called after the connection fully
* closes.</p>
*/
public void close() {
lock.lock();
try {
if (connectionOpen && !connectionClosing) {
conn.sendToClient(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.CLOSE)
.build());
conn.destroyConnection(CloseReason.SERVER_REQUESTED_CLOSE);
}
} finally {
lock.unlock();
}
}
}
| apache-2.0 |
Dennis-Koch/ambeth | jambeth/jambeth-merge/src/main/java/com/koch/ambeth/merge/IDeepScanRecursion.java | 2946 | package com.koch.ambeth.merge;
/**
* Allows to apply a generic algorithm of crawling through collections and arrays of entities and
* calling a provided delegate for each resolved entity instance. It is also ensured that a resolved
* entity is forwarded exactly once.
*/
public interface IDeepScanRecursion {
/**
* The handle provided to the {@link EntityDelegate#visitEntity(Object, Proceed)} when called by
* the {@link IDeepScanRecursion#handleDeep(Object, EntityDelegate)} algorithm. It allows to
* proceed recursively with a given object handle that - in most cases - may have been resolved by
* accessing specific properties of the previous passed on entity instance (e.g. a relational
* value).
*/
interface Proceed {
boolean proceed(Object obj);
boolean proceed(Object obj, EntityDelegate entityDelegate);
}
/**
* The delegate provided initially to the
* {@link IDeepScanRecursion#handleDeep(Object, EntityDelegate) algorithm. The delegate be locally
* exchanged can during recursion when using the {@link Proceed#proceed(Object, EntityDelegate)}
* overload. As long as {@link Proceed#proceed(Object)} is used the current delegate is
* continuously applied.
*/
interface EntityDelegate {
/**
* Called by the recursion algorithm for each discovered entity. This method is called once per
* each discovered instance per initial call to
* {@link IDeepScanRecursion#handleDeep(Object, EntityDelegate)}.
*
* @param entity The entity discovered by crawling through the initial object handle on any
* depth
* @param proceed The handle to allow to crawl "deeper" through the object graph by reusing the
* existing recursion session (means that it is further guaranteed to not produce a cycle
* - each resolved entity, entity-containing collection or entity-containing array at any
* depth is only processed once)
* @return false if the complete recursion shall terminate (that is: no other entities are
* resolved and the outer {@link IDeepScanRecursion#handleDeep(Object, EntityDelegate)}
* call will terminate. True if the algorithm shall further proceed with other entities.
*/
boolean visitEntity(Object entity, Proceed proceed);
}
/**
* Instantiates a new recursive process to "crawl through" the given obj instance and calling the
* specific delegate for each discovered entity instance.
*
* @param obj The initial object handle to start the crawling algorithm. It may be any type of
* {@link Iterable}, array or a single entity instance.
* @param entityDelegate The delegate which receives any discovered entity instance. This delegate
* may "finish" the recursion at that step or it may invoke an additional depth of
* recursion by calling one of the methods of the passed on {@link Proceed} handle.
*/
void handleDeep(Object obj, EntityDelegate entityDelegate);
}
| apache-2.0 |
yeasy/lazyctrl | ccm/floodlight-lc/src/main/java/net/floodlightcontroller/core/types/PortIpPair.java | 1404 | /**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.floodlightcontroller.core.types;
public class PortIpPair {
public Short port;
public int ip;
public PortIpPair(Short port, int ip) {
this.port = port;
this.ip = ip;
}
public void setPort(Short port) {
this.port = port;
}
public void setIp(int ip) {
this.ip = ip;
}
public int getPort() {
return port.shortValue();
}
public int getIp() {
return ip;
}
public boolean equals(Object o) {
return (o instanceof PortIpPair) && (port.equals(((PortIpPair) o).port))
&& (ip==(((PortIpPair) o).ip));
}
public int hashCode() {
return port.hashCode() ^ ip;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/InitiateAuthRequest.java | 42800 | /*
* 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.cognitoidp.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Initiates the authentication request.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/InitiateAuth" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InitiateAuthRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP variables
* to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return the next
* challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access token
* and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a
* user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME is not
* found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* </p>
*/
private String authFlow;
/**
* <p>
* The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code> that you are invoking.
* The required values depend on the value of <code>AuthFlow</code>:
* </p>
* <ul>
* <li>
* <p>
* For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code> (if app client is
* configured with client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* </ul>
*/
private java.util.Map<String, String> authParameters;
/**
* <p>
* This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda
* trigger as-is. It can be used to implement additional validations around authentication.
* </p>
*/
private java.util.Map<String, String> clientMetadata;
/**
* <p>
* The app client ID.
* </p>
*/
private String clientId;
/**
* <p>
* The Amazon Pinpoint analytics metadata for collecting metrics for <code>InitiateAuth</code> calls.
* </p>
*/
private AnalyticsMetadataType analyticsMetadata;
/**
* <p>
* Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an
* unexpected event by Amazon Cognito advanced security.
* </p>
*/
private UserContextDataType userContextData;
/**
* <p>
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP variables
* to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return the next
* challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access token
* and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a
* user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME is not
* found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* </p>
*
* @param authFlow
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP
* variables to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return
* the next challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access
* token and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly.
* If a user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME
* is not found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* @see AuthFlowType
*/
public void setAuthFlow(String authFlow) {
this.authFlow = authFlow;
}
/**
* <p>
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP variables
* to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return the next
* challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access token
* and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a
* user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME is not
* found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* </p>
*
* @return The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP
* variables to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return
* the next challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access
* token and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly.
* If a user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the
* USERNAME is not found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* @see AuthFlowType
*/
public String getAuthFlow() {
return this.authFlow;
}
/**
* <p>
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP variables
* to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return the next
* challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access token
* and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a
* user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME is not
* found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* </p>
*
* @param authFlow
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP
* variables to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return
* the next challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access
* token and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly.
* If a user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME
* is not found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* @return Returns a reference to this object so that method calls can be chained together.
* @see AuthFlowType
*/
public InitiateAuthRequest withAuthFlow(String authFlow) {
setAuthFlow(authFlow);
return this;
}
/**
* <p>
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP variables
* to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return the next
* challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access token
* and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a
* user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME is not
* found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* </p>
*
* @param authFlow
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP
* variables to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return
* the next challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access
* token and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly.
* If a user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME
* is not found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* @see AuthFlowType
*/
public void setAuthFlow(AuthFlowType authFlow) {
withAuthFlow(authFlow);
}
/**
* <p>
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP variables
* to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return the next
* challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access token
* and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly. If a
* user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME is not
* found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* </p>
*
* @param authFlow
* The authentication flow for this call to execute. The API action will depend on this value. For example:
* </p>
* <ul>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new tokens.
* </p>
* </li>
* <li>
* <p>
* <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> and return the SRP
* variables to be used for next challenge execution.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> and return
* the next challenge or tokens.
* </p>
* </li>
* </ul>
* <p>
* Valid values include:
* </p>
* <ul>
* <li>
* <p>
* <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) protocol.
* </p>
* </li>
* <li>
* <p>
* <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for refreshing the access
* token and ID token by supplying a valid refresh token.
* </p>
* </li>
* <li>
* <p>
* <code>CUSTOM_AUTH</code>: Custom authentication flow.
* </p>
* </li>
* <li>
* <p>
* <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD are passed directly.
* If a user migration Lambda trigger is set, this flow will invoke the user migration Lambda if the USERNAME
* is not found in the user pool.
* </p>
* </li>
* </ul>
* <p>
* <code>ADMIN_NO_SRP_AUTH</code> is not a valid value.
* @return Returns a reference to this object so that method calls can be chained together.
* @see AuthFlowType
*/
public InitiateAuthRequest withAuthFlow(AuthFlowType authFlow) {
this.authFlow = authFlow.toString();
return this;
}
/**
* <p>
* The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code> that you are invoking.
* The required values depend on the value of <code>AuthFlow</code>:
* </p>
* <ul>
* <li>
* <p>
* For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code> (if app client is
* configured with client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* </ul>
*
* @return The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code> that you are
* invoking. The required values depend on the value of <code>AuthFlow</code>:</p>
* <ul>
* <li>
* <p>
* For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret),
* <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret),
* <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code> (if app client
* is configured with client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
*/
public java.util.Map<String, String> getAuthParameters() {
return authParameters;
}
/**
* <p>
* The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code> that you are invoking.
* The required values depend on the value of <code>AuthFlow</code>:
* </p>
* <ul>
* <li>
* <p>
* For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code> (if app client is
* configured with client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* </ul>
*
* @param authParameters
* The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code> that you are
* invoking. The required values depend on the value of <code>AuthFlow</code>:</p>
* <ul>
* <li>
* <p>
* For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret),
* <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret),
* <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code> (if app client is
* configured with client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
*/
public void setAuthParameters(java.util.Map<String, String> authParameters) {
this.authParameters = authParameters;
}
/**
* <p>
* The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code> that you are invoking.
* The required values depend on the value of <code>AuthFlow</code>:
* </p>
* <ul>
* <li>
* <p>
* For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code> (if app client is
* configured with client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* </ul>
*
* @param authParameters
* The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code> that you are
* invoking. The required values depend on the value of <code>AuthFlow</code>:</p>
* <ul>
* <li>
* <p>
* For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret),
* <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required),
* <code>SECRET_HASH</code> (required if the app client is configured with a client secret),
* <code>DEVICE_KEY</code>
* </p>
* </li>
* <li>
* <p>
* For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code> (if app client is
* configured with client secret), <code>DEVICE_KEY</code>
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InitiateAuthRequest withAuthParameters(java.util.Map<String, String> authParameters) {
setAuthParameters(authParameters);
return this;
}
public InitiateAuthRequest addAuthParametersEntry(String key, String value) {
if (null == this.authParameters) {
this.authParameters = new java.util.HashMap<String, String>();
}
if (this.authParameters.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.authParameters.put(key, value);
return this;
}
/**
* Removes all the entries added into AuthParameters.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InitiateAuthRequest clearAuthParametersEntries() {
this.authParameters = null;
return this;
}
/**
* <p>
* This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda
* trigger as-is. It can be used to implement additional validations around authentication.
* </p>
*
* @return This is a random key-value pair map which can contain any key and will be passed to your
* PreAuthentication Lambda trigger as-is. It can be used to implement additional validations around
* authentication.
*/
public java.util.Map<String, String> getClientMetadata() {
return clientMetadata;
}
/**
* <p>
* This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda
* trigger as-is. It can be used to implement additional validations around authentication.
* </p>
*
* @param clientMetadata
* This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication
* Lambda trigger as-is. It can be used to implement additional validations around authentication.
*/
public void setClientMetadata(java.util.Map<String, String> clientMetadata) {
this.clientMetadata = clientMetadata;
}
/**
* <p>
* This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication Lambda
* trigger as-is. It can be used to implement additional validations around authentication.
* </p>
*
* @param clientMetadata
* This is a random key-value pair map which can contain any key and will be passed to your PreAuthentication
* Lambda trigger as-is. It can be used to implement additional validations around authentication.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InitiateAuthRequest withClientMetadata(java.util.Map<String, String> clientMetadata) {
setClientMetadata(clientMetadata);
return this;
}
public InitiateAuthRequest addClientMetadataEntry(String key, String value) {
if (null == this.clientMetadata) {
this.clientMetadata = new java.util.HashMap<String, String>();
}
if (this.clientMetadata.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.clientMetadata.put(key, value);
return this;
}
/**
* Removes all the entries added into ClientMetadata.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InitiateAuthRequest clearClientMetadataEntries() {
this.clientMetadata = null;
return this;
}
/**
* <p>
* The app client ID.
* </p>
*
* @param clientId
* The app client ID.
*/
public void setClientId(String clientId) {
this.clientId = clientId;
}
/**
* <p>
* The app client ID.
* </p>
*
* @return The app client ID.
*/
public String getClientId() {
return this.clientId;
}
/**
* <p>
* The app client ID.
* </p>
*
* @param clientId
* The app client ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InitiateAuthRequest withClientId(String clientId) {
setClientId(clientId);
return this;
}
/**
* <p>
* The Amazon Pinpoint analytics metadata for collecting metrics for <code>InitiateAuth</code> calls.
* </p>
*
* @param analyticsMetadata
* The Amazon Pinpoint analytics metadata for collecting metrics for <code>InitiateAuth</code> calls.
*/
public void setAnalyticsMetadata(AnalyticsMetadataType analyticsMetadata) {
this.analyticsMetadata = analyticsMetadata;
}
/**
* <p>
* The Amazon Pinpoint analytics metadata for collecting metrics for <code>InitiateAuth</code> calls.
* </p>
*
* @return The Amazon Pinpoint analytics metadata for collecting metrics for <code>InitiateAuth</code> calls.
*/
public AnalyticsMetadataType getAnalyticsMetadata() {
return this.analyticsMetadata;
}
/**
* <p>
* The Amazon Pinpoint analytics metadata for collecting metrics for <code>InitiateAuth</code> calls.
* </p>
*
* @param analyticsMetadata
* The Amazon Pinpoint analytics metadata for collecting metrics for <code>InitiateAuth</code> calls.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InitiateAuthRequest withAnalyticsMetadata(AnalyticsMetadataType analyticsMetadata) {
setAnalyticsMetadata(analyticsMetadata);
return this;
}
/**
* <p>
* Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an
* unexpected event by Amazon Cognito advanced security.
* </p>
*
* @param userContextData
* Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the
* risk of an unexpected event by Amazon Cognito advanced security.
*/
public void setUserContextData(UserContextDataType userContextData) {
this.userContextData = userContextData;
}
/**
* <p>
* Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an
* unexpected event by Amazon Cognito advanced security.
* </p>
*
* @return Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the
* risk of an unexpected event by Amazon Cognito advanced security.
*/
public UserContextDataType getUserContextData() {
return this.userContextData;
}
/**
* <p>
* Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the risk of an
* unexpected event by Amazon Cognito advanced security.
* </p>
*
* @param userContextData
* Contextual data such as the user's device fingerprint, IP address, or location used for evaluating the
* risk of an unexpected event by Amazon Cognito advanced security.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InitiateAuthRequest withUserContextData(UserContextDataType userContextData) {
setUserContextData(userContextData);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAuthFlow() != null)
sb.append("AuthFlow: ").append(getAuthFlow()).append(",");
if (getAuthParameters() != null)
sb.append("AuthParameters: ").append(getAuthParameters()).append(",");
if (getClientMetadata() != null)
sb.append("ClientMetadata: ").append(getClientMetadata()).append(",");
if (getClientId() != null)
sb.append("ClientId: ").append("***Sensitive Data Redacted***").append(",");
if (getAnalyticsMetadata() != null)
sb.append("AnalyticsMetadata: ").append(getAnalyticsMetadata()).append(",");
if (getUserContextData() != null)
sb.append("UserContextData: ").append(getUserContextData());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof InitiateAuthRequest == false)
return false;
InitiateAuthRequest other = (InitiateAuthRequest) obj;
if (other.getAuthFlow() == null ^ this.getAuthFlow() == null)
return false;
if (other.getAuthFlow() != null && other.getAuthFlow().equals(this.getAuthFlow()) == false)
return false;
if (other.getAuthParameters() == null ^ this.getAuthParameters() == null)
return false;
if (other.getAuthParameters() != null && other.getAuthParameters().equals(this.getAuthParameters()) == false)
return false;
if (other.getClientMetadata() == null ^ this.getClientMetadata() == null)
return false;
if (other.getClientMetadata() != null && other.getClientMetadata().equals(this.getClientMetadata()) == false)
return false;
if (other.getClientId() == null ^ this.getClientId() == null)
return false;
if (other.getClientId() != null && other.getClientId().equals(this.getClientId()) == false)
return false;
if (other.getAnalyticsMetadata() == null ^ this.getAnalyticsMetadata() == null)
return false;
if (other.getAnalyticsMetadata() != null && other.getAnalyticsMetadata().equals(this.getAnalyticsMetadata()) == false)
return false;
if (other.getUserContextData() == null ^ this.getUserContextData() == null)
return false;
if (other.getUserContextData() != null && other.getUserContextData().equals(this.getUserContextData()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAuthFlow() == null) ? 0 : getAuthFlow().hashCode());
hashCode = prime * hashCode + ((getAuthParameters() == null) ? 0 : getAuthParameters().hashCode());
hashCode = prime * hashCode + ((getClientMetadata() == null) ? 0 : getClientMetadata().hashCode());
hashCode = prime * hashCode + ((getClientId() == null) ? 0 : getClientId().hashCode());
hashCode = prime * hashCode + ((getAnalyticsMetadata() == null) ? 0 : getAnalyticsMetadata().hashCode());
hashCode = prime * hashCode + ((getUserContextData() == null) ? 0 : getUserContextData().hashCode());
return hashCode;
}
@Override
public InitiateAuthRequest clone() {
return (InitiateAuthRequest) super.clone();
}
}
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast/src/test/java/com/hazelcast/nio/tcp/TcpIpConnectionManager_ConnectionListenerTest.java | 2157 | package com.hazelcast.nio.tcp;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.ConnectionListener;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class TcpIpConnectionManager_ConnectionListenerTest extends TcpIpConnection_AbstractTest {
@Test(expected = NullPointerException.class)
public void addConnectionListener_whenNull() {
connManagerA.addConnectionListener(null);
}
@Test
public void whenConnectionAdded() throws Exception {
startAllConnectionManagers();
final ConnectionListener listener = mock(ConnectionListener.class);
connManagerA.addConnectionListener(listener);
final Connection c = connect(connManagerA, addressB);
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
listener.connectionAdded(c);
}
});
}
@Test
public void whenConnectionDestroyed() throws Exception {
startAllConnectionManagers();
final ConnectionListener listener = mock(ConnectionListener.class);
connManagerA.addConnectionListener(listener);
final Connection c = connect(connManagerA, addressB);
c.close(null, null);
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
listener.connectionRemoved(c);
}
});
}
@Test
public void whenConnectionManagerShutdown_thenListenersRemoved() {
startAllConnectionManagers();
ConnectionListener listener = mock(ConnectionListener.class);
connManagerA.addConnectionListener(listener);
connManagerA.shutdown();
assertEquals(0, connManagerA.connectionListeners.size());
}
}
| apache-2.0 |
wangsongpeng/jdk-src | src/main/java/org/omg/IOP/TaggedProfile.java | 719 | package org.omg.IOP;
/**
* org/omg/IOP/TaggedProfile.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON3/workspace/8-2-build-linux-amd64/jdk8u121/8372/corba/src/share/classes/org/omg/PortableInterceptor/IOP.idl
* Monday, December 12, 2016 4:37:46 PM PST
*/
public final class TaggedProfile implements org.omg.CORBA.portable.IDLEntity
{
/** The tag, represented as a profile id. */
public int tag = (int)0;
/** The associated profile data. */
public byte profile_data[] = null;
public TaggedProfile ()
{
} // ctor
public TaggedProfile (int _tag, byte[] _profile_data)
{
tag = _tag;
profile_data = _profile_data;
} // ctor
} // class TaggedProfile
| apache-2.0 |
sdliang1013/account-import | src/main/java/com/caul/modules/user/service/UserServiceImpl.java | 2744 | package com.caul.modules.user.service;
import cn.easybuild.core.dao.AppBaseDao;
import cn.easybuild.core.exceptions.InvalidOperationException;
import cn.easybuild.core.service.StringPojoAppBaseServiceImpl;
import cn.easybuild.pojo.DataSet;
import com.caul.modules.config.ApplicationConfig;
import com.caul.modules.user.User;
import com.caul.modules.user.UserQueryParam;
import com.caul.modules.user.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by BlueDream on 2016-03-20.
*/
@Service
public class UserServiceImpl extends StringPojoAppBaseServiceImpl<User>
implements UserService {
private UserDao userDao;
private ApplicationConfig applicationConfig;
private static int position = 0;
private static String code = null;
private StringBuilder sb = new StringBuilder();
@Autowired(required = false)
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Autowired(required = false)
public void setApplicationConfig(ApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
@Override
protected AppBaseDao<User, String> getDao() {
return userDao;
}
@Override
public User login(String username, String password) {
User user = userDao.getByUsername(username);
if (user == null) {
throw new RuntimeException("无效的用户名!");
}
if (!checkPwd(user.getPassword(), password)) {
throw new RuntimeException("密码错误!");
}
return user;
}
@Override
public String save(User entity) {
User user = userDao.getByUsername(entity.getUserName());
if (user != null) {
throw new InvalidOperationException("该账号已存在!");
}
return super.save(entity);
}
@Override
public DataSet<User> queryForManage(UserQueryParam queryParam) {
return userDao.queryForManage(queryParam);
}
private boolean checkPwd(String dbPwd, String inputPwd) {
return inputPwd.equals(resetPwd(dbPwd));
}
private String resetPwd(String dbPwd) {
sb.delete(0, sb.length());
sb.append(dbPwd.substring(0, getPosition())).append(
getCode()).append(dbPwd.substring(getPosition()));
return sb.toString();
}
public int getPosition() {
if (position == 0) {
position = applicationConfig.getEncryptPosition();
}
return position;
}
public String getCode() {
if (code == null) {
code = applicationConfig.getEncryptCode();
}
return code;
}
}
| apache-2.0 |
peridotperiod/isis | core/runtime/src/main/java/org/apache/isis/core/runtime/runner/opts/OptionHandlerNoSplash.java | 2269 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.core.runtime.runner.opts;
import static org.apache.isis.core.runtime.runner.Constants.NO_SPLASH_LONG_OPT;
import static org.apache.isis.core.runtime.runner.Constants.NO_SPLASH_OPT;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.isis.core.commons.config.IsisConfigurationBuilder;
import org.apache.isis.core.runtime.optionhandler.BootPrinter;
import org.apache.isis.core.runtime.optionhandler.OptionHandlerAbstract;
import org.apache.isis.core.runtime.system.SystemConstants;
public class OptionHandlerNoSplash extends OptionHandlerAbstract {
private boolean noSplash;
public OptionHandlerNoSplash() {
super();
}
@Override
public void addOption(final Options options) {
options.addOption(NO_SPLASH_OPT, NO_SPLASH_LONG_OPT, false, "don't show splash window");
}
@Override
public boolean handle(final CommandLine commandLine, final BootPrinter bootPrinter, final Options options) {
noSplash = commandLine.hasOption(NO_SPLASH_OPT);
return true;
}
@Override
public void primeConfigurationBuilder(final IsisConfigurationBuilder isisConfigurationBuilder) {
if (noSplash) {
isisConfigurationBuilder.add(SystemConstants.NOSPLASH_KEY, "true");
}
// configurationBuilder.add(SystemConstants.NOSPLASH_KEY, noSplash ?
// "true" : "false");
}
}
| apache-2.0 |
eturka/eturka | chapter_002/src/main/java/ru/job4j/chess/King.java | 823 | package ru.job4j.chess;
/**
* Class King.
*
* @author Ekaterina Turka (ekaterina2rka@gmail.com)
* @version 1
* @since 11.12.2017
*/
public class King extends Figure {
/**
* Create the figure on a board.
*
* @param position start position on a board
*/
public King(Cell position) {
super(position);
}
/**
* {@inheritDoc}
*/
@Override
public int countSteps(Cell dest) throws ImpossibleMoveException {
int x = Math.abs(dest.getX() - position.getX());
int y = Math.abs(dest.getY() - position.getY());
if (x > 1 || y > 1) {
throw new ImpossibleMoveException();
}
return 1;
}
/**
* {@inheritDoc}
*/
@Override
public Figure copy(Cell dest) {
return new King(dest);
}
}
| apache-2.0 |
unluonur/bosphorus | bosphorus-core/src/main/java/org/bosphorus/core/expression/aggregate/executor/math/AvgFloatExecutor.java | 1593 | /**
* Copyright (c) Onur Ünlü
*
* 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.
*
* The latest version of this file can be found at https://github.com/unluonur/bosphorus
*/
package org.bosphorus.core.expression.aggregate.executor.math;
import org.bosphorus.core.expression.aggregate.executor.IAggregateExecutor;
public class AvgFloatExecutor implements IAggregateExecutor<Number, Float> {
private AvgState<Double, Long> state;
public AvgFloatExecutor() {
this.state = new AvgState<Double, Long>();
this.reset();
}
@Override
public void execute(Number input) throws Exception {
state.sum += input.doubleValue();
state.count++;
}
@Override
public Float getValue() {
if(state.count != 0) {
Double d = state.sum / state.count;
return d.floatValue();
}
return null;
}
@Override
public void reset() {
state.sum = 0.0;
state.count = 0L;
}
@Override
public Object getState() {
return state;
}
@SuppressWarnings("unchecked")
@Override
public void setState(Object state) throws Exception {
this.state = (AvgState<Double, Long>)state;
}
}
| apache-2.0 |