code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
/***********************************************************************************************
*
* Copyright (C) 2016, IBL Software Engineering spol. s r. o.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************/
package com.iblsoft.iwxxm.webservice.ws.internal;
import com.googlecode.jsonrpc4j.JsonRpcParam;
import com.iblsoft.iwxxm.webservice.util.Log;
import com.iblsoft.iwxxm.webservice.validator.IwxxmValidator;
import com.iblsoft.iwxxm.webservice.validator.ValidationError;
import com.iblsoft.iwxxm.webservice.validator.ValidationResult;
import com.iblsoft.iwxxm.webservice.ws.IwxxmWebService;
import com.iblsoft.iwxxm.webservice.ws.messages.ValidationRequest;
import com.iblsoft.iwxxm.webservice.ws.messages.ValidationResponse;
import java.io.File;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Implementation class of IwxxmWebService interface.
*/
public class IwxxmWebServiceImpl implements IwxxmWebService {
private final IwxxmValidator iwxxmValidator;
public IwxxmWebServiceImpl(File validationCatalogFile, File validationRulesDir, String defaultIwxxmVersion) {
this.iwxxmValidator = new IwxxmValidator(validationCatalogFile, validationRulesDir, defaultIwxxmVersion);
}
@Override
public ValidationResponse validate(@JsonRpcParam("request") ValidationRequest request) {
Log.INSTANCE.debug("IwxxmWebService.validate request started");
checkRequestVersion(request.getRequestVersion());
ValidationResult validationResult = iwxxmValidator.validate(request.getIwxxmData(), request.getIwxxmVersion());
ValidationResponse.Builder responseBuilder = ValidationResponse.builder();
for (ValidationError ve : validationResult.getValidationErrors()) {
responseBuilder.addValidationError(ve.getError(), ve.getLineNumber(), ve.getColumnNumber());
}
Log.INSTANCE.debug("IwxxmWebService.validate request finished");
return responseBuilder.build();
}
private void checkRequestVersion(String requestVersion) {
checkArgument(requestVersion != null && requestVersion.equals("1.0"), "Unsupported request version.");
}
}
| iblsoft/iwxxm-validator | src/main/java/com/iblsoft/iwxxm/webservice/ws/internal/IwxxmWebServiceImpl.java | Java | apache-2.0 | 2,770 |
package org.jboss.resteasy.reactive.client.processor.beanparam;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.BEAN_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.COOKIE_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.FORM_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.HEADER_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.PATH_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.QUERY_PARAM;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import org.jboss.resteasy.reactive.common.processor.JandexUtil;
public class BeanParamParser {
public static List<Item> parse(ClassInfo beanParamClass, IndexView index) {
Set<ClassInfo> processedBeanParamClasses = Collections.newSetFromMap(new IdentityHashMap<>());
return parseInternal(beanParamClass, index, processedBeanParamClasses);
}
private static List<Item> parseInternal(ClassInfo beanParamClass, IndexView index,
Set<ClassInfo> processedBeanParamClasses) {
if (!processedBeanParamClasses.add(beanParamClass)) {
throw new IllegalArgumentException("Cycle detected in BeanParam annotations; already processed class "
+ beanParamClass.name());
}
try {
List<Item> resultList = new ArrayList<>();
// Parse class tree recursively
if (!JandexUtil.DOTNAME_OBJECT.equals(beanParamClass.superName())) {
resultList
.addAll(parseInternal(index.getClassByName(beanParamClass.superName()), index,
processedBeanParamClasses));
}
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, QUERY_PARAM,
(annotationValue, fieldInfo) -> new QueryParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()),
fieldInfo.type()),
(annotationValue, getterMethod) -> new QueryParamItem(annotationValue, new GetterExtractor(getterMethod),
getterMethod.returnType())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, BEAN_PARAM,
(annotationValue, fieldInfo) -> {
Type type = fieldInfo.type();
if (type.kind() == Type.Kind.CLASS) {
List<Item> subBeanParamItems = parseInternal(index.getClassByName(type.asClassType().name()), index,
processedBeanParamClasses);
return new BeanParamItem(subBeanParamItems,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()));
} else {
throw new IllegalArgumentException("BeanParam annotation used on a field that is not an object: "
+ beanParamClass.name() + "." + fieldInfo.name());
}
},
(annotationValue, getterMethod) -> {
Type returnType = getterMethod.returnType();
List<Item> items = parseInternal(index.getClassByName(returnType.name()), index,
processedBeanParamClasses);
return new BeanParamItem(items, new GetterExtractor(getterMethod));
}));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, COOKIE_PARAM,
(annotationValue, fieldInfo) -> new CookieParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(),
fieldInfo.declaringClass().name().toString()),
fieldInfo.type().name().toString()),
(annotationValue, getterMethod) -> new CookieParamItem(annotationValue,
new GetterExtractor(getterMethod), getterMethod.returnType().name().toString())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, HEADER_PARAM,
(annotationValue, fieldInfo) -> new HeaderParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()),
fieldInfo.type().name().toString()),
(annotationValue, getterMethod) -> new HeaderParamItem(annotationValue,
new GetterExtractor(getterMethod), getterMethod.returnType().name().toString())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, PATH_PARAM,
(annotationValue, fieldInfo) -> new PathParamItem(annotationValue, fieldInfo.type().name().toString(),
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())),
(annotationValue, getterMethod) -> new PathParamItem(annotationValue,
getterMethod.returnType().name().toString(),
new GetterExtractor(getterMethod))));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, FORM_PARAM,
(annotationValue, fieldInfo) -> new FormParamItem(annotationValue,
fieldInfo.type().name().toString(),
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())),
(annotationValue, getterMethod) -> new FormParamItem(annotationValue,
getterMethod.returnType().name().toString(),
new GetterExtractor(getterMethod))));
return resultList;
} finally {
processedBeanParamClasses.remove(beanParamClass);
}
}
private static MethodInfo getGetterMethod(ClassInfo beanParamClass, MethodInfo methodInfo) {
MethodInfo getter = null;
if (methodInfo.parameters().size() > 0) { // should be setter
// find the corresponding getter:
String setterName = methodInfo.name();
if (setterName.startsWith("set")) {
getter = beanParamClass.method(setterName.replace("^set", "^get"));
}
} else if (methodInfo.name().startsWith("get")) {
getter = methodInfo;
}
if (getter == null) {
throw new IllegalArgumentException(
"No getter corresponding to " + methodInfo.declaringClass().name() + "#" + methodInfo.name() + " found");
}
return getter;
}
private static <T extends Item> List<T> paramItemsForFieldsAndMethods(ClassInfo beanParamClass, DotName parameterType,
BiFunction<String, FieldInfo, T> fieldExtractor, BiFunction<String, MethodInfo, T> methodExtractor) {
return ParamTypeAnnotations.of(beanParamClass, parameterType).itemsForFieldsAndMethods(fieldExtractor, methodExtractor);
}
private BeanParamParser() {
}
private static class ParamTypeAnnotations {
private final ClassInfo beanParamClass;
private final List<AnnotationInstance> annotations;
private ParamTypeAnnotations(ClassInfo beanParamClass, DotName parameterType) {
this.beanParamClass = beanParamClass;
List<AnnotationInstance> relevantAnnotations = beanParamClass.annotations().get(parameterType);
this.annotations = relevantAnnotations == null
? Collections.emptyList()
: relevantAnnotations.stream().filter(this::isFieldOrMethodAnnotation).collect(Collectors.toList());
}
private static ParamTypeAnnotations of(ClassInfo beanParamClass, DotName parameterType) {
return new ParamTypeAnnotations(beanParamClass, parameterType);
}
private <T extends Item> List<T> itemsForFieldsAndMethods(BiFunction<String, FieldInfo, T> itemFromFieldExtractor,
BiFunction<String, MethodInfo, T> itemFromMethodExtractor) {
return annotations.stream()
.map(annotation -> toItem(annotation, itemFromFieldExtractor, itemFromMethodExtractor))
.collect(Collectors.toList());
}
private <T extends Item> T toItem(AnnotationInstance annotation,
BiFunction<String, FieldInfo, T> itemFromFieldExtractor,
BiFunction<String, MethodInfo, T> itemFromMethodExtractor) {
String annotationValue = annotation.value() == null ? null : annotation.value().asString();
return annotation.target().kind() == AnnotationTarget.Kind.FIELD
? itemFromFieldExtractor.apply(annotationValue, annotation.target().asField())
: itemFromMethodExtractor.apply(annotationValue,
getGetterMethod(beanParamClass, annotation.target().asMethod()));
}
private boolean isFieldOrMethodAnnotation(AnnotationInstance annotation) {
return annotation.target().kind() == AnnotationTarget.Kind.FIELD
|| annotation.target().kind() == AnnotationTarget.Kind.METHOD;
}
}
}
| quarkusio/quarkus | independent-projects/resteasy-reactive/client/processor/src/main/java/org/jboss/resteasy/reactive/client/processor/beanparam/BeanParamParser.java | Java | apache-2.0 | 9,998 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ui.actions;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.*;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.runtime.IPluginService;
import org.jkiss.dbeaver.ui.ActionUtils;
/**
* GlobalPropertyTester
*/
public class GlobalPropertyTester extends PropertyTester {
//static final Log log = LogFactory.get vLog(ObjectPropertyTester.class);
public static final String NAMESPACE = "org.jkiss.dbeaver.core.global";
public static final String PROP_STANDALONE = "standalone";
public static final String PROP_HAS_ACTIVE_PROJECT = "hasActiveProject";
public static final String PROP_HAS_MULTI_PROJECTS = "hasMultipleProjects";
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
switch (property) {
case PROP_HAS_MULTI_PROJECTS:
return DBWorkbench.getPlatform().getWorkspace().getProjects().size() > 1;
case PROP_HAS_ACTIVE_PROJECT:
return DBWorkbench.getPlatform().getWorkspace().getActiveProject() != null;
case PROP_STANDALONE:
return DBWorkbench.getPlatform().getApplication().isStandalone();
}
return false;
}
public static void firePropertyChange(String propName)
{
ActionUtils.evaluatePropertyState(NAMESPACE + "." + propName);
}
public static class ResourceListener implements IPluginService, IResourceChangeListener {
@Override
public void activateService() {
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
}
@Override
public void deactivateService() {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
}
@Override
public void resourceChanged(IResourceChangeEvent event) {
if (event.getType() == IResourceChangeEvent.POST_CHANGE) {
for (IResourceDelta childDelta : event.getDelta().getAffectedChildren()) {
if (childDelta.getResource() instanceof IProject) {
if (childDelta.getKind() == IResourceDelta.ADDED || childDelta.getKind() == IResourceDelta.REMOVED) {
firePropertyChange(GlobalPropertyTester.PROP_HAS_MULTI_PROJECTS);
}
}
}
}
}
}
}
| liuyuanyuan/dbeaver | plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/actions/GlobalPropertyTester.java | Java | apache-2.0 | 3,123 |
/*
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.customers.persistence;
import static org.mifos.application.meeting.util.helpers.MeetingType.CUSTOMER_MEETING;
import static org.mifos.application.meeting.util.helpers.RecurrenceType.WEEKLY;
import static org.mifos.framework.util.helpers.TestObjectFactory.EVERY_WEEK;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import junit.framework.Assert;
import org.mifos.accounts.business.AccountActionDateEntity;
import org.mifos.accounts.business.AccountBO;
import org.mifos.accounts.business.AccountFeesEntity;
import org.mifos.accounts.business.AccountStateEntity;
import org.mifos.accounts.business.AccountTestUtils;
import org.mifos.accounts.exceptions.AccountException;
import org.mifos.accounts.fees.business.AmountFeeBO;
import org.mifos.accounts.fees.business.FeeBO;
import org.mifos.accounts.fees.util.helpers.FeeCategory;
import org.mifos.accounts.loan.business.LoanBO;
import org.mifos.accounts.productdefinition.business.LoanOfferingBO;
import org.mifos.accounts.productdefinition.business.SavingsOfferingBO;
import org.mifos.accounts.productdefinition.util.helpers.RecommendedAmountUnit;
import org.mifos.accounts.savings.business.SavingsBO;
import org.mifos.accounts.util.helpers.AccountState;
import org.mifos.accounts.util.helpers.AccountStateFlag;
import org.mifos.accounts.util.helpers.AccountTypes;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.meeting.exceptions.MeetingException;
import org.mifos.application.meeting.persistence.MeetingPersistence;
import org.mifos.application.meeting.util.helpers.RecurrenceType;
import org.mifos.application.servicefacade.CollectionSheetCustomerDto;
import org.mifos.application.util.helpers.YesNoFlag;
import org.mifos.config.AccountingRulesConstants;
import org.mifos.config.ConfigurationManager;
import org.mifos.core.CurrencyMismatchException;
import org.mifos.customers.business.CustomerAccountBO;
import org.mifos.customers.business.CustomerBO;
import org.mifos.customers.business.CustomerBOTestUtils;
import org.mifos.customers.business.CustomerNoteEntity;
import org.mifos.customers.business.CustomerPerformanceHistoryView;
import org.mifos.customers.business.CustomerSearch;
import org.mifos.customers.business.CustomerStatusEntity;
import org.mifos.customers.business.CustomerView;
import org.mifos.customers.center.business.CenterBO;
import org.mifos.customers.checklist.business.CheckListBO;
import org.mifos.customers.checklist.business.CustomerCheckListBO;
import org.mifos.customers.checklist.util.helpers.CheckListConstants;
import org.mifos.customers.client.business.AttendanceType;
import org.mifos.customers.client.business.ClientBO;
import org.mifos.customers.client.util.helpers.ClientConstants;
import org.mifos.customers.group.BasicGroupInfo;
import org.mifos.customers.group.business.GroupBO;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.personnel.util.helpers.PersonnelConstants;
import org.mifos.customers.util.helpers.ChildrenStateType;
import org.mifos.customers.util.helpers.CustomerLevel;
import org.mifos.customers.util.helpers.CustomerStatus;
import org.mifos.customers.util.helpers.CustomerStatusFlag;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.hibernate.helper.QueryResult;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
import org.mifos.security.util.UserContext;
public class CustomerPersistenceIntegrationTest extends MifosIntegrationTestCase {
public CustomerPersistenceIntegrationTest() throws Exception {
super();
}
private MeetingBO meeting;
private CustomerBO center;
private ClientBO client;
private CustomerBO group2;
private CustomerBO group;
private AccountBO account;
private LoanBO groupAccount;
private LoanBO clientAccount;
private SavingsBO centerSavingsAccount;
private SavingsBO groupSavingsAccount;
private SavingsBO clientSavingsAccount;
private SavingsOfferingBO savingsOffering;
private final CustomerPersistence customerPersistence = new CustomerPersistence();
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
public void tearDown() throws Exception {
try {
TestObjectFactory.cleanUp(centerSavingsAccount);
TestObjectFactory.cleanUp(groupSavingsAccount);
TestObjectFactory.cleanUp(clientSavingsAccount);
TestObjectFactory.cleanUp(groupAccount);
TestObjectFactory.cleanUp(clientAccount);
TestObjectFactory.cleanUp(account);
TestObjectFactory.cleanUp(client);
TestObjectFactory.cleanUp(group2);
TestObjectFactory.cleanUp(group);
TestObjectFactory.cleanUp(center);
StaticHibernateUtil.closeSession();
} catch (Exception e) {
// Throwing from tearDown will tend to mask the real failure.
e.printStackTrace();
}
super.tearDown();
}
public void testGetTotalAmountForAllClientsOfGroupForSingleCurrency() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
AccountBO clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg", TestUtils.RUPEE);
AccountBO clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe", TestUtils.RUPEE);
Money amount = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(TestUtils.RUPEE, "600"), amount);
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
/*
* When trying to sum amounts across loans with different currencies, we should get an exception
*/
public void testGetTotalAmountForAllClientsOfGroupForMultipleCurrencies() throws Exception {
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
AccountBO clientAccount1;
AccountBO clientAccount2;
try {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg", TestUtils.RUPEE);
clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe", TestUtils.EURO);
try {
customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
fail("didn't get the expected CurrencyMismatchException");
} catch (CurrencyMismatchException e) {
// if we got here then we got the exception we were expecting
assertNotNull(e);
} catch (Exception e) {
fail("didn't get the expected CurrencyMismatchException");
}
} finally {
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
/*
* When trying to sum amounts across loans with different currencies, we should get an exception
*/
public void testGetTotalAmountForGroupForMultipleCurrencies() throws Exception {
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
GroupBO group1;
AccountBO account1;
AccountBO account2;
try {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
account1 = getLoanAccount(group1, meeting, "adsfdsfsd", "3saf", TestUtils.RUPEE);
account2 = getLoanAccount(group1, meeting, "adspp", "kkaf", TestUtils.EURO);
try {
customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING);
fail("didn't get the expected CurrencyMismatchException");
} catch (CurrencyMismatchException e) {
// if we got here then we got the exception we were expecting
assertNotNull(e);
} catch (Exception e) {
fail("didn't get the expected CurrencyMismatchException");
}
} finally {
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(group1);
}
public void testGetTotalAmountForGroup() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
AccountBO account1 = getLoanAccount(group1, meeting, "adsfdsfsd", "3saf");
AccountBO account2 = getLoanAccount(group1, meeting, "adspp", "kkaf");
Money amount = customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING);
Assert.assertEquals(new Money(getCurrency(), "600"), amount);
AccountBO account3 = getLoanAccountInActiveBadStanding(group1, meeting, "adsfdsfsd1", "4sa");
AccountBO account4 = getLoanAccountInActiveBadStanding(group1, meeting, "adspp2", "kaf5");
Money amount2 = customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_BAD_STANDING);
Assert.assertEquals(new Money(getCurrency(), "600"), amount2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(group1);
}
public void testGetTotalAmountForAllClientsOfGroup() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
AccountBO clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg");
AccountBO clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe");
Money amount = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(getCurrency(), "600"), amount);
clientAccount1.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "none");
clientAccount2.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "none");
TestObjectFactory.updateObject(clientAccount1);
TestObjectFactory.updateObject(clientAccount2);
StaticHibernateUtil.commitTransaction();
Money amount2 = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_BAD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(getCurrency(), "600"), amount2);
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
public void testGetAllBasicGroupInfo() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
GroupBO newGroup = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup", CustomerStatus.GROUP_HOLD, center);
GroupBO newGroup2 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup2", CustomerStatus.GROUP_CANCELLED,
center);
GroupBO newGroup3 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup3", CustomerStatus.GROUP_CLOSED, center);
GroupBO newGroup4 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup4", CustomerStatus.GROUP_PARTIAL, center);
GroupBO newGroup5 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup5", CustomerStatus.GROUP_PENDING, center);
List<BasicGroupInfo> groupInfos = customerPersistence.getAllBasicGroupInfo();
Assert.assertEquals(2, groupInfos.size());
Assert.assertEquals(group.getDisplayName(), groupInfos.get(0).getGroupName());
Assert.assertEquals(group.getSearchId(), groupInfos.get(0).getSearchId());
Assert.assertEquals(group.getOffice().getOfficeId(), groupInfos.get(0).getBranchId());
Assert.assertEquals(group.getCustomerId(), groupInfos.get(0).getGroupId());
Assert.assertEquals(newGroup.getDisplayName(), groupInfos.get(1).getGroupName());
Assert.assertEquals(newGroup.getSearchId(), groupInfos.get(1).getSearchId());
Assert.assertEquals(newGroup.getOffice().getOfficeId(), groupInfos.get(1).getBranchId());
Assert.assertEquals(newGroup.getCustomerId(), groupInfos.get(1).getGroupId());
TestObjectFactory.cleanUp(newGroup);
TestObjectFactory.cleanUp(newGroup2);
TestObjectFactory.cleanUp(newGroup3);
TestObjectFactory.cleanUp(newGroup4);
TestObjectFactory.cleanUp(newGroup5);
}
public void testCustomersUnderLO() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center_Active", meeting);
List<CustomerView> customers = customerPersistence.getActiveParentList(Short.valueOf("1"), CustomerLevel.CENTER
.getValue(), Short.valueOf("3"));
Assert.assertEquals(1, customers.size());
}
public void testActiveCustomersUnderParent() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
List<CustomerView> customers = customerPersistence.getChildrenForParent(center.getCustomerId(), center
.getSearchId(), center.getOffice().getOfficeId());
Assert.assertEquals(2, customers.size());
}
public void testOnHoldCustomersUnderParent() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
createCustomers(CustomerStatus.GROUP_HOLD, CustomerStatus.CLIENT_HOLD);
List<CustomerView> customers = customerPersistence.getChildrenForParent(center.getCustomerId(), center
.getSearchId(), center.getOffice().getOfficeId());
Assert.assertEquals(2, customers.size());
}
public void testGetLastMeetingDateForCustomer() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
account = getLoanAccount(group, meeting, "adsfdsfsd", "3saf");
// Date actionDate = new Date(2006,03,13);
Date meetingDate = customerPersistence.getLastMeetingDateForCustomer(center.getCustomerId());
Assert.assertEquals(new Date(getMeetingDates(meeting).getTime()).toString(), meetingDate.toString());
}
public void testGetChildernOtherThanClosed() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.OTHER_THAN_CLOSED);
Assert.assertEquals(new Integer("3").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().intValue() == client3.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetChildernActiveAndHold() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_PARTIAL, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_PENDING, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_HOLD, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.ACTIVE_AND_ONHOLD);
Assert.assertEquals(new Integer("2").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().intValue() == client.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
if (customer.getCustomerId().intValue() == client4.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetChildernOtherThanClosedAndCancelled() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.OTHER_THAN_CANCELLED_AND_CLOSED);
Assert.assertEquals(new Integer("2").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().equals(client4.getCustomerId())) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetAllChildern() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.ALL);
Assert.assertEquals(new Integer("4").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().equals(client2.getCustomerId())) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testRetrieveSavingsAccountForCustomer() throws Exception {
java.util.Date currentDate = new java.util.Date();
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd1", "S", currentDate, RecommendedAmountUnit.COMPLETE_GROUP);
UserContext user = new UserContext();
user.setId(PersonnelConstants.SYSTEM_USER);
account = TestObjectFactory.createSavingsAccount("000100000000020", group, AccountState.SAVINGS_ACTIVE,
currentDate, savingsOffering, user);
StaticHibernateUtil.closeSession();
List<SavingsBO> savingsList = customerPersistence.retrieveSavingsAccountForCustomer(group.getCustomerId());
Assert.assertEquals(1, savingsList.size());
account = savingsList.get(0);
group = account.getCustomer();
center = group.getParentCustomer();
}
public void testNumberOfMeetingsAttended() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.ABSENT);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.PRESENT);
Calendar currentDate = new GregorianCalendar();
currentDate.roll(Calendar.DATE, 1);
client.handleAttendance(new Date(currentDate.getTimeInMillis()), AttendanceType.LATE);
StaticHibernateUtil.commitTransaction();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.numberOfMeetings(true,
client.getCustomerId());
Assert.assertEquals(2, customerPerformanceHistoryView.getMeetingsAttended().intValue());
StaticHibernateUtil.closeSession();
}
public void testNumberOfMeetingsMissed() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.PRESENT);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.ABSENT);
Calendar currentDate = new GregorianCalendar();
currentDate.roll(Calendar.DATE, 1);
client.handleAttendance(new Date(currentDate.getTimeInMillis()), AttendanceType.APPROVED_LEAVE);
StaticHibernateUtil.commitTransaction();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.numberOfMeetings(false,
client.getCustomerId());
Assert.assertEquals(2, customerPerformanceHistoryView.getMeetingsMissed().intValue());
StaticHibernateUtil.closeSession();
}
public void testLastLoanAmount() throws PersistenceException, AccountException {
Date startDate = new Date(System.currentTimeMillis());
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(startDate, center.getCustomerMeeting()
.getMeeting());
LoanBO loanBO = TestObjectFactory.createLoanAccount("42423142341", client,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
account = (AccountBO) StaticHibernateUtil.getSessionTL().get(LoanBO.class, loanBO.getAccountId());
AccountStateEntity accountStateEntity = new AccountStateEntity(AccountState.LOAN_CLOSED_OBLIGATIONS_MET);
account.setUserContext(TestObjectFactory.getContext());
account.changeStatus(accountStateEntity.getId(), null, "");
TestObjectFactory.updateObject(account);
CustomerPersistence customerPersistence = new CustomerPersistence();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.getLastLoanAmount(client
.getCustomerId());
Assert.assertEquals("300.0", customerPerformanceHistoryView.getLastLoanAmount());
}
public void testFindBySystemId() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
GroupBO groupBO = (GroupBO) customerPersistence.findBySystemId(group.getGlobalCustNum());
Assert.assertEquals(groupBO.getDisplayName(), group.getDisplayName());
}
public void testGetBySystemId() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
GroupBO groupBO = (GroupBO) customerPersistence.findBySystemId(group.getGlobalCustNum(), group
.getCustomerLevel().getId());
Assert.assertEquals(groupBO.getDisplayName(), group.getDisplayName());
}
public void testOptionalCustomerStates() throws Exception {
Assert.assertEquals(Integer.valueOf(0).intValue(), customerPersistence.getCustomerStates(Short.valueOf("0"))
.size());
}
public void testCustomerStatesInUse() throws Exception {
Assert.assertEquals(Integer.valueOf(14).intValue(), customerPersistence.getCustomerStates(Short.valueOf("1"))
.size());
}
public void testGetCustomersWithUpdatedMeetings() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
CustomerBOTestUtils.setUpdatedFlag(group.getCustomerMeeting(), YesNoFlag.YES.getValue());
TestObjectFactory.updateObject(group);
List<Integer> customerIds = customerPersistence.getCustomersWithUpdatedMeetings();
Assert.assertEquals(1, customerIds.size());
}
public void testRetrieveAllLoanAccountUnderCustomer() throws PersistenceException {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_ACTIVE, group1);
account = getLoanAccount(group, meeting, "cdfggdfs", "1qdd");
AccountBO account1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg");
AccountBO account2 = getLoanAccount(client2, meeting, "fasdfdsfasdf", "1qwe");
AccountBO account3 = getLoanAccount(client3, meeting, "fdsgdfgfd", "543g");
AccountBO account4 = getLoanAccount(group1, meeting, "fasdf23", "3fds");
CustomerBOTestUtils.setCustomerStatus(client2, new CustomerStatusEntity(CustomerStatus.CLIENT_CLOSED));
TestObjectFactory.updateObject(client2);
client2 = TestObjectFactory.getClient(client2.getCustomerId());
CustomerBOTestUtils.setCustomerStatus(client3, new CustomerStatusEntity(CustomerStatus.CLIENT_CANCELLED));
TestObjectFactory.updateObject(client3);
client3 = TestObjectFactory.getClient(client3.getCustomerId());
List<AccountBO> loansForCenter = customerPersistence.retrieveAccountsUnderCustomer(center.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(3, loansForCenter.size());
List<AccountBO> loansForGroup = customerPersistence.retrieveAccountsUnderCustomer(group.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(3, loansForGroup.size());
List<AccountBO> loansForClient = customerPersistence.retrieveAccountsUnderCustomer(client.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(1, loansForClient.size());
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testRetrieveAllSavingsAccountUnderCustomer() throws Exception {
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("new_center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
account = getSavingsAccount(center, "Savings Prd1", "Abc1");
AccountBO account1 = getSavingsAccount(client, "Savings Prd2", "Abc2");
AccountBO account2 = getSavingsAccount(client2, "Savings Prd3", "Abc3");
AccountBO account3 = getSavingsAccount(client3, "Savings Prd4", "Abc4");
AccountBO account4 = getSavingsAccount(group1, "Savings Prd5", "Abc5");
AccountBO account5 = getSavingsAccount(group, "Savings Prd6", "Abc6");
AccountBO account6 = getSavingsAccount(center1, "Savings Prd7", "Abc7");
List<AccountBO> savingsForCenter = customerPersistence.retrieveAccountsUnderCustomer(center.getSearchId(),
Short.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(4, savingsForCenter.size());
List<AccountBO> savingsForGroup = customerPersistence.retrieveAccountsUnderCustomer(group.getSearchId(), Short
.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(3, savingsForGroup.size());
List<AccountBO> savingsForClient = customerPersistence.retrieveAccountsUnderCustomer(client.getSearchId(),
Short.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(1, savingsForClient.size());
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(account5);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(account6);
TestObjectFactory.cleanUp(center1);
}
public void testGetAllChildrenForParent() throws NumberFormatException, PersistenceException {
center = createCenter("Center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center11");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<CustomerBO> customerList1 = customerPersistence.getAllChildrenForParent(center.getSearchId(), Short
.valueOf("3"), CustomerLevel.CENTER.getValue());
Assert.assertEquals(2, customerList1.size());
List<CustomerBO> customerList2 = customerPersistence.getAllChildrenForParent(center.getSearchId(), Short
.valueOf("3"), CustomerLevel.GROUP.getValue());
Assert.assertEquals(1, customerList2.size());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetChildrenForParent() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<Integer> customerIds = customerPersistence.getChildrenForParent(center.getSearchId(), Short.valueOf("3"));
Assert.assertEquals(3, customerIds.size());
CustomerBO customer = TestObjectFactory.getCustomer(customerIds.get(0));
Assert.assertEquals("Group", customer.getDisplayName());
customer = TestObjectFactory.getCustomer(customerIds.get(1));
Assert.assertEquals("client1", customer.getDisplayName());
customer = TestObjectFactory.getCustomer(customerIds.get(2));
Assert.assertEquals("client2", customer.getDisplayName());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetCustomers() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center11");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<Integer> customerIds = customerPersistence.getCustomers(CustomerLevel.CENTER.getValue());
Assert.assertEquals(2, customerIds.size());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetCustomerChecklist() throws NumberFormatException, SystemException, ApplicationException,
Exception {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
CustomerCheckListBO checklistCenter = TestObjectFactory.createCustomerChecklist(center.getCustomerLevel()
.getId(), center.getCustomerStatus().getId(), CheckListConstants.STATUS_ACTIVE);
CustomerCheckListBO checklistClient = TestObjectFactory.createCustomerChecklist(client.getCustomerLevel()
.getId(), client.getCustomerStatus().getId(), CheckListConstants.STATUS_INACTIVE);
CustomerCheckListBO checklistGroup = TestObjectFactory.createCustomerChecklist(
group.getCustomerLevel().getId(), group.getCustomerStatus().getId(), CheckListConstants.STATUS_ACTIVE);
StaticHibernateUtil.closeSession();
Assert.assertEquals(1, customerPersistence.getStatusChecklist(center.getCustomerStatus().getId(),
center.getCustomerLevel().getId()).size());
client = (ClientBO) StaticHibernateUtil.getSessionTL().get(ClientBO.class,
Integer.valueOf(client.getCustomerId()));
group = (GroupBO) StaticHibernateUtil.getSessionTL().get(GroupBO.class, Integer.valueOf(group.getCustomerId()));
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
Integer.valueOf(center.getCustomerId()));
checklistCenter = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistCenter.getChecklistId()));
checklistClient = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistClient.getChecklistId()));
checklistGroup = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistGroup.getChecklistId()));
TestObjectFactory.cleanUp(checklistCenter);
TestObjectFactory.cleanUp(checklistClient);
TestObjectFactory.cleanUp(checklistGroup);
}
public void testRetrieveAllCustomerStatusList() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter();
Assert.assertEquals(2, customerPersistence.retrieveAllCustomerStatusList(center.getCustomerLevel().getId())
.size());
}
public void testCustomerCountByOffice() throws Exception {
int count = customerPersistence.getCustomerCountForOffice(CustomerLevel.CENTER, Short.valueOf("3"));
Assert.assertEquals(0, count);
center = createCenter();
count = customerPersistence.getCustomerCountForOffice(CustomerLevel.CENTER, Short.valueOf("3"));
Assert.assertEquals(1, count);
}
public void testGetAllCustomerNotes() throws Exception {
center = createCenter();
center.addCustomerNotes(TestObjectFactory.getCustomerNote("Test Note", center));
TestObjectFactory.updateObject(center);
Assert.assertEquals(1, customerPersistence.getAllCustomerNotes(center.getCustomerId()).getSize());
for (CustomerNoteEntity note : center.getCustomerNotes()) {
Assert.assertEquals("Test Note", note.getComment());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), note.getPersonnel().getPersonnelId());
}
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
Integer.valueOf(center.getCustomerId()));
}
public void testGetAllCustomerNotesWithZeroNotes() throws Exception {
center = createCenter();
Assert.assertEquals(0, customerPersistence.getAllCustomerNotes(center.getCustomerId()).getSize());
Assert.assertEquals(0, center.getCustomerNotes().size());
}
public void testGetFormedByPersonnel() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter();
Assert.assertEquals(1, customerPersistence.getFormedByPersonnel(ClientConstants.LOAN_OFFICER_LEVEL,
center.getOffice().getOfficeId()).size());
}
public void testGetAllClosedAccounts() throws Exception {
getCustomer();
groupAccount.changeStatus(AccountState.LOAN_CANCELLED.getValue(), AccountStateFlag.LOAN_WITHDRAW.getValue(),
"WITHDRAW LOAN ACCOUNT");
clientAccount.changeStatus(AccountState.LOAN_CLOSED_WRITTEN_OFF.getValue(), null, "WITHDRAW LOAN ACCOUNT");
clientSavingsAccount.changeStatus(AccountState.SAVINGS_CANCELLED.getValue(), AccountStateFlag.SAVINGS_REJECTED
.getValue(), "WITHDRAW LOAN ACCOUNT");
TestObjectFactory.updateObject(groupAccount);
TestObjectFactory.updateObject(clientAccount);
TestObjectFactory.updateObject(clientSavingsAccount);
StaticHibernateUtil.commitTransaction();
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(group.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.SAVINGS_ACCOUNT.getValue()).size());
}
public void testGetAllClosedAccountsWhenNoAccountsClosed() throws Exception {
getCustomer();
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(group.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.SAVINGS_ACCOUNT.getValue()).size());
}
public void testGetLOForCustomer() throws PersistenceException {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Short LO = customerPersistence.getLoanOfficerForCustomer(center.getCustomerId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), LO);
}
public void testUpdateLOsForAllChildren() {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Assert.assertEquals(center.getPersonnel().getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), client.getPersonnel().getPersonnelId());
StaticHibernateUtil.startTransaction();
PersonnelBO newLO = TestObjectFactory.getPersonnel(Short.valueOf("2"));
new CustomerPersistence().updateLOsForAllChildren(newLO.getPersonnelId(), center.getSearchId(), center
.getOffice().getOfficeId());
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
center = TestObjectFactory.getCenter(center.getCustomerId());
group = TestObjectFactory.getGroup(group.getCustomerId());
client = TestObjectFactory.getClient(client.getCustomerId());
Assert.assertEquals(newLO.getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(newLO.getPersonnelId(), client.getPersonnel().getPersonnelId());
}
public void testUpdateLOsForAllChildrenAccounts() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Assert.assertEquals(center.getPersonnel().getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), client.getPersonnel().getPersonnelId());
StaticHibernateUtil.startTransaction();
PersonnelBO newLO = TestObjectFactory.getPersonnel(Short.valueOf("2"));
new CustomerPersistence().updateLOsForAllChildrenAccounts(newLO.getPersonnelId(), center.getSearchId(), center
.getOffice().getOfficeId());
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
for (AccountBO account : client.getAccounts()) {
Assert.assertEquals(newLO.getPersonnelId(), account.getPersonnel().getPersonnelId());
}
}
public void testCustomerDeleteMeeting() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
client = TestObjectFactory.createClient("myClient", meeting, CustomerStatus.CLIENT_PENDING);
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
customerPersistence.deleteCustomerMeeting(client);
CustomerBOTestUtils.setCustomerMeeting(client, null);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
Assert.assertNull(client.getCustomerMeeting());
}
public void testDeleteMeeting() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
StaticHibernateUtil.closeSession();
meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
customerPersistence.deleteMeeting(meeting);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
Assert.assertNull(meeting);
}
public void testSearchWithOfficeId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("C", Short.valueOf("3"), Short.valueOf("1"), Short
.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testSearchWithoutOfficeId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("C", Short.valueOf("0"), Short.valueOf("1"), Short
.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testSearchWithGlobalNo() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchWithGovernmentId() throws Exception {
createCustomersWithGovernmentId(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("76346793216", Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
@SuppressWarnings("unchecked")
public void testSearchWithCancelLoanAccounts() throws Exception {
groupAccount = getLoanAccount();
groupAccount.changeStatus(AccountState.LOAN_CANCELLED.getValue(), AccountStateFlag.LOAN_WITHDRAW.getValue(),
"WITHDRAW LOAN ACCOUNT");
TestObjectFactory.updateObject(groupAccount);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
List results = queryResult.get(0, 10);
Assert.assertEquals(1, results.size());
CustomerSearch customerSearch = (CustomerSearch) results.get(0);
Assert.assertEquals(0, customerSearch.getLoanGlobalAccountNum().size());
}
public void testSearchWithAccountGlobalNo() throws Exception {
getCustomer();
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search(groupAccount.getGlobalAccountNum(), Short
.valueOf("3"), Short.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchGropAndClient() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("C", Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchGropAndClientForLoNoResults() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting, Short.valueOf("3"), Short.valueOf("3"));
group = TestObjectFactory.createGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, "1234", true,
new java.util.Date(), null, null, null, Short.valueOf("3"), center);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("C", Short.valueOf("3"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(0, queryResult.getSize());
Assert.assertEquals(0, queryResult.get(0, 10).size());
}
public void testSearchGropAndClientForLo() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting, Short.valueOf("3"), Short.valueOf("3"));
group = TestObjectFactory.createGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, "1234", true,
new java.util.Date(), null, null, null, Short.valueOf("3"), center);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("G", Short.valueOf("3"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchCustForSavings() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchCustForSavings("C", Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testGetCustomerAccountsForFee() throws Exception {
groupAccount = getLoanAccount();
FeeBO periodicFee = TestObjectFactory.createPeriodicAmountFee("ClientPeridoicFee", FeeCategory.CENTER, "5",
RecurrenceType.WEEKLY, Short.valueOf("1"));
AccountFeesEntity accountFee = new AccountFeesEntity(center.getCustomerAccount(), periodicFee,
((AmountFeeBO) periodicFee).getFeeAmount().getAmountDoubleValue());
CustomerAccountBO customerAccount = center.getCustomerAccount();
AccountTestUtils.addAccountFees(accountFee, customerAccount);
TestObjectFactory.updateObject(customerAccount);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
// check for the account fee
List<AccountBO> accountList = new CustomerPersistence().getCustomerAccountsForFee(periodicFee.getFeeId());
Assert.assertNotNull(accountList);
Assert.assertEquals(1, accountList.size());
Assert.assertTrue(accountList.get(0) instanceof CustomerAccountBO);
// get all objects again
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
}
public void testRetrieveCustomerAccountActionDetails() throws Exception {
center = createCenter();
Assert.assertNotNull(center.getCustomerAccount());
List<AccountActionDateEntity> actionDates = new CustomerPersistence().retrieveCustomerAccountActionDetails(
center.getCustomerAccount().getAccountId(), new java.sql.Date(System.currentTimeMillis()));
Assert.assertEquals("The size of the due insallments is ", actionDates.size(), 1);
}
public void testGetActiveCentersUnderUser() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("center", meeting, Short.valueOf("1"), Short.valueOf("1"));
PersonnelBO personnel = TestObjectFactory.getPersonnel(Short.valueOf("1"));
List<CustomerBO> customers = new CustomerPersistence().getActiveCentersUnderUser(personnel);
Assert.assertNotNull(customers);
Assert.assertEquals(1, customers.size());
}
public void testgetGroupsUnderUser() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("center", meeting, Short.valueOf("1"), Short.valueOf("1"));
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
group2 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group33", CustomerStatus.GROUP_CANCELLED, center);
PersonnelBO personnel = TestObjectFactory.getPersonnel(Short.valueOf("1"));
List<CustomerBO> customers = new CustomerPersistence().getGroupsUnderUser(personnel);
Assert.assertNotNull(customers);
Assert.assertEquals(1, customers.size());
}
@SuppressWarnings("unchecked")
public void testSearchForActiveInBadStandingLoanAccount() throws Exception {
groupAccount = getLoanAccount();
groupAccount.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "Changing to badStanding");
TestObjectFactory.updateObject(groupAccount);
StaticHibernateUtil.closeSession();
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
List results = queryResult.get(0, 10);
Assert.assertEquals(1, results.size());
CustomerSearch customerSearch = (CustomerSearch) results.get(0);
Assert.assertEquals(1, customerSearch.getLoanGlobalAccountNum().size());
}
public void testGetCustomersByLevelId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
List<CustomerBO> client = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("1"));
Assert.assertNotNull(client);
Assert.assertEquals(1, client.size());
List<CustomerBO> group = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("2"));
Assert.assertNotNull(group);
Assert.assertEquals(1, group.size());
List<CustomerBO> center = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("3"));
Assert.assertNotNull(center);
Assert.assertEquals(1, center.size());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveCenter() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
verifyCustomerLoaded(center.getCustomerId(), center.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnInactiveCenter() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Inactive Center", meeting);
center.changeStatus(CustomerStatus.CENTER_INACTIVE, CustomerStatusFlag.GROUP_CANCEL_BLACKLISTED, "Made Inactive");
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class, center.getCustomerId());
verifyCustomerNotLoaded(center.getCustomerId(), center.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
verifyCustomerLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsHoldGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Hold Group", CustomerStatus.GROUP_HOLD,
center);
verifyCustomerLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnClosedGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Closed Group", CustomerStatus.GROUP_CLOSED,
center);
verifyCustomerNotLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Active Client", CustomerStatus.CLIENT_ACTIVE, group);
verifyCustomerLoaded(client.getCustomerId(), client.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsHoldClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Hold Client", CustomerStatus.CLIENT_HOLD, group);
verifyCustomerLoaded(client.getCustomerId(), client.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnClosedClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Closed Client", CustomerStatus.CLIENT_CLOSED, group);
verifyCustomerNotLoaded(client.getCustomerId(), client.getDisplayName());
}
private void verifyCustomerLoaded(Integer customerId, String customerName) {
CollectionSheetCustomerDto collectionSheetCustomerDto = customerPersistence
.findCustomerWithNoAssocationsLoaded(customerId);
Assert.assertNotNull(customerName + " was not returned", collectionSheetCustomerDto);
Assert.assertEquals(collectionSheetCustomerDto.getCustomerId(), customerId);
}
private void verifyCustomerNotLoaded(Integer customerId, String customerName) {
CollectionSheetCustomerDto collectionSheetCustomerDto = customerPersistence
.findCustomerWithNoAssocationsLoaded(customerId);
Assert.assertNull(customerName + " was returned", collectionSheetCustomerDto);
}
private AccountBO getSavingsAccount(final CustomerBO customer, final String prdOfferingname, final String shortName)
throws Exception {
Date startDate = new Date(System.currentTimeMillis());
SavingsOfferingBO savingsOffering = TestObjectFactory.createSavingsProduct(prdOfferingname, shortName,
startDate, RecommendedAmountUnit.COMPLETE_GROUP);
return TestObjectFactory.createSavingsAccount("432434", customer, Short.valueOf("16"), startDate,
savingsOffering);
}
private void getCustomer() throws Exception {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering1 = TestObjectFactory.createLoanOffering("Loanwer", "43fs", startDate, meeting);
LoanOfferingBO loanOffering2 = TestObjectFactory.createLoanOffering("Loancd123", "vfr", startDate, meeting);
groupAccount = TestObjectFactory.createLoanAccount("42423142341", group,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering1);
clientAccount = TestObjectFactory.createLoanAccount("3243", client, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering2);
MeetingBO meetingIntCalc = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
MeetingBO meetingIntPost = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
SavingsOfferingBO savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd12", "abc1", startDate,
RecommendedAmountUnit.COMPLETE_GROUP, meetingIntCalc, meetingIntPost);
SavingsOfferingBO savingsOffering1 = TestObjectFactory.createSavingsProduct("SavingPrd11", "abc2", startDate,
RecommendedAmountUnit.COMPLETE_GROUP, meetingIntCalc, meetingIntPost);
centerSavingsAccount = TestObjectFactory.createSavingsAccount("432434", center, Short.valueOf("16"), startDate,
savingsOffering);
clientSavingsAccount = TestObjectFactory.createSavingsAccount("432434", client, Short.valueOf("16"), startDate,
savingsOffering1);
}
private void createCustomers(final CustomerStatus groupStatus, final CustomerStatus clientStatus) {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", groupStatus, center);
client = TestObjectFactory.createClient("Client", clientStatus, group);
}
private void createCustomersWithGovernmentId(final CustomerStatus groupStatus, final CustomerStatus clientStatus) {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", groupStatus, center);
client = TestObjectFactory.createClient("Client", clientStatus, group, TestObjectFactory.getFees(), "76346793216", new java.util.Date(1222333444000L));
}
private static java.util.Date getMeetingDates(final MeetingBO meeting) {
List<java.util.Date> dates = new ArrayList<java.util.Date>();
try {
dates = meeting.getAllDates(new java.util.Date(System.currentTimeMillis()));
} catch (MeetingException e) {
e.printStackTrace();
}
return dates.get(dates.size() - 1);
}
private CenterBO createCenter() {
return createCenter("Center_Active_test");
}
private CenterBO createCenter(final String name) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
return TestObjectFactory.createWeeklyFeeCenter(name, meeting);
}
private LoanBO getLoanAccount() {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccount(final CustomerBO group, final MeetingBO meeting, final String offeringName,
final String shortName) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccount(final CustomerBO group, final MeetingBO meeting, final String offeringName,
final String shortName, MifosCurrency currency) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting, currency);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccountInActiveBadStanding(final CustomerBO group, final MeetingBO meeting,
final String offeringName, final String shortName) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting);
return TestObjectFactory.createLoanAccount("42423141111", group, AccountState.LOAN_ACTIVE_IN_BAD_STANDING,
startDate, loanOffering);
}
}
| mifos/1.5.x | application/src/test/java/org/mifos/customers/persistence/CustomerPersistenceIntegrationTest.java | Java | apache-2.0 | 73,142 |
/**
*
* @author Alex Karpov (mailto:karpov_aleksey@mail.ru)
* @version $Id$
* @since 0.1
*/
package ru.job4j.max; | AlekseyKarpov/akarpov | chapter_001/src/test/java/ru/job4j/max/package-info.java | Java | apache-2.0 | 113 |
package com.capgemini.resilience.employer.service;
public interface ErrorSimulationService {
void generateErrorDependingOnErrorPossibility();
}
| microservices-summit-2016/resilience-demo | employer-service/src/main/java/com/capgemini/resilience/employer/service/ErrorSimulationService.java | Java | apache-2.0 | 150 |
package com.box.boxjavalibv2.responseparsers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.Assert;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import com.box.boxjavalibv2.dao.BoxPreview;
import com.box.restclientv2.exceptions.BoxRestException;
import com.box.restclientv2.responses.DefaultBoxResponse;
public class PreviewResponseParserTest {
private final static String PREVIEW_MOCK_CONTENT = "arbitrary string";
private final static String LINK_VALUE = "<https://api.box.com/2.0/files/5000369410/preview.png?page=%d>; rel=\"first\", <https://api.box.com/2.0/files/5000369410/preview.png?page=%d>; rel=\"last\"";
private final static String LINK_NAME = "Link";
private final static int firstPage = 1;
private final static int lastPage = 2;
private final static double length = 213;
private BoxPreview preview;
private DefaultBoxResponse boxResponse;
private HttpResponse response;
private HttpEntity entity;
private InputStream inputStream;
private Header header;
@Before
public void setUp() {
preview = new BoxPreview();
preview.setFirstPage(firstPage);
preview.setLastPage(lastPage);
boxResponse = EasyMock.createMock(DefaultBoxResponse.class);
response = EasyMock.createMock(BasicHttpResponse.class);
entity = EasyMock.createMock(StringEntity.class);
header = new BasicHeader("Link", String.format(LINK_VALUE, firstPage, lastPage));
}
@Test
public void testCanParsePreview() throws IllegalStateException, IOException, BoxRestException {
EasyMock.reset(boxResponse, response, entity);
inputStream = new ByteArrayInputStream(PREVIEW_MOCK_CONTENT.getBytes());
EasyMock.expect(boxResponse.getHttpResponse()).andReturn(response);
EasyMock.expect(boxResponse.getContentLength()).andReturn(length);
EasyMock.expect(response.getEntity()).andReturn(entity);
EasyMock.expect(entity.getContent()).andReturn(inputStream);
EasyMock.expect(boxResponse.getHttpResponse()).andReturn(response);
EasyMock.expect(response.getFirstHeader("Link")).andReturn(header);
EasyMock.replay(boxResponse, response, entity);
PreviewResponseParser parser = new PreviewResponseParser();
Object object = parser.parse(boxResponse);
Assert.assertEquals(BoxPreview.class, object.getClass());
BoxPreview parsed = (BoxPreview) object;
Assert.assertEquals(length, parsed.getContentLength());
Assert.assertEquals(firstPage, parsed.getFirstPage().intValue());
Assert.assertEquals(lastPage, parsed.getLastPage().intValue());
Assert.assertEquals(PREVIEW_MOCK_CONTENT, IOUtils.toString(parsed.getContent()));
EasyMock.verify(boxResponse, response, entity);
}
}
| shelsonjava/box-java-sdk-v2 | BoxJavaLibraryV2/tst/com/box/boxjavalibv2/responseparsers/PreviewResponseParserTest.java | Java | apache-2.0 | 3,189 |
// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git.receive;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.reviewdb.client.Change;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/**
* Keeps track of the change IDs thus far updated by ReceiveCommit.
*
* <p>This class is thread-safe.
*/
public class ResultChangeIds {
public enum Key {
CREATED,
REPLACED,
AUTOCLOSED,
}
private boolean isMagicPush;
private final Map<Key, List<Change.Id>> ids;
ResultChangeIds() {
ids = new EnumMap<>(Key.class);
for (Key k : Key.values()) {
ids.put(k, new ArrayList<>());
}
}
/** Record a change ID update as having completed. Thread-safe. */
public synchronized void add(Key key, Change.Id id) {
ids.get(key).add(id);
}
/** Indicate that the ReceiveCommits call involved a magic branch. */
public synchronized void setMagicPush(boolean magic) {
isMagicPush = magic;
}
public synchronized boolean isMagicPush() {
return isMagicPush;
}
/**
* Returns change IDs of the given type for which the BatchUpdate succeeded, or empty list if
* there are none. Thread-safe.
*/
public synchronized List<Change.Id> get(Key key) {
return ImmutableList.copyOf(ids.get(key));
}
}
| qtproject/qtqa-gerrit | java/com/google/gerrit/server/git/receive/ResultChangeIds.java | Java | apache-2.0 | 1,920 |
package com.veneweather.android;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.veneweather.android.db.City;
import com.veneweather.android.db.County;
import com.veneweather.android.db.Province;
import com.veneweather.android.util.HttpUtil;
import com.veneweather.android.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by lenovo on 2017/4/10.
*/
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button btn_back;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中的省份
*/
private Province selectedProvince;
/**
* 选中的城市
*/
private City selectedCity;
/**
* 当前选中的级别
*/
private int currentLevel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area, container, false);
titleText = (TextView) view.findViewById(R.id.title_text);
btn_back = (Button) view.findViewById(R.id.back_button);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String weatherId = countyList.get(position).getWeatherId();
if (getActivity() instanceof MainActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id", weatherId);
startActivity(intent);
getActivity().finish();
} else if (getActivity() instanceof WeatherActivity) {
WeatherActivity activity = (WeatherActivity) getActivity();
activity.drawerLayout.closeDrawers();
activity.swipeRefresh.setRefreshing(true);
activity.requestWeather(weatherId);
}
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else if (currentLevel == LEVEL_COUNTY) {
queryCities();
}
}
});
queryProvinces();
}
/**
* 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryProvinces() {
titleText.setText("中国");
btn_back.setVisibility(View.GONE);
provinceList = DataSupport.findAll(Province.class);
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
} else {
String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
/**
* 查询选中省内所有市,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCities() {
titleText.setText(selectedProvince.getProvinceName());
btn_back.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 查询选中市内所有县,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
btn_back.setVisibility(View.VISIBLE);
countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCitycode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address, "county");
}
}
/**
* 根据传入的地址和类型从服务器上查询省市县数据
*/
private void queryFromServer(String address, final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(responseText);
} else if ("city".equals(type)) {
result = Utility.handleCityResponse(responseText, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountyResponse(responseText, selectedCity.getId());
}
if (result) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
} else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
@Override
public void onFailure(Call call, IOException e) {
// 通过runOnUiThread()方法回到主线程处理逻辑
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
| Ackerm-Zed/veneweather | app/src/main/java/com/veneweather/android/ChooseAreaFragment.java | Java | apache-2.0 | 9,584 |
package operationExtensibility.tests;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import operationExtensibility.*;
public class TestEvaluator {
private static Visitor<Integer> v;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
v = new Evaluator();
}
@Test
public void testLit() {
Lit x = new Lit();
x.setInfo(42);
assertEquals("evaluate a literal", 42, x.accept(v));
}
@Test
public void testAdd() {
Add x = new Add();
Lit y = new Lit();
y.setInfo(1);
x.setLeft(y);
y = new Lit();
y.setInfo(2);
x.setRight(y);
assertEquals("evaluate addition", 3, x.accept(v));
}
}
| egaburov/funstuff | Haskell/tytag/xproblem_src/samples/expressions/Java/operationExtensibility/tests/TestEvaluator.java | Java | apache-2.0 | 719 |
/*
* 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.ivy.core.pack;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ivy.util.FileUtil;
/**
* Packaging which handle OSGi bundles with inner packed jar
*/
public class OsgiBundlePacking extends ZipPacking {
private static final String[] NAMES = {"bundle"};
@Override
public String[] getNames() {
return NAMES;
}
@Override
protected void writeFile(InputStream zip, File f) throws IOException {
// XXX maybe we should only unpack file listed by the 'Bundle-ClassPath' MANIFEST header ?
if (f.getName().endsWith(".jar.pack.gz")) {
zip = FileUtil.unwrapPack200(zip);
f = new File(f.getParentFile(), f.getName().substring(0, f.getName().length() - 8));
}
super.writeFile(zip, f);
}
}
| jaikiran/ant-ivy | src/java/org/apache/ivy/core/pack/OsgiBundlePacking.java | Java | apache-2.0 | 1,656 |
package fr.openwide.core.wicket.more.markup.html.feedback;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
public abstract class AbstractFeedbackPanel extends Panel {
private static final long serialVersionUID = 8440891357292721078L;
private static final int[] ERROR_MESSAGE_LEVELS = {
FeedbackMessage.FATAL,
FeedbackMessage.ERROR,
FeedbackMessage.WARNING,
FeedbackMessage.SUCCESS,
FeedbackMessage.INFO,
FeedbackMessage.DEBUG,
FeedbackMessage.UNDEFINED
};
private static final String[] ERROR_MESSAGE_LEVEL_NAMES = {
"FATAL",
"ERROR",
"WARNING",
"SUCCESS",
"INFO",
"DEBUG",
"UNDEFINED"
};
private List<FeedbackPanel> feedbackPanels = new ArrayList<FeedbackPanel>();
public AbstractFeedbackPanel(String id, MarkupContainer container) {
super(id);
int i = 0;
for(int level: ERROR_MESSAGE_LEVELS) {
FeedbackPanel f = getFeedbackPanel(ERROR_MESSAGE_LEVEL_NAMES[i] + "feedbackPanel", level, container);
feedbackPanels.add(f);
add(f);
i++;
}
}
public abstract FeedbackPanel getFeedbackPanel(String id, int level, MarkupContainer container);
}
| openwide-java/owsi-core-parent | owsi-core/owsi-core-components/owsi-core-component-wicket-more/src/main/java/fr/openwide/core/wicket/more/markup/html/feedback/AbstractFeedbackPanel.java | Java | apache-2.0 | 1,314 |
/*
* EditorMouseMenu.java
*
* Created on March 21, 2007, 10:34 AM; Updated May 29, 2007
*
* Copyright 2007 Grotto Networking
*/
package Samples.MouseMenu;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPopupMenu;
/**
* Illustrates the use of custom edge and vertex classes in a graph editing application.
* Demonstrates a new graph mouse plugin for bringing up popup menus for vertices and
* edges.
* @author Dr. Greg M. Bernstein
*/
public class EditorMouseMenu {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Editing and Mouse Menu Demo");
SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge> g =
new SparseMultigraph<GraphElements.MyVertex, GraphElements.MyEdge>();
// Layout<V, E>, VisualizationViewer<V,E>
// Map<GraphElements.MyVertex,Point2D> vertexLocations = new HashMap<GraphElements.MyVertex, Point2D>();
Layout<GraphElements.MyVertex, GraphElements.MyEdge> layout = new StaticLayout(g);
layout.setSize(new Dimension(300,300));
VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge> vv =
new VisualizationViewer<GraphElements.MyVertex,GraphElements.MyEdge>(layout);
vv.setPreferredSize(new Dimension(350,350));
// Show vertex and edge labels
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
// Create a graph mouse and add it to the visualization viewer
EditingModalGraphMouse gm = new EditingModalGraphMouse(vv.getRenderContext(),
GraphElements.MyVertexFactory.getInstance(),
GraphElements.MyEdgeFactory.getInstance());
// Set some defaults for the Edges...
GraphElements.MyEdgeFactory.setDefaultCapacity(192.0);
GraphElements.MyEdgeFactory.setDefaultWeight(5.0);
// Trying out our new popup menu mouse plugin...
PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
// Add some popup menus for the edges and vertices to our mouse plugin.
JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame);
JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu();
myPlugin.setEdgePopup(edgeMenu);
myPlugin.setVertexPopup(vertexMenu);
gm.remove(gm.getPopupEditingPlugin()); // Removes the existing popup editing plugin
gm.add(myPlugin); // Add our new plugin to the mouse
vv.setGraphMouse(gm);
//JFrame frame = new JFrame("Editing and Mouse Menu Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
// Let's add a menu for changing mouse modes
JMenuBar menuBar = new JMenuBar();
JMenu modeMenu = gm.getModeMenu();
modeMenu.setText("Mouse Mode");
modeMenu.setIcon(null); // I'm using this in a main menu
modeMenu.setPreferredSize(new Dimension(80,20)); // Change the size so I can see the text
menuBar.add(modeMenu);
frame.setJMenuBar(menuBar);
gm.setMode(ModalGraphMouse.Mode.EDITING); // Start off in editing mode
frame.pack();
frame.setVisible(true);
}
}
| ksotala/BayesGame | BayesGame/src/Samples/MouseMenu/EditorMouseMenu.java | Java | apache-2.0 | 3,984 |
package ru.job4j.max;
/**
*Класс помогает узнать, какое из двух чисел больше.
*@author ifedorenko
*@since 14.08.2017
*@version 1
*/
public class Max {
/**
*Возвращает большее число из двух.
*@param first содержит первое число
*@param second содержит второе число
*@return Большее из двух
*/
public int max(int first, int second) {
return first > second ? first : second;
}
/**
*Возвращает большее число из трех.
*@param first содержит первое число
*@param second содержит второе число
*@param third содержит третье число
*@return Большее из трех
*/
public int max(int first, int second, int third) {
return max(first, max(second, third));
}
} | fr3anthe/ifedorenko | 1.1-Base/src/main/java/ru/job4j/max/Max.java | Java | apache-2.0 | 887 |
/**
* 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.kew.docsearch.dao.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.uif.RemotableAttributeField;
import org.kuali.rice.coreservice.framework.CoreFrameworkServiceLocator;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria;
import org.kuali.rice.kew.api.document.search.DocumentSearchResults;
import org.kuali.rice.kew.docsearch.dao.DocumentSearchDAO;
import org.kuali.rice.kew.impl.document.search.DocumentSearchGenerator;
import org.kuali.rice.kew.util.PerformanceLogger;
import org.kuali.rice.krad.util.KRADConstants;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
/**
* Spring JdbcTemplate implementation of DocumentSearchDAO
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
public class DocumentSearchDAOJdbcImpl implements DocumentSearchDAO {
public static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DocumentSearchDAOJdbcImpl.class);
private static final int DEFAULT_FETCH_MORE_ITERATION_LIMIT = 10;
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = new TransactionAwareDataSourceProxy(dataSource);
}
@Override
public DocumentSearchResults.Builder findDocuments(final DocumentSearchGenerator documentSearchGenerator, final DocumentSearchCriteria criteria, final boolean criteriaModified, final List<RemotableAttributeField> searchFields) {
final int maxResultCap = getMaxResultCap(criteria);
try {
final JdbcTemplate template = new JdbcTemplate(dataSource);
return template.execute(new ConnectionCallback<DocumentSearchResults.Builder>() {
@Override
public DocumentSearchResults.Builder doInConnection(final Connection con) throws SQLException {
final Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
try {
final int fetchIterationLimit = getFetchMoreIterationLimit();
final int fetchLimit = fetchIterationLimit * maxResultCap;
statement.setFetchSize(maxResultCap + 1);
statement.setMaxRows(fetchLimit + 1);
PerformanceLogger perfLog = new PerformanceLogger();
String sql = documentSearchGenerator.generateSearchSql(criteria, searchFields);
perfLog.log("Time to generate search sql from documentSearchGenerator class: " + documentSearchGenerator
.getClass().getName(), true);
LOG.info("Executing document search with statement max rows: " + statement.getMaxRows());
LOG.info("Executing document search with statement fetch size: " + statement.getFetchSize());
perfLog = new PerformanceLogger();
final ResultSet rs = statement.executeQuery(sql);
try {
perfLog.log("Time to execute doc search database query.", true);
final Statement searchAttributeStatement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
try {
return documentSearchGenerator.processResultSet(criteria, criteriaModified, searchAttributeStatement, rs, maxResultCap, fetchLimit);
} finally {
try {
searchAttributeStatement.close();
} catch (SQLException e) {
LOG.warn("Could not close search attribute statement.");
}
}
} finally {
try {
rs.close();
} catch (SQLException e) {
LOG.warn("Could not close result set.");
}
}
} finally {
try {
statement.close();
} catch (SQLException e) {
LOG.warn("Could not close statement.");
}
}
}
});
} catch (DataAccessException dae) {
String errorMsg = "DataAccessException: " + dae.getMessage();
LOG.error("getList() " + errorMsg, dae);
throw new RuntimeException(errorMsg, dae);
} catch (Exception e) {
String errorMsg = "LookupException: " + e.getMessage();
LOG.error("getList() " + errorMsg, e);
throw new RuntimeException(errorMsg, e);
}
}
/**
* Returns the maximum number of results that should be returned from the document search.
*
* @param criteria the criteria in which to check for a max results value
* @return the maximum number of results that should be returned from a document search
*/
public int getMaxResultCap(DocumentSearchCriteria criteria) {
int systemLimit = KewApiConstants.DOCUMENT_LOOKUP_DEFAULT_RESULT_CAP;
String resultCapValue = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE, KewApiConstants.DOC_SEARCH_RESULT_CAP);
if (StringUtils.isNotBlank(resultCapValue)) {
try {
int configuredLimit = Integer.parseInt(resultCapValue);
if (configuredLimit <= 0) {
LOG.warn(KewApiConstants.DOC_SEARCH_RESULT_CAP + " was less than or equal to zero. Please use a positive integer.");
} else {
systemLimit = configuredLimit;
}
} catch (NumberFormatException e) {
LOG.warn(KewApiConstants.DOC_SEARCH_RESULT_CAP + " is not a valid number. Value was " + resultCapValue + ". Using default: " + KewApiConstants.DOCUMENT_LOOKUP_DEFAULT_RESULT_CAP);
}
}
int maxResults = systemLimit;
if (criteria.getMaxResults() != null) {
int criteriaLimit = criteria.getMaxResults().intValue();
if (criteriaLimit > systemLimit) {
LOG.warn("Result set cap of " + criteriaLimit + " is greater than system value of " + systemLimit);
} else {
if (criteriaLimit < 0) {
LOG.warn("Criteria results limit was less than zero.");
criteriaLimit = 0;
}
maxResults = criteriaLimit;
}
}
return maxResults;
}
public int getFetchMoreIterationLimit() {
int fetchMoreLimit = DEFAULT_FETCH_MORE_ITERATION_LIMIT;
String fetchMoreLimitValue = CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.DOCUMENT_SEARCH_DETAIL_TYPE, KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT);
if (!StringUtils.isBlank(fetchMoreLimitValue)) {
try {
fetchMoreLimit = Integer.parseInt(fetchMoreLimitValue);
if (fetchMoreLimit < 0) {
LOG.warn(KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT + " was less than zero. Please use a value greater than or equal to zero.");
fetchMoreLimit = DEFAULT_FETCH_MORE_ITERATION_LIMIT;
}
} catch (NumberFormatException e) {
LOG.warn(KewApiConstants.DOC_SEARCH_FETCH_MORE_ITERATION_LIMIT + " is not a valid number. Value was " + fetchMoreLimitValue);
}
}
return fetchMoreLimit;
}
}
| ua-eas/ua-rice-2.1.9 | impl/src/main/java/org/kuali/rice/kew/docsearch/dao/impl/DocumentSearchDAOJdbcImpl.java | Java | apache-2.0 | 8,999 |
/*
* Copyright 2016 Alexander Severgin
*
* 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 eu.alpinweiss.filegen.util.generator.impl;
import eu.alpinweiss.filegen.model.FieldDefinition;
import eu.alpinweiss.filegen.model.FieldType;
import eu.alpinweiss.filegen.util.wrapper.AbstractDataWrapper;
import eu.alpinweiss.filegen.util.generator.FieldGenerator;
import eu.alpinweiss.filegen.util.vault.ParameterVault;
import eu.alpinweiss.filegen.util.vault.ValueVault;
import org.apache.commons.lang.StringUtils;
import java.util.concurrent.ThreadLocalRandom;
/**
* {@link AutoNumberGenerator}.
*
* @author Aleksandrs.Severgins | <a href="http://alpinweiss.eu">SIA Alpinweiss</a>
*/
public class AutoNumberGenerator implements FieldGenerator {
private final FieldDefinition fieldDefinition;
private int startNum;
public AutoNumberGenerator(FieldDefinition fieldDefinition) {
this.fieldDefinition = fieldDefinition;
final String pattern = this.fieldDefinition.getPattern();
if (!pattern.isEmpty()) {
startNum = Integer.parseInt(pattern);
}
}
@Override
public void generate(final ParameterVault parameterVault, ThreadLocalRandom randomGenerator, ValueVault valueVault) {
valueVault.storeValue(new IntegerDataWrapper() {
@Override
public Double getNumberValue() {
int value = startNum + (parameterVault.rowCount() * parameterVault.dataPartNumber()) + parameterVault.iterationNumber();
return new Double(value);
}
});
}
private class IntegerDataWrapper extends AbstractDataWrapper {
@Override
public FieldType getFieldType() {
return FieldType.INTEGER;
}
}
}
| alpinweiss/filegen | src/main/java/eu/alpinweiss/filegen/util/generator/impl/AutoNumberGenerator.java | Java | apache-2.0 | 2,280 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.analytics.mapper;
import org.elasticsearch.index.mapper.FieldTypeTestCase;
import org.elasticsearch.index.mapper.MappedFieldType;
public class HistogramFieldTypeTests extends FieldTypeTestCase<MappedFieldType> {
@Override
protected MappedFieldType createDefaultFieldType() {
return new HistogramFieldMapper.HistogramFieldType();
}
}
| uschindler/elasticsearch | x-pack/plugin/analytics/src/test/java/org/elasticsearch/xpack/analytics/mapper/HistogramFieldTypeTests.java | Java | apache-2.0 | 632 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml.provider;
import java.util.Collection;
import java.util.List;
import net.opengis.gml.FeatureStyleType;
import net.opengis.gml.GmlFactory;
import net.opengis.gml.GmlPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMapUtil;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link net.opengis.gml.FeatureStyleType} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class FeatureStyleTypeItemProvider
extends AbstractGMLTypeItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FeatureStyleTypeItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addFeatureConstraintPropertyDescriptor(object);
addBaseTypePropertyDescriptor(object);
addFeatureTypePropertyDescriptor(object);
addQueryGrammarPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Feature Constraint feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFeatureConstraintPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_featureConstraint_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_featureConstraint_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_FeatureConstraint(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Base Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addBaseTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_baseType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_baseType_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_BaseType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Feature Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFeatureTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_featureType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_featureType_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_FeatureType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Query Grammar feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addQueryGrammarPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureStyleType_queryGrammar_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureStyleType_queryGrammar_feature", "_UI_FeatureStyleType_type"),
GmlPackage.eINSTANCE.getFeatureStyleType_QueryGrammar(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_GeometryStyle());
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_TopologyStyle());
childrenFeatures.add(GmlPackage.eINSTANCE.getFeatureStyleType_LabelStyle());
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns FeatureStyleType.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/FeatureStyleType"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((FeatureStyleType)object).getId();
return label == null || label.length() == 0 ?
getString("_UI_FeatureStyleType_type") :
getString("_UI_FeatureStyleType_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(FeatureStyleType.class)) {
case GmlPackage.FEATURE_STYLE_TYPE__FEATURE_CONSTRAINT:
case GmlPackage.FEATURE_STYLE_TYPE__BASE_TYPE:
case GmlPackage.FEATURE_STYLE_TYPE__FEATURE_TYPE:
case GmlPackage.FEATURE_STYLE_TYPE__QUERY_GRAMMAR:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case GmlPackage.FEATURE_STYLE_TYPE__GEOMETRY_STYLE:
case GmlPackage.FEATURE_STYLE_TYPE__TOPOLOGY_STYLE:
case GmlPackage.FEATURE_STYLE_TYPE__LABEL_STYLE:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_GeometryStyle(),
GmlFactory.eINSTANCE.createGeometryStylePropertyType()));
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_TopologyStyle(),
GmlFactory.eINSTANCE.createTopologyStylePropertyType()));
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getFeatureStyleType_LabelStyle(),
GmlFactory.eINSTANCE.createLabelStylePropertyType()));
}
/**
* This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) {
Object childFeature = feature;
Object childObject = child;
if (childFeature instanceof EStructuralFeature && FeatureMapUtil.isFeatureMap((EStructuralFeature)childFeature)) {
FeatureMap.Entry entry = (FeatureMap.Entry)childObject;
childFeature = entry.getEStructuralFeature();
childObject = entry.getValue();
}
boolean qualify =
childFeature == GmlPackage.eINSTANCE.getAbstractGMLType_Name() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CoordinateOperationName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CsName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_DatumName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_EllipsoidName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_GroupName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MeridianName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MethodName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_ParameterName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_SrsName();
if (qualify) {
return getString
("_UI_CreateChild_text2",
new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) });
}
return super.getCreateChildText(owner, feature, child, selection);
}
}
| markus1978/citygml4emf | de.hub.citygml.emf.ecore.edit/src/net/opengis/gml/provider/FeatureStyleTypeItemProvider.java | Java | apache-2.0 | 10,661 |
/*
* 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.neptune.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/neptune-2014-10-31/RemoveRoleFromDBCluster" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RemoveRoleFromDBClusterResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* 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("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RemoveRoleFromDBClusterResult == false)
return false;
RemoveRoleFromDBClusterResult other = (RemoveRoleFromDBClusterResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public RemoveRoleFromDBClusterResult clone() {
try {
return (RemoveRoleFromDBClusterResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-neptune/src/main/java/com/amazonaws/services/neptune/model/RemoveRoleFromDBClusterResult.java | Java | apache-2.0 | 2,392 |
package ru.istolbov;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
* @author istolbov
* @version $Id$
*/
public class TurnTest {
/**
* Test turn back array.
*/
@Test
public void whenWeTurnBackArray() {
final int[] targetArray = new int[] {5, 4, 3, 2, 1};
final int[] testArray = new int[] {1, 2, 3, 4, 5};
final Turn turn = new Turn();
final int[] resultArray = turn.back(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test sort.
*/
@Test
public void whenWeSortArray() {
final int[] targetArray = new int[] {1, 2, 3, 4, 5};
final int[] testArray = new int[] {5, 3, 4, 1, 2};
final Turn turn = new Turn();
final int[] resultArray = turn.sort(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test rotate.
*/
@Test
public void whenWeRotateArray() {
final int[][] targetArray = new int[][] {{13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4}};
final int[][] testArray = new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
final Turn turn = new Turn();
final int[][] resultArray = turn.rotate(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test duplicateDelete.
*/
@Test
public void whenWeDuplicateDeleteInArray() {
final String[] targetArray = new String[] {"Привет", "Мир", "Май"};
final String[] testArray = new String[] {"Привет", "Привет", "Мир", "Привет", "Май", "Май", "Мир"};
final Turn turn = new Turn();
final String[] resultArray = turn.duplicateDelete(testArray);
assertThat(resultArray, is(targetArray));
}
/**
* Test join.
*/
@Test
public void whenWeJoinArrays() {
final int[] firstTestArray = new int[] {1, 3, 5, 7, 9};
final int[] secondTestArray = new int[] {2, 4, 6, 8, 10};
final int[] targetArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
final Turn turn = new Turn();
final int[] resultArray = turn.join(firstTestArray, secondTestArray);
assertThat(resultArray, is(targetArray));
}
} | istolbov/i_stolbov | chapter_001/src/test/java/ru/istolbov/TurnTest.java | Java | apache-2.0 | 2,196 |
package javay.test.security;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* DES安全编码组件
*
* <pre>
* 支持 DES、DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR)
* DES key size must be equal to 56
* DESede(TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
* RC2 key size must be between 40 and 1024 bits
* RC4(ARCFOUR) key size must be between 40 and 1024 bits
* 具体内容 需要关注 JDK Document http://.../docs/technotes/guides/security/SunProviders.html
* </pre>
*
*/
public abstract class DESCoder extends Coder {
/**
* ALGORITHM 算法 <br>
* 可替换为以下任意一种算法,同时key值的size相应改变。
*
* <pre>
* DES key size must be equal to 56
* DESede(TripleDES) key size must be equal to 112 or 168
* AES key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
* Blowfish key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
* RC2 key size must be between 40 and 1024 bits
* RC4(ARCFOUR) key size must be between 40 and 1024 bits
* </pre>
*
* 在Key toKey(byte[] key)方法中使用下述代码
* <code>SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);</code> 替换
* <code>
* DESKeySpec dks = new DESKeySpec(key);
* SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
* SecretKey secretKey = keyFactory.generateSecret(dks);
* </code>
*/
public static final String ALGORITHM = "DES";
/**
* 转换密钥<br>
*
* @param key
* @return
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(dks);
// 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码
// SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
return secretKey;
}
/**
* 解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, String key) throws Exception {
Key k = toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
Key k = toKey(decryptBASE64(key));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, k);
return cipher.doFinal(data);
}
/**
* 生成密钥
*
* @return
* @throws Exception
*/
public static String initKey() throws Exception {
return initKey(null);
}
/**
* 生成密钥
*
* @param seed
* @return
* @throws Exception
*/
public static String initKey(String seed) throws Exception {
SecureRandom secureRandom = null;
if (seed != null) {
secureRandom = new SecureRandom(decryptBASE64(seed));
} else {
secureRandom = new SecureRandom();
}
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
kg.init(secureRandom);
SecretKey secretKey = kg.generateKey();
return encryptBASE64(secretKey.getEncoded());
}
}
| dubenju/javay | src/java/javay/test/security/DESCoder.java | Java | apache-2.0 | 4,047 |
/*
* Copyright 2016 Yu Sheng. 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.ysheng.auth.model.api;
/**
* Defines the grant types.
*/
public enum GrantType {
AUTHORIZATION_CODE,
IMPLICIT,
PASSWORD,
CLIENT_CREDENTIALS
}
| zeelichsheng/auth | auth-model/src/main/java/com/ysheng/auth/model/api/GrantType.java | Java | apache-2.0 | 769 |
package me.knox.zmz.mvp.model;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import java.util.List;
import javax.inject.Inject;
import me.knox.zmz.App;
import me.knox.zmz.entity.News;
import me.knox.zmz.mvp.contract.NewsListContract;
import me.knox.zmz.network.JsonResponse;
/**
* Created by KNOX.
*/
public class NewsListModel implements NewsListContract.Model {
@Inject public NewsListModel() {
// empty constructor for injection
}
@Override public Flowable<JsonResponse<List<News>>> getNewsList() {
return App.getInstance().getApi().getNews().observeOn(AndroidSchedulers.mainThread(), true);
}
}
| chowaikong/ZMZ | app/src/main/java/me/knox/zmz/mvp/model/NewsListModel.java | Java | apache-2.0 | 664 |
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.model.tld;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Maps.toMap;
import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration;
import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static org.joda.money.CurrencyUnit.USD;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Mapify;
import com.googlecode.objectify.annotation.OnSave;
import com.googlecode.objectify.annotation.Parent;
import google.registry.model.Buildable;
import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject;
import google.registry.model.UnsafeSerializable;
import google.registry.model.annotations.InCrossTld;
import google.registry.model.annotations.ReportedOn;
import google.registry.model.common.EntityGroupRoot;
import google.registry.model.common.TimedTransitionProperty;
import google.registry.model.common.TimedTransitionProperty.TimedTransition;
import google.registry.model.domain.fee.BaseFee.FeeType;
import google.registry.model.domain.fee.Fee;
import google.registry.model.replay.DatastoreAndSqlEntity;
import google.registry.model.tld.label.PremiumList;
import google.registry.model.tld.label.ReservedList;
import google.registry.persistence.VKey;
import google.registry.persistence.converter.JodaMoneyType;
import google.registry.util.Idn;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.PostLoad;
import javax.persistence.Transient;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.joda.time.Duration;
/** Persisted per-TLD configuration data. */
@ReportedOn
@Entity
@javax.persistence.Entity(name = "Tld")
@InCrossTld
public class Registry extends ImmutableObject
implements Buildable, DatastoreAndSqlEntity, UnsafeSerializable {
@Parent @Transient Key<EntityGroupRoot> parent = getCrossTldKey();
/**
* The canonical string representation of the TLD associated with this {@link Registry}, which is
* the standard ASCII for regular TLDs and punycoded ASCII for IDN TLDs.
*/
@Id
@javax.persistence.Id
@Column(name = "tld_name", nullable = false)
String tldStrId;
/**
* A duplicate of {@link #tldStrId}, to simplify BigQuery reporting since the id field becomes
* {@code __key__.name} rather than being exported as a named field.
*/
@Transient String tldStr;
/** Sets the Datastore specific field, tldStr, when the entity is loaded from Cloud SQL */
@PostLoad
void postLoad() {
tldStr = tldStrId;
}
/** The suffix that identifies roids as belonging to this specific tld, e.g. -HOW for .how. */
String roidSuffix;
/** Default values for all the relevant TLD parameters. */
public static final TldState DEFAULT_TLD_STATE = TldState.PREDELEGATION;
public static final boolean DEFAULT_ESCROW_ENABLED = false;
public static final boolean DEFAULT_DNS_PAUSED = false;
public static final Duration DEFAULT_ADD_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_AUTO_RENEW_GRACE_PERIOD = Duration.standardDays(45);
public static final Duration DEFAULT_REDEMPTION_GRACE_PERIOD = Duration.standardDays(30);
public static final Duration DEFAULT_RENEW_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_TRANSFER_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_AUTOMATIC_TRANSFER_LENGTH = Duration.standardDays(5);
public static final Duration DEFAULT_PENDING_DELETE_LENGTH = Duration.standardDays(5);
public static final Duration DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD = Duration.standardDays(30);
public static final CurrencyUnit DEFAULT_CURRENCY = USD;
public static final Money DEFAULT_CREATE_BILLING_COST = Money.of(USD, 8);
public static final Money DEFAULT_EAP_BILLING_COST = Money.of(USD, 0);
public static final Money DEFAULT_RENEW_BILLING_COST = Money.of(USD, 8);
public static final Money DEFAULT_RESTORE_BILLING_COST = Money.of(USD, 100);
public static final Money DEFAULT_SERVER_STATUS_CHANGE_BILLING_COST = Money.of(USD, 20);
public static final Money DEFAULT_REGISTRY_LOCK_OR_UNLOCK_BILLING_COST = Money.of(USD, 0);
/** The type of TLD, which determines things like backups and escrow policy. */
public enum TldType {
/** A real, official TLD. */
REAL,
/** A test TLD, for the prober. */
TEST
}
/**
* The states a TLD can be in at any given point in time. The ordering below is the required
* sequence of states (ignoring {@link #PDT} which is a pseudo-state).
*/
public enum TldState {
/** The state of not yet being delegated to this registry in the root zone by IANA. */
PREDELEGATION,
/**
* The state in which only trademark holders can submit a "create" request. It is identical to
* {@link #GENERAL_AVAILABILITY} in all other respects.
*/
START_DATE_SUNRISE,
/**
* A state in which no domain operations are permitted. Generally used between sunrise and
* general availability. This state is special in that it has no ordering constraints and can
* appear after any phase.
*/
QUIET_PERIOD,
/**
* The steady state of a TLD in which all domain names are available via first-come,
* first-serve.
*/
GENERAL_AVAILABILITY,
/** A "fake" state for use in predelegation testing. Acts like {@link #GENERAL_AVAILABILITY}. */
PDT
}
/**
* A transition to a TLD state at a specific time, for use in a TimedTransitionProperty. Public
* because App Engine's security manager requires this for instantiation via reflection.
*/
@Embed
public static class TldStateTransition extends TimedTransition<TldState> {
/** The TLD state. */
private TldState tldState;
@Override
public TldState getValue() {
return tldState;
}
@Override
protected void setValue(TldState tldState) {
this.tldState = tldState;
}
}
/**
* A transition to a given billing cost at a specific time, for use in a TimedTransitionProperty.
*
* <p>Public because App Engine's security manager requires this for instantiation via reflection.
*/
@Embed
public static class BillingCostTransition extends TimedTransition<Money> {
/** The billing cost value. */
private Money billingCost;
@Override
public Money getValue() {
return billingCost;
}
@Override
protected void setValue(Money billingCost) {
this.billingCost = billingCost;
}
}
/** Returns the registry for a given TLD, throwing if none exists. */
public static Registry get(String tld) {
Registry registry = CACHE.getUnchecked(tld).orElse(null);
if (registry == null) {
throw new RegistryNotFoundException(tld);
}
return registry;
}
/** Returns the registry entities for the given TLD strings, throwing if any don't exist. */
static ImmutableSet<Registry> getAll(Set<String> tlds) {
try {
ImmutableMap<String, Optional<Registry>> registries = CACHE.getAll(tlds);
ImmutableSet<String> missingRegistries =
registries.entrySet().stream()
.filter(e -> !e.getValue().isPresent())
.map(Map.Entry::getKey)
.collect(toImmutableSet());
if (missingRegistries.isEmpty()) {
return registries.values().stream().map(Optional::get).collect(toImmutableSet());
} else {
throw new RegistryNotFoundException(missingRegistries);
}
} catch (ExecutionException e) {
throw new RuntimeException("Unexpected error retrieving TLDs " + tlds, e);
}
}
/**
* Invalidates the cache entry.
*
* <p>This is called automatically when the registry is saved. One should also call it when a
* registry is deleted.
*/
@OnSave
public void invalidateInCache() {
CACHE.invalidate(tldStr);
}
/** A cache that loads the {@link Registry} for a given tld. */
private static final LoadingCache<String, Optional<Registry>> CACHE =
CacheBuilder.newBuilder()
.expireAfterWrite(
java.time.Duration.ofMillis(getSingletonCacheRefreshDuration().getMillis()))
.build(
new CacheLoader<String, Optional<Registry>>() {
@Override
public Optional<Registry> load(final String tld) {
// Enter a transaction-less context briefly; we don't want to enroll every TLD in
// a transaction that might be wrapping this call.
return tm().doTransactionless(() -> tm().loadByKeyIfPresent(createVKey(tld)));
}
@Override
public Map<String, Optional<Registry>> loadAll(Iterable<? extends String> tlds) {
ImmutableMap<String, VKey<Registry>> keysMap =
toMap(ImmutableSet.copyOf(tlds), Registry::createVKey);
Map<VKey<? extends Registry>, Registry> entities =
tm().doTransactionless(() -> tm().loadByKeys(keysMap.values()));
return Maps.transformEntries(
keysMap, (k, v) -> Optional.ofNullable(entities.getOrDefault(v, null)));
}
});
public static VKey<Registry> createVKey(String tld) {
return VKey.create(Registry.class, tld, Key.create(getCrossTldKey(), Registry.class, tld));
}
public static VKey<Registry> createVKey(Key<Registry> key) {
return createVKey(key.getName());
}
/**
* The name of the pricing engine that this TLD uses.
*
* <p>This must be a valid key for the map of pricing engines injected by {@code @Inject
* Map<String, PricingEngine>}.
*
* <p>Note that it used to be the canonical class name, hence the name of this field, but this
* restriction has since been relaxed and it may now be any unique string.
*/
String pricingEngineClassName;
/**
* The set of name(s) of the {@code DnsWriter} implementations that this TLD uses.
*
* <p>There must be at least one entry in this set.
*
* <p>All entries of this list must be valid keys for the map of {@code DnsWriter}s injected by
* {@code @Inject Map<String, DnsWriter>}
*/
@Column(nullable = false)
Set<String> dnsWriters;
/**
* The number of locks we allow at once for {@link google.registry.dns.PublishDnsUpdatesAction}.
*
* <p>This should always be a positive integer- use 1 for TLD-wide locks. All {@link Registry}
* objects have this value default to 1.
*
* <p>WARNING: changing this parameter changes the lock name for subsequent DNS updates, and thus
* invalidates the locking scheme for enqueued DNS publish updates. If the {@link
* google.registry.dns.writer.DnsWriter} you use is not parallel-write tolerant, you must follow
* this procedure to change this value:
*
* <ol>
* <li>Pause the DNS queue via {@link google.registry.tools.UpdateTldCommand}
* <li>Change this number
* <li>Let the Registry caches expire (currently 5 minutes) and drain the DNS publish queue
* <li>Unpause the DNS queue
* </ol>
*
* <p>Failure to do so can result in parallel writes to the {@link
* google.registry.dns.writer.DnsWriter}, which may be dangerous depending on your implementation.
*/
@Column(nullable = false)
int numDnsPublishLocks;
/** Updates an unset numDnsPublishLocks (0) to the standard default of 1. */
void setDefaultNumDnsPublishLocks() {
if (numDnsPublishLocks == 0) {
numDnsPublishLocks = 1;
}
}
/**
* The unicode-aware representation of the TLD associated with this {@link Registry}.
*
* <p>This will be equal to {@link #tldStr} for ASCII TLDs, but will be non-ASCII for IDN TLDs. We
* store this in a field so that it will be retained upon import into BigQuery.
*/
@Column(nullable = false)
String tldUnicode;
/**
* Id of the folder in drive used to public (export) information for this TLD.
*
* <p>This is optional; if not configured, then information won't be exported for this TLD.
*/
@Nullable String driveFolderId;
/** The type of the TLD, whether it's real or for testing. */
@Column(nullable = false)
@Enumerated(EnumType.STRING)
TldType tldType = TldType.REAL;
/**
* Whether to enable invoicing for this TLD.
*
* <p>Note that this boolean is the sole determiner on whether invoices should be generated for a
* TLD. This applies to {@link TldType#TEST} TLDs as well.
*/
@Column(nullable = false)
boolean invoicingEnabled = false;
/**
* A property that transitions to different TldStates at different times. Stored as a list of
* TldStateTransition embedded objects using the @Mapify annotation.
*/
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<TldState, TldStateTransition> tldStateTransitions =
TimedTransitionProperty.forMapify(DEFAULT_TLD_STATE, TldStateTransition.class);
/** An automatically managed creation timestamp. */
@Column(nullable = false)
CreateAutoTimestamp creationTime = CreateAutoTimestamp.create(null);
/** The set of reserved list names that are applicable to this registry. */
@Column(name = "reserved_list_names")
Set<String> reservedListNames;
/**
* Retrieves an ImmutableSet of all ReservedLists associated with this TLD.
*
* <p>This set contains only the names of the list and not a reference to the lists. Updates to a
* reserved list in Cloud SQL are saved as a new ReservedList entity. When using the ReservedList
* for a registry, the database should be queried for the entity with this name that has the
* largest revision ID.
*/
public ImmutableSet<String> getReservedListNames() {
return nullToEmptyImmutableCopy(reservedListNames);
}
/**
* The name of the {@link PremiumList} for this TLD, if there is one.
*
* <p>This is only the name of the list and not a reference to the list. Updates to the premium
* list in Cloud SQL are saved as a new PremiumList entity. When using the PremiumList for a
* registry, the database should be queried for the entity with this name that has the largest
* revision ID.
*/
@Column(name = "premium_list_name", nullable = true)
String premiumListName;
/** Should RDE upload a nightly escrow deposit for this TLD? */
@Column(nullable = false)
boolean escrowEnabled = DEFAULT_ESCROW_ENABLED;
/** Whether the pull queue that writes to authoritative DNS is paused for this TLD. */
@Column(nullable = false)
boolean dnsPaused = DEFAULT_DNS_PAUSED;
/**
* The length of the add grace period for this TLD.
*
* <p>Domain deletes are free and effective immediately so long as they take place within this
* amount of time following creation.
*/
@Column(nullable = false)
Duration addGracePeriodLength = DEFAULT_ADD_GRACE_PERIOD;
/** The length of the anchor tenant add grace period for this TLD. */
@Column(nullable = false)
Duration anchorTenantAddGracePeriodLength = DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD;
/** The length of the auto renew grace period for this TLD. */
@Column(nullable = false)
Duration autoRenewGracePeriodLength = DEFAULT_AUTO_RENEW_GRACE_PERIOD;
/** The length of the redemption grace period for this TLD. */
@Column(nullable = false)
Duration redemptionGracePeriodLength = DEFAULT_REDEMPTION_GRACE_PERIOD;
/** The length of the renew grace period for this TLD. */
@Column(nullable = false)
Duration renewGracePeriodLength = DEFAULT_RENEW_GRACE_PERIOD;
/** The length of the transfer grace period for this TLD. */
@Column(nullable = false)
Duration transferGracePeriodLength = DEFAULT_TRANSFER_GRACE_PERIOD;
/** The length of time before a transfer is automatically approved for this TLD. */
@Column(nullable = false)
Duration automaticTransferLength = DEFAULT_AUTOMATIC_TRANSFER_LENGTH;
/** The length of time a domain spends in the non-redeemable pending delete phase for this TLD. */
@Column(nullable = false)
Duration pendingDeleteLength = DEFAULT_PENDING_DELETE_LENGTH;
/** The currency unit for all costs associated with this TLD. */
@Column(nullable = false)
CurrencyUnit currency = DEFAULT_CURRENCY;
/** The per-year billing cost for registering a new domain name. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "create_billing_cost_amount"),
@Column(name = "create_billing_cost_currency")
})
Money createBillingCost = DEFAULT_CREATE_BILLING_COST;
/** The one-time billing cost for restoring a domain name from the redemption grace period. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "restore_billing_cost_amount"),
@Column(name = "restore_billing_cost_currency")
})
Money restoreBillingCost = DEFAULT_RESTORE_BILLING_COST;
/** The one-time billing cost for changing the server status (i.e. lock). */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "server_status_change_billing_cost_amount"),
@Column(name = "server_status_change_billing_cost_currency")
})
Money serverStatusChangeBillingCost = DEFAULT_SERVER_STATUS_CHANGE_BILLING_COST;
/** The one-time billing cost for a registry lock/unlock action initiated by a registrar. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "registry_lock_or_unlock_cost_amount"),
@Column(name = "registry_lock_or_unlock_cost_currency")
})
Money registryLockOrUnlockBillingCost = DEFAULT_REGISTRY_LOCK_OR_UNLOCK_BILLING_COST;
/**
* A property that transitions to different renew billing costs at different times. Stored as a
* list of BillingCostTransition embedded objects using the @Mapify annotation.
*
* <p>A given value of this property represents the per-year billing cost for renewing a domain
* name. This cost is also used to compute costs for transfers, since each transfer includes a
* renewal to ensure transfers have a cost.
*/
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<Money, BillingCostTransition> renewBillingCostTransitions =
TimedTransitionProperty.forMapify(DEFAULT_RENEW_BILLING_COST, BillingCostTransition.class);
/** A property that tracks the EAP fee schedule (if any) for the TLD. */
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<Money, BillingCostTransition> eapFeeSchedule =
TimedTransitionProperty.forMapify(DEFAULT_EAP_BILLING_COST, BillingCostTransition.class);
/** Marksdb LORDN service username (password is stored in Keyring) */
String lordnUsername;
/** The end of the claims period (at or after this time, claims no longer applies). */
@Column(nullable = false)
DateTime claimsPeriodEnd = END_OF_TIME;
/** An allow list of clients allowed to be used on domains on this TLD (ignored if empty). */
@Nullable Set<String> allowedRegistrantContactIds;
/** An allow list of hosts allowed to be used on domains on this TLD (ignored if empty). */
@Nullable Set<String> allowedFullyQualifiedHostNames;
public String getTldStr() {
return tldStr;
}
public String getRoidSuffix() {
return roidSuffix;
}
/** Retrieve the actual domain name representing the TLD for which this registry operates. */
public InternetDomainName getTld() {
return InternetDomainName.from(tldStr);
}
/** Retrieve the TLD type (real or test). */
public TldType getTldType() {
return tldType;
}
/**
* Retrieve the TLD state at the given time. Defaults to {@link TldState#PREDELEGATION}.
*
* <p>Note that {@link TldState#PDT} TLDs pretend to be in {@link TldState#GENERAL_AVAILABILITY}.
*/
public TldState getTldState(DateTime now) {
TldState state = tldStateTransitions.getValueAtTime(now);
return TldState.PDT.equals(state) ? TldState.GENERAL_AVAILABILITY : state;
}
/** Retrieve whether this TLD is in predelegation testing. */
public boolean isPdt(DateTime now) {
return TldState.PDT.equals(tldStateTransitions.getValueAtTime(now));
}
public DateTime getCreationTime() {
return creationTime.getTimestamp();
}
public boolean getEscrowEnabled() {
return escrowEnabled;
}
public boolean getDnsPaused() {
return dnsPaused;
}
public String getDriveFolderId() {
return driveFolderId;
}
public Duration getAddGracePeriodLength() {
return addGracePeriodLength;
}
public Duration getAutoRenewGracePeriodLength() {
return autoRenewGracePeriodLength;
}
public Duration getRedemptionGracePeriodLength() {
return redemptionGracePeriodLength;
}
public Duration getRenewGracePeriodLength() {
return renewGracePeriodLength;
}
public Duration getTransferGracePeriodLength() {
return transferGracePeriodLength;
}
public Duration getAutomaticTransferLength() {
return automaticTransferLength;
}
public Duration getPendingDeleteLength() {
return pendingDeleteLength;
}
public Duration getAnchorTenantAddGracePeriodLength() {
return anchorTenantAddGracePeriodLength;
}
public Optional<String> getPremiumListName() {
return Optional.ofNullable(premiumListName);
}
public CurrencyUnit getCurrency() {
return currency;
}
/**
* Use <code>PricingEngineProxy.getDomainCreateCost</code> instead of this to find the cost for a
* domain create.
*/
@VisibleForTesting
public Money getStandardCreateCost() {
return createBillingCost;
}
/**
* Returns the add-on cost of a domain restore (the flat registry-wide fee charged in addition to
* one year of renewal for that name).
*/
public Money getStandardRestoreCost() {
return restoreBillingCost;
}
/**
* Use <code>PricingEngineProxy.getDomainRenewCost</code> instead of this to find the cost for a
* domain renewal, and all derived costs (i.e. autorenews, transfers, and the per-domain part of a
* restore cost).
*/
public Money getStandardRenewCost(DateTime now) {
return renewBillingCostTransitions.getValueAtTime(now);
}
/** Returns the cost of a server status change (i.e. lock). */
public Money getServerStatusChangeCost() {
return serverStatusChangeBillingCost;
}
/** Returns the cost of a registry lock/unlock. */
public Money getRegistryLockOrUnlockBillingCost() {
return registryLockOrUnlockBillingCost;
}
public ImmutableSortedMap<DateTime, TldState> getTldStateTransitions() {
return tldStateTransitions.toValueMap();
}
public ImmutableSortedMap<DateTime, Money> getRenewBillingCostTransitions() {
return renewBillingCostTransitions.toValueMap();
}
/** Returns the EAP fee for the registry at the given time. */
public Fee getEapFeeFor(DateTime now) {
ImmutableSortedMap<DateTime, Money> valueMap = getEapFeeScheduleAsMap();
DateTime periodStart = valueMap.floorKey(now);
DateTime periodEnd = valueMap.ceilingKey(now);
// NOTE: assuming END_OF_TIME would never be reached...
Range<DateTime> validPeriod =
Range.closedOpen(
periodStart != null ? periodStart : START_OF_TIME,
periodEnd != null ? periodEnd : END_OF_TIME);
return Fee.create(
eapFeeSchedule.getValueAtTime(now).getAmount(),
FeeType.EAP,
// An EAP fee does not count as premium -- it's a separate one-time fee, independent of
// which the domain is separately considered standard vs premium depending on renewal price.
false,
validPeriod,
validPeriod.upperEndpoint());
}
@VisibleForTesting
public ImmutableSortedMap<DateTime, Money> getEapFeeScheduleAsMap() {
return eapFeeSchedule.toValueMap();
}
public String getLordnUsername() {
return lordnUsername;
}
public DateTime getClaimsPeriodEnd() {
return claimsPeriodEnd;
}
public String getPremiumPricingEngineClassName() {
return pricingEngineClassName;
}
public ImmutableSet<String> getDnsWriters() {
return ImmutableSet.copyOf(dnsWriters);
}
/** Returns the number of simultaneous DNS publish operations we allow at once. */
public int getNumDnsPublishLocks() {
return numDnsPublishLocks;
}
public ImmutableSet<String> getAllowedRegistrantContactIds() {
return nullToEmptyImmutableCopy(allowedRegistrantContactIds);
}
public ImmutableSet<String> getAllowedFullyQualifiedHostNames() {
return nullToEmptyImmutableCopy(allowedFullyQualifiedHostNames);
}
@Override
public Builder asBuilder() {
return new Builder(clone(this));
}
/** A builder for constructing {@link Registry} objects, since they are immutable. */
public static class Builder extends Buildable.Builder<Registry> {
public Builder() {}
private Builder(Registry instance) {
super(instance);
}
public Builder setTldType(TldType tldType) {
getInstance().tldType = tldType;
return this;
}
public Builder setInvoicingEnabled(boolean invoicingEnabled) {
getInstance().invoicingEnabled = invoicingEnabled;
return this;
}
/** Sets the TLD state to transition to the specified states at the specified times. */
public Builder setTldStateTransitions(ImmutableSortedMap<DateTime, TldState> tldStatesMap) {
checkNotNull(tldStatesMap, "TLD states map cannot be null");
// Filter out any entries with QUIET_PERIOD as the value before checking for ordering, since
// that phase is allowed to appear anywhere.
checkArgument(
Ordering.natural()
.isStrictlyOrdered(
Iterables.filter(tldStatesMap.values(), not(equalTo(TldState.QUIET_PERIOD)))),
"The TLD states are chronologically out of order");
getInstance().tldStateTransitions =
TimedTransitionProperty.fromValueMap(tldStatesMap, TldStateTransition.class);
return this;
}
public Builder setTldStr(String tldStr) {
checkArgument(tldStr != null, "TLD must not be null");
getInstance().tldStr = tldStr;
return this;
}
public Builder setEscrowEnabled(boolean enabled) {
getInstance().escrowEnabled = enabled;
return this;
}
public Builder setDnsPaused(boolean paused) {
getInstance().dnsPaused = paused;
return this;
}
public Builder setDriveFolderId(String driveFolderId) {
getInstance().driveFolderId = driveFolderId;
return this;
}
public Builder setPremiumPricingEngine(String pricingEngineClass) {
getInstance().pricingEngineClassName = checkArgumentNotNull(pricingEngineClass);
return this;
}
public Builder setDnsWriters(ImmutableSet<String> dnsWriters) {
getInstance().dnsWriters = dnsWriters;
return this;
}
public Builder setNumDnsPublishLocks(int numDnsPublishLocks) {
checkArgument(
numDnsPublishLocks > 0,
"numDnsPublishLocks must be positive when set explicitly (use 1 for TLD-wide locks)");
getInstance().numDnsPublishLocks = numDnsPublishLocks;
return this;
}
public Builder setAddGracePeriodLength(Duration addGracePeriodLength) {
checkArgument(
addGracePeriodLength.isLongerThan(Duration.ZERO),
"addGracePeriodLength must be non-zero");
getInstance().addGracePeriodLength = addGracePeriodLength;
return this;
}
/** Warning! Changing this will affect the billing time of autorenew events in the past. */
public Builder setAutoRenewGracePeriodLength(Duration autoRenewGracePeriodLength) {
checkArgument(
autoRenewGracePeriodLength.isLongerThan(Duration.ZERO),
"autoRenewGracePeriodLength must be non-zero");
getInstance().autoRenewGracePeriodLength = autoRenewGracePeriodLength;
return this;
}
public Builder setRedemptionGracePeriodLength(Duration redemptionGracePeriodLength) {
checkArgument(
redemptionGracePeriodLength.isLongerThan(Duration.ZERO),
"redemptionGracePeriodLength must be non-zero");
getInstance().redemptionGracePeriodLength = redemptionGracePeriodLength;
return this;
}
public Builder setRenewGracePeriodLength(Duration renewGracePeriodLength) {
checkArgument(
renewGracePeriodLength.isLongerThan(Duration.ZERO),
"renewGracePeriodLength must be non-zero");
getInstance().renewGracePeriodLength = renewGracePeriodLength;
return this;
}
public Builder setTransferGracePeriodLength(Duration transferGracePeriodLength) {
checkArgument(
transferGracePeriodLength.isLongerThan(Duration.ZERO),
"transferGracePeriodLength must be non-zero");
getInstance().transferGracePeriodLength = transferGracePeriodLength;
return this;
}
public Builder setAutomaticTransferLength(Duration automaticTransferLength) {
checkArgument(
automaticTransferLength.isLongerThan(Duration.ZERO),
"automaticTransferLength must be non-zero");
getInstance().automaticTransferLength = automaticTransferLength;
return this;
}
public Builder setPendingDeleteLength(Duration pendingDeleteLength) {
checkArgument(
pendingDeleteLength.isLongerThan(Duration.ZERO), "pendingDeleteLength must be non-zero");
getInstance().pendingDeleteLength = pendingDeleteLength;
return this;
}
public Builder setCurrency(CurrencyUnit currency) {
checkArgument(currency != null, "currency must be non-null");
getInstance().currency = currency;
return this;
}
public Builder setCreateBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "createBillingCost cannot be negative");
getInstance().createBillingCost = amount;
return this;
}
public Builder setReservedListsByName(Set<String> reservedListNames) {
checkArgument(reservedListNames != null, "reservedListNames must not be null");
ImmutableSet.Builder<ReservedList> builder = new ImmutableSet.Builder<>();
for (String reservedListName : reservedListNames) {
// Check for existence of the reserved list and throw an exception if it doesn't exist.
Optional<ReservedList> reservedList = ReservedList.get(reservedListName);
checkArgument(
reservedList.isPresent(),
"Could not find reserved list %s to add to the tld",
reservedListName);
builder.add(reservedList.get());
}
return setReservedLists(builder.build());
}
public Builder setReservedLists(ReservedList... reservedLists) {
return setReservedLists(ImmutableSet.copyOf(reservedLists));
}
public Builder setReservedLists(Set<ReservedList> reservedLists) {
checkArgumentNotNull(reservedLists, "reservedLists must not be null");
ImmutableSet.Builder<String> nameBuilder = new ImmutableSet.Builder<>();
for (ReservedList reservedList : reservedLists) {
nameBuilder.add(reservedList.getName());
}
getInstance().reservedListNames = nameBuilder.build();
return this;
}
public Builder setPremiumList(@Nullable PremiumList premiumList) {
getInstance().premiumListName = (premiumList == null) ? null : premiumList.getName();
return this;
}
public Builder setRestoreBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "restoreBillingCost cannot be negative");
getInstance().restoreBillingCost = amount;
return this;
}
/**
* Sets the renew billing cost to transition to the specified values at the specified times.
*
* <p>Renew billing costs transitions should only be added at least 5 days (the length of an
* automatic transfer) in advance, to avoid discrepancies between the cost stored with the
* billing event (created when the transfer is requested) and the cost at the time when the
* transfer actually occurs (5 days later).
*/
public Builder setRenewBillingCostTransitions(
ImmutableSortedMap<DateTime, Money> renewCostsMap) {
checkArgumentNotNull(renewCostsMap, "Renew billing costs map cannot be null");
checkArgument(
renewCostsMap.values().stream().allMatch(Money::isPositiveOrZero),
"Renew billing cost cannot be negative");
getInstance().renewBillingCostTransitions =
TimedTransitionProperty.fromValueMap(renewCostsMap, BillingCostTransition.class);
return this;
}
/** Sets the EAP fee schedule for the TLD. */
public Builder setEapFeeSchedule(ImmutableSortedMap<DateTime, Money> eapFeeSchedule) {
checkArgumentNotNull(eapFeeSchedule, "EAP schedule map cannot be null");
checkArgument(
eapFeeSchedule.values().stream().allMatch(Money::isPositiveOrZero),
"EAP fee cannot be negative");
getInstance().eapFeeSchedule =
TimedTransitionProperty.fromValueMap(eapFeeSchedule, BillingCostTransition.class);
return this;
}
private static final Pattern ROID_SUFFIX_PATTERN = Pattern.compile("^[A-Z0-9_]{1,8}$");
public Builder setRoidSuffix(String roidSuffix) {
checkArgument(
ROID_SUFFIX_PATTERN.matcher(roidSuffix).matches(),
"ROID suffix must be in format %s",
ROID_SUFFIX_PATTERN.pattern());
getInstance().roidSuffix = roidSuffix;
return this;
}
public Builder setServerStatusChangeBillingCost(Money amount) {
checkArgument(
amount.isPositiveOrZero(), "Server status change billing cost cannot be negative");
getInstance().serverStatusChangeBillingCost = amount;
return this;
}
public Builder setRegistryLockOrUnlockBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "Registry lock/unlock cost cannot be negative");
getInstance().registryLockOrUnlockBillingCost = amount;
return this;
}
public Builder setLordnUsername(String username) {
getInstance().lordnUsername = username;
return this;
}
public Builder setClaimsPeriodEnd(DateTime claimsPeriodEnd) {
getInstance().claimsPeriodEnd = checkArgumentNotNull(claimsPeriodEnd);
return this;
}
public Builder setAllowedRegistrantContactIds(
ImmutableSet<String> allowedRegistrantContactIds) {
getInstance().allowedRegistrantContactIds = allowedRegistrantContactIds;
return this;
}
public Builder setAllowedFullyQualifiedHostNames(
ImmutableSet<String> allowedFullyQualifiedHostNames) {
getInstance().allowedFullyQualifiedHostNames = allowedFullyQualifiedHostNames;
return this;
}
@Override
public Registry build() {
final Registry instance = getInstance();
// Pick up the name of the associated TLD from the instance object.
String tldName = instance.tldStr;
checkArgument(tldName != null, "No registry TLD specified");
// Check for canonical form by converting to an InternetDomainName and then back.
checkArgument(
InternetDomainName.isValid(tldName)
&& tldName.equals(InternetDomainName.from(tldName).toString()),
"Cannot create registry for TLD that is not a valid, canonical domain name");
// Check the validity of all TimedTransitionProperties to ensure that they have values for
// START_OF_TIME. The setters above have already checked this for new values, but also check
// here to catch cases where we loaded an invalid TimedTransitionProperty from Datastore and
// cloned it into a new builder, to block re-building a Registry in an invalid state.
instance.tldStateTransitions.checkValidity();
instance.renewBillingCostTransitions.checkValidity();
instance.eapFeeSchedule.checkValidity();
// All costs must be in the expected currency.
// TODO(b/21854155): When we move PremiumList into Datastore, verify its currency too.
checkArgument(
instance.getStandardCreateCost().getCurrencyUnit().equals(instance.currency),
"Create cost must be in the registry's currency");
checkArgument(
instance.getStandardRestoreCost().getCurrencyUnit().equals(instance.currency),
"Restore cost must be in the registry's currency");
checkArgument(
instance.getServerStatusChangeCost().getCurrencyUnit().equals(instance.currency),
"Server status change cost must be in the registry's currency");
checkArgument(
instance.getRegistryLockOrUnlockBillingCost().getCurrencyUnit().equals(instance.currency),
"Registry lock/unlock cost must be in the registry's currency");
Predicate<Money> currencyCheck =
(Money money) -> money.getCurrencyUnit().equals(instance.currency);
checkArgument(
instance.getRenewBillingCostTransitions().values().stream().allMatch(currencyCheck),
"Renew cost must be in the registry's currency");
checkArgument(
instance.eapFeeSchedule.toValueMap().values().stream().allMatch(currencyCheck),
"All EAP fees must be in the registry's currency");
checkArgumentNotNull(
instance.pricingEngineClassName, "All registries must have a configured pricing engine");
checkArgument(
instance.dnsWriters != null && !instance.dnsWriters.isEmpty(),
"At least one DNS writer must be specified."
+ " VoidDnsWriter can be used if DNS writing isn't desired");
// If not set explicitly, numDnsPublishLocks defaults to 1.
instance.setDefaultNumDnsPublishLocks();
checkArgument(
instance.numDnsPublishLocks > 0,
"Number of DNS publish locks must be positive. Use 1 for TLD-wide locks.");
instance.tldStrId = tldName;
instance.tldUnicode = Idn.toUnicode(tldName);
return super.build();
}
}
/** Exception to throw when no Registry entity is found for given TLD string(s). */
public static class RegistryNotFoundException extends RuntimeException {
RegistryNotFoundException(ImmutableSet<String> tlds) {
super("No registry object(s) found for " + Joiner.on(", ").join(tlds));
}
RegistryNotFoundException(String tld) {
this(ImmutableSet.of(tld));
}
}
}
| google/nomulus | core/src/main/java/google/registry/model/tld/Registry.java | Java | apache-2.0 | 40,835 |
import java.util.Scanner;
/**
* @author Oleg Cherednik
* @since 27.10.2017
*/
public class Solution {
static int[] leftRotation(int[] a, int d) {
for (int i = 0, j = a.length - 1; i < j; i++, j--)
swap(a, i, j);
d %= a.length;
if (d > 0) {
d = a.length - d;
for (int i = 0, j = d - 1; i < j; i++, j--)
swap(a, i, j);
for (int i = d, j = a.length - 1; i < j; i++, j--)
swap(a, i, j);
}
return a;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int[] a = new int[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
int[] result = leftRotation(a, d);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + (i != result.length - 1 ? " " : ""));
}
System.out.println("");
in.close();
}
}
| oleg-cherednik/hackerrank | Data Structures/Arrays/Left Rotation/Solution.java | Java | apache-2.0 | 1,184 |
package com.pmis.manage.dao;
import org.springframework.stereotype.Component;
import com.pmis.common.dao.CommonDao;
@Component
public class UserInfoDao extends CommonDao{
}
| twosunnus/zhcy | src/com/pmis/manage/dao/UserInfoDao.java | Java | apache-2.0 | 193 |
/**
* Licensed to Odiago, Inc. under one or more contributor license
* agreements. See the NOTICE.txt file distributed with this work for
* additional information regarding copyright ownership. Odiago, Inc.
* licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.odiago.flumebase.lang;
import java.util.Collections;
import java.util.List;
/**
* Abstract base class that defines a callable function. Subclasses
* of this exist for scalar, aggregate, and table functions.
*/
public abstract class Function {
/**
* @return the Type of the object returned by the function.
*/
public abstract Type getReturnType();
/**
* @return an ordered list containing the types expected for all mandatory arguments.
*/
public abstract List<Type> getArgumentTypes();
/**
* @return an ordered list containing types expected for variable argument lists.
* If a function takes a variable-length argument list, the varargs must be arranged
* in groups matching the size of the list returned by this method. e.g., to accept
* an arbitrary number of strings, this should return a singleton list of type STRING.
* If pairs of strings and ints are required, this should return a list [STRING, INT].
*/
public List<Type> getVarArgTypes() {
return Collections.emptyList();
}
/**
* Determines whether arguments are promoted to their specified types by
* the runtime. If this returns true, actual arguments are promoted to
* new values that match the types specified in getArgumentTypes().
* If false, the expressions are simply type-checked to ensure that there
* is a valid promotion, but are passed in as-is. The default value of
* this method is true.
*/
public boolean autoPromoteArguments() {
return true;
}
}
| flumebase/flumebase | src/main/java/com/odiago/flumebase/lang/Function.java | Java | apache-2.0 | 2,315 |
/**
* Copyright 2016 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 io.reactivex.internal.operators.maybe;
import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;
/**
* Turns an onSuccess into an onComplete, onError and onComplete is relayed as is.
*
* @param <T> the value type
*/
public final class MaybeIgnoreElement<T> extends AbstractMaybeWithUpstream<T, T> {
public MaybeIgnoreElement(MaybeSource<T> source) {
super(source);
}
@Override
protected void subscribeActual(MaybeObserver<? super T> observer) {
source.subscribe(new IgnoreMaybeObserver<T>(observer));
}
static final class IgnoreMaybeObserver<T> implements MaybeObserver<T>, Disposable {
final MaybeObserver<? super T> actual;
Disposable d;
IgnoreMaybeObserver(MaybeObserver<? super T> actual) {
this.actual = actual;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.d, d)) {
this.d = d;
actual.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public void onError(Throwable e) {
d = DisposableHelper.DISPOSED;
actual.onError(e);
}
@Override
public void onComplete() {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public boolean isDisposed() {
return d.isDisposed();
}
@Override
public void dispose() {
d.dispose();
d = DisposableHelper.DISPOSED;
}
}
}
| benjchristensen/RxJava | src/main/java/io/reactivex/internal/operators/maybe/MaybeIgnoreElement.java | Java | apache-2.0 | 2,368 |
package com.intellij.util.xml.impl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.NullableFactory;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.DomNameStrategy;
import com.intellij.util.xml.EvaluatedXmlName;
import com.intellij.util.xml.stubs.ElementStub;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
/**
* @author peter
*/
public class DomRootInvocationHandler extends DomInvocationHandler<AbstractDomChildDescriptionImpl, ElementStub> {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.impl.DomRootInvocationHandler");
private final DomFileElementImpl<?> myParent;
public DomRootInvocationHandler(final Class aClass,
final RootDomParentStrategy strategy,
@Nonnull final DomFileElementImpl fileElement,
@Nonnull final EvaluatedXmlName tagName,
@Nullable ElementStub stub
) {
super(aClass, strategy, tagName, new AbstractDomChildDescriptionImpl(aClass) {
@Nonnull
public List<? extends DomElement> getValues(@Nonnull final DomElement parent) {
throw new UnsupportedOperationException();
}
public int compareTo(final AbstractDomChildDescriptionImpl o) {
throw new UnsupportedOperationException();
}
}, fileElement.getManager(), true, stub);
myParent = fileElement;
}
public void undefineInternal() {
try {
final XmlTag tag = getXmlTag();
if (tag != null) {
deleteTag(tag);
detach();
fireUndefinedEvent();
}
}
catch (Exception e) {
LOG.error(e);
}
}
public boolean equals(final Object obj) {
if (!(obj instanceof DomRootInvocationHandler)) return false;
final DomRootInvocationHandler handler = (DomRootInvocationHandler)obj;
return myParent.equals(handler.myParent);
}
public int hashCode() {
return myParent.hashCode();
}
@Nonnull
public String getXmlElementNamespace() {
return getXmlName().getNamespace(getFile(), getFile());
}
@Override
protected String checkValidity() {
final XmlTag tag = (XmlTag)getXmlElement();
if (tag != null && !tag.isValid()) {
return "invalid root tag";
}
final String s = myParent.checkValidity();
if (s != null) {
return "root: " + s;
}
return null;
}
@Nonnull
public DomFileElementImpl getParent() {
return myParent;
}
public DomElement createPathStableCopy() {
final DomFileElement stableCopy = myParent.createStableCopy();
return getManager().createStableValue(new NullableFactory<DomElement>() {
public DomElement create() {
return stableCopy.isValid() ? stableCopy.getRootElement() : null;
}
});
}
protected XmlTag setEmptyXmlTag() {
final XmlTag[] result = new XmlTag[]{null};
getManager().runChange(new Runnable() {
public void run() {
try {
final String namespace = getXmlElementNamespace();
@NonNls final String nsDecl = StringUtil.isEmpty(namespace) ? "" : " xmlns=\"" + namespace + "\"";
final XmlFile xmlFile = getFile();
final XmlTag tag = XmlElementFactory.getInstance(xmlFile.getProject()).createTagFromText("<" + getXmlElementName() + nsDecl + "/>");
result[0] = ((XmlDocument)xmlFile.getDocument().replace(((XmlFile)tag.getContainingFile()).getDocument())).getRootTag();
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
});
return result[0];
}
@Nonnull
public final DomNameStrategy getNameStrategy() {
final Class<?> rawType = getRawType();
final DomNameStrategy strategy = DomImplUtil.getDomNameStrategy(rawType, isAttribute());
if (strategy != null) {
return strategy;
}
return DomNameStrategy.HYPHEN_STRATEGY;
}
}
| consulo/consulo-xml | xml-dom-impl/src/main/java/com/intellij/util/xml/impl/DomRootInvocationHandler.java | Java | apache-2.0 | 4,330 |
package org.consumersunion.stories.common.client.util;
public class CachedObjectKeys {
public static final String OPENED_CONTENT = "openedContent";
public static final String OPENED_STORY = "openedStory";
public static final String OPENED_COLLECTION = "openedCollection";
}
| stori-es/stori_es | dashboard/src/main/java/org/consumersunion/stories/common/client/util/CachedObjectKeys.java | Java | apache-2.0 | 287 |
package dkalymbaev.triangle;
class Triangle {
/**
* This class defines points a b and c as peacks of triangle.
*/
public Point a;
public Point b;
public Point c;
/**
* Creating of a new objects.
* @param a is the length of the first side.
* @param b is the length of the second side.
* @param c is the length of the third side.
*/
public Triangle(Point a, Point b, Point c) {
this.a = a;
this.b = b;
this.c = c;
}
public double area() {
double ab = a.distanceTo(b);
double bc = b.distanceTo(c);
double ac = a.distanceTo(c);
double halfperim = ((ab + bc + ac) / 2);
double area = Math.sqrt(halfperim * (halfperim - ab) * (halfperim - bc) * (halfperim - ac));
if (ab > 0 && bc > 0 && ac > 0) {
return area;
} else {
return 0;
}
}
} | Damir2805/java-a-to-z | Chapter_001/src/main/java/dkalymbaev/triangle/Triangle.java | Java | apache-2.0 | 783 |
/*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2019] EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ensembl.healthcheck.util;
import java.util.HashMap;
import java.util.Map;
/**
* A default implementation of the {@link MapRowMapper} intended as an
* extension point to help when creating these call back objects. This version
* will return a HashMap of the given generic types.
*
* @author ayates
* @author dstaines
*/
public abstract class AbstractMapRowMapper<K, T> implements MapRowMapper<K, T>{
public Map<K, T> getMap() {
return new HashMap<K,T>();
}
}
| Ensembl/ensj-healthcheck | src/org/ensembl/healthcheck/util/AbstractMapRowMapper.java | Java | apache-2.0 | 1,222 |
package com.linbo.algs.examples.queues;
import java.util.Iterator;
import com.linbo.algs.util.StdRandom;
/**
* Created by @linbojin on 13/1/17.
* Ref: http://coursera.cs.princeton.edu/algs4/assignments/queues.html
* RandomizedQueue: a double-ended queue or deque (pronounced "deck") is a
* generalization of a stack and a queue that supports adding and removing
* items from either the front or the back of the data structure.
*/
public class RandomizedQueue<Item> implements Iterable<Item> {
// Memory: 16 + 8 + 4 + 4 + 4 + 4 + 24 + N * 4 * 2
// = 64 + 8N
private Item[] q; // queue elements
private int size; // number of elements on queue
private int first; // index of first element of queue
private int last; // index of next available slot
// construct an empty randomized queue
public RandomizedQueue() {
q = (Item[]) new Object[2];
size = 0;
first = 0;
last = 0;
}
// is the queue empty?
public boolean isEmpty() {
return size == 0;
}
// return the number of items on the queue
public int size() {
return size;
}
// resize the underlying array
private void resize(int capacity) {
assert capacity >= size;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < size; i++) {
temp[i] = q[(first + i) % q.length];
}
q = temp;
first = 0;
last = size;
}
// add the item
public void enqueue(Item item) {
if (item == null) {
throw new java.lang.NullPointerException("Input item can not be null!");
}
// double size of array if necessary and recopy to front of array
if (size == q.length) resize(2 * q.length); // double size of array if necessary
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
size++;
}
// remove and return a random item
public Item dequeue() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Queue is empty!");
}
int index = StdRandom.uniform(size) + first;
int i = index % q.length;
Item item = q[i];
last = (last + q.length - 1) % q.length;
if (i != last) {
q[i] = q[last];
}
q[last] = null;
size--;
// shrink size of array if necessary
if (size > 0 && size == q.length / 4) resize(q.length / 2);
return item;
}
// return (but do not remove) a random item
public Item sample() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Queue is empty!");
}
int index = StdRandom.uniform(size) + first;
return q[index % q.length];
}
// an independent iterator over items in random order
public Iterator<Item> iterator() {
return new ArrayIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
private int[] inxArr;
public ArrayIterator() {
inxArr = StdRandom.permutation(size);
}
public boolean hasNext() {
return i < size;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new java.util.NoSuchElementException();
Item item = q[(inxArr[i] + first) % q.length];
i++;
return item;
}
}
// unit testing (optional)
public static void main(String[] args) {
RandomizedQueue<Integer> rq = new RandomizedQueue<Integer>();
System.out.println(rq.isEmpty());
rq.enqueue(1);
rq.enqueue(2);
rq.enqueue(3);
rq.enqueue(4);
rq.enqueue(5);
for (int i : rq) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("\n*******");
System.out.println(rq.sample());
System.out.println(rq.size()); // 5
System.out.println("*******");
System.out.println(rq.isEmpty());
System.out.println(rq.dequeue());
System.out.println(rq.dequeue());
System.out.println(rq.sample());
System.out.println(rq.size()); // 3
System.out.println("*******");
System.out.println(rq.dequeue());
System.out.println(rq.dequeue());
System.out.println(rq.size()); // 1
System.out.println("*******");
System.out.println(rq.sample());
System.out.println(rq.dequeue());
System.out.println(rq.size()); // 0
System.out.println("*******");
RandomizedQueue<Integer> rqOne = new RandomizedQueue<Integer>();
System.out.println(rq.size());
rq.enqueue(4);
System.out.println(rq.size());
rq.enqueue(5);
System.out.println(rq.dequeue());
}
}
| linbojin/algorithms | java/src/main/java/com/linbo/algs/examples/queues/RandomizedQueue.java | Java | apache-2.0 | 4,619 |
/*
* 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.xerces.impl.scd;
import java.util.ArrayList;
import java.util.List;
import org.apache.xerces.util.NamespaceSupport;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.util.XML11Char;
//import org.apache.xml.serializer.utils.XML11Char;
/**
* This class handles the parsing of relative/incomplete SCDs/SCPs
* @author Ishan Jayawardena udeshike@gmail.com
* @version $Id$
*/
class SCDParser {
private List steps;
private static final int CHARTYPE_AT = 1; // @
private static final int CHARTYPE_TILDE = 2; // ~
private static final int CHARTYPE_PERIOD = 3; // .
private static final int CHARTYPE_STAR = 4; // *
private static final int CHARTYPE_ZERO = 5; // 0
private static final int CHARTYPE_1_THROUGH_9 = 6; // [1-9]
private static final int CHARTYPE_NC_NAMESTART = 7; // XML11Char.NCNameStart
private static final int CHARTYPE_NC_NAME = 8; // XML11Char.NCName
private static final int CHARTYPE_OPEN_BRACKET = 9; // [
private static final int CHARTYPE_CLOSE_BRACKET = 10;// ]
private static final int CHARTYPE_OPEN_PAREN = 11; // (
private static final int CHARTYPE_CLOSE_PAREN = 12; // )
private static final int CHARTYPE_COLON = 13; // :
private static final int CHARTYPE_SLASH = 14; // /
private static final int CHARTYPE_NOMORE = 0;
private static final short LIST_SIZE = 15;
public SCDParser() {
steps = new ArrayList(LIST_SIZE);
}
private static int getCharType(int c) throws SCDException {
switch (c) {
case '@':
return CHARTYPE_AT;
case '~':
return CHARTYPE_TILDE;
case '.':
return CHARTYPE_PERIOD;
case '*':
return CHARTYPE_STAR;
case ':':
return CHARTYPE_COLON;
case '/':
return CHARTYPE_SLASH;
case '(':
return CHARTYPE_OPEN_PAREN;
case ')':
return CHARTYPE_CLOSE_PAREN;
case '[':
return CHARTYPE_OPEN_BRACKET;
case ']':
return CHARTYPE_CLOSE_BRACKET;
case '0':
return CHARTYPE_ZERO;
}
if (c == CHARTYPE_NOMORE) {
return CHARTYPE_NOMORE;
}
if (c >= '1' && c <= '9') {
return CHARTYPE_1_THROUGH_9;
}
if (XML11Char.isXML11NCNameStart(c)) {
return CHARTYPE_NC_NAMESTART;
}
if (XML11Char.isXML11NCName(c)) {
return CHARTYPE_NC_NAME;
}
throw new SCDException("Error in SCP: Unsupported character "
+ (char) c + " (" + c + ")");
}
public static char charAt(String s, int position) {
if (position >= s.length()) {
return (char) -1; // TODO: throw and exception instead?
//throw new SCDException("Error in SCP: No more characters in the SCP string");
}
return s.charAt(position);
}
private static QName readQName(String step, int[] finalPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
return readNameTest(step, finalPosition, currentPosition, nsContext);
}
/**
* TODO: this is the wild card name test
*/
public static final QName WILDCARD = new QName(null, "*", "*", null);
/**
* TODO: this is the name test zero
*/
public static final QName ZERO = new QName(null, "0", "0", null);
/*
* Similar to readQName() method. But this method additionally tests for another two types
* of name tests. i.e the wildcard name test and the zero name test.
*/
private static QName readNameTest(String step, int[] finalPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
int initialPosition = currentPosition;
int start = currentPosition;
String prefix = ""; // for the default namespace
String localPart = null;
if (charAt(step, currentPosition) == '*') {
finalPosition[0] = currentPosition + 1;
return WILDCARD;
} else if (charAt(step, currentPosition) == '0') {
finalPosition[0] = currentPosition + 1;
return ZERO;
// prefix, localPart, rawname, uri;
} else if (XML11Char.isXML11NCNameStart(charAt(step, currentPosition))) {
while (XML11Char.isXML11NCName(charAt(step, ++currentPosition))) {}
prefix = step.substring(initialPosition, currentPosition);
if (charAt(step, currentPosition) == ':') {
if (XML11Char
.isXML11NCNameStart(charAt(step, ++currentPosition))) {
initialPosition = currentPosition;
while (XML11Char.isXML11NCName(charAt(step,
currentPosition++))) {
}
localPart = step.substring(initialPosition,
currentPosition - 1);
}
if (localPart == null) {
localPart = prefix;
prefix = "";
}
finalPosition[0] = currentPosition - 1;
} else {
finalPosition[0] = currentPosition;
localPart = prefix;
prefix = "";
}
String rawname = step.substring(start, finalPosition[0]);
if (nsContext != null) {
// it a field
String uri = nsContext.getURI(prefix.intern());
if ("".equals(prefix)) { // default namespace.
return new QName(prefix, localPart, rawname, uri);
} else if (uri != null) {
// just use uri != null test here!
return new QName(prefix, localPart, rawname, uri);
}
throw new SCDException("Error in SCP: The prefix \"" + prefix
+ "\" is undeclared in this context");
}
throw new SCDException("Error in SCP: Namespace context is null");
}
throw new SCDException("Error in SCP: Invalid nametest starting character \'"
+ charAt(step, currentPosition) + "\'");
} // readNameTest()
private static int scanNCName(String data, int currentPosition) {
if (XML11Char.isXML11NCNameStart(charAt(data, currentPosition))) {
while (XML11Char.isXML11NCName(charAt(data, ++currentPosition))) {
}
}
return currentPosition;
}
/* scans a XML namespace Scheme Data section
* [2] EscapedNamespaceName ::= EscapedData*
* [6] SchemeData ::= EscapedData*
* [7] EscapedData ::= NormalChar | '^(' | '^)' | '^^' | '(' SchemeData ')'
* [8] NormalChar ::= UnicodeChar - [()^]
* [9] UnicodeChar ::= [#x0-#x10FFFF]
*/
private static int scanXmlnsSchemeData(String data, int currentPosition) throws SCDException {
int c = 0;
int balanceParen = 0;
do {
c = charAt(data, currentPosition);
if (c >= 0x0 && c <= 0x10FFFF) { // unicode char
if (c != '^') { // normal char
++currentPosition;
if (c == '(') {
++balanceParen;
} else if (c == ')') { // can`t be empty '(' xmlnsSchemeData ')'
--balanceParen;
if (balanceParen == -1) {
// this is the end
return currentPosition - 1;
}
if (charAt(data, currentPosition - 2) == '(') {
throw new SCDException(
"Error in SCD: empty xmlns scheme data between '(' and ')'");
}
}
} else { // check if '^' is used as an escape char
if (charAt(data, currentPosition + 1) == '('
|| charAt(data, currentPosition + 1) == ')'
|| charAt(data, currentPosition + 1) == '^') {
currentPosition = currentPosition + 2;
} else {
throw new SCDException("Error in SCD: \'^\' character is used as a non escape character at position "
+ ++currentPosition);
}
}
} else {
throw new SCDException("Error in SCD: the character \'" + c + "\' at position "
+ ++currentPosition + " is invalid for xmlns scheme data");
}
} while (currentPosition < data.length());
String s = "";
if (balanceParen != -1) { // checks unbalanced l parens only.
s = "Unbalanced parentheses exist within xmlns scheme data section";
}
throw new SCDException("Error in SCD: Attempt to read an invalid xmlns Scheme data. " + s);
}
private static int skipWhiteSpaces(String data, int currentPosition) {
while (XML11Char.isXML11Space(charAt(data, currentPosition))) {
++currentPosition; // this is important
}
return currentPosition;
}
// Scans a predicate from the input string step
private static int readPredicate(String step, int[] finalPosition,
int currentPosition) throws SCDException {
// we've already seen a '['
int end = step.indexOf(']', currentPosition);
if (end >= 0) {
try {
int i = Integer.parseInt(step.substring(currentPosition, end)); // toString?
if (i > 0) {
finalPosition[0] = end + 1;
return i;
}
throw new SCDException("Error in SCP: Invalid predicate value "
+ i);
} catch (NumberFormatException e) {
e.printStackTrace();
throw new SCDException(
"Error in SCP: A NumberFormatException occurred while reading the predicate");
}
}
throw new SCDException(
"Error in SCP: Attempt to read an invalid predicate starting from position "
+ ++currentPosition);
} // readPredicate()
/**
* Processes the scp input string and seperates it into Steps
* @param scp the input string that contains an SCDParser
* @return a list of Steps contained in the SCDParser
*/
public List parseSCP(String scp, NamespaceContext nsContext, boolean isRelative)
throws SCDException {
steps.clear();
Step step;
if (scp.length() == 1 && scp.charAt(0) == '/') { // read a schema
// schema step.
//System.out.println("<SCHEMA STEP>");
steps.add(new Step(Axis.NO_AXIS, null, 0));
return steps;
}
// check if this is an incomplete SCP
if (isRelative) {
if ("./".equals(scp.substring(0, 2))) {
scp = scp.substring(1);
} else if (scp.charAt(0) != '/') {
scp = '/' + scp;
} else {
throw new SCDException("Error in incomplete SCP: Invalid starting character");
}
}
int stepStart = 0;
int[] currentPosition = new int[] { 0 };
while (currentPosition[0] < scp.length()) {
if (charAt(scp, currentPosition[0]) == '/') {
if (charAt(scp, currentPosition[0] + 1) == '/') {
if (currentPosition[0] + 1 != scp.length() - 1) {
steps.add(new Step(Axis.SPECIAL_COMPONENT, WILDCARD, 0));
stepStart = currentPosition[0] + 2;
} else {
stepStart = currentPosition[0] + 1;
}
} else {
if (currentPosition[0] != scp.length() - 1) {
stepStart = currentPosition[0] + 1;
} else {
stepStart = currentPosition[0];
}
}
step = processStep(scp, currentPosition, stepStart, nsContext);
steps.add(step);
} else { // error: invalid scp. should start with a slash
throw new SCDException("Error in SCP: Invalid character \'"
+ charAt(scp, currentPosition[0]) + " \' at position"
+ currentPosition[0]);
}
}
return steps;
}
private static Step processStep(String step, int[] newPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
short axis = -1;
QName nameTest = null;
int predicate = 0;
switch (getCharType(charAt(step, currentPosition))) { // 0
case CHARTYPE_AT: // '@'
axis = Axis.SCHEMA_ATTRIBUTE;
nameTest = readNameTest(step, newPosition, currentPosition + 1,
nsContext); // 1 handles *, 0, and QNames.
break;
case CHARTYPE_TILDE: // '~'
axis = Axis.TYPE;
nameTest = readNameTest(step, newPosition, currentPosition + 1,
nsContext); // 1
break;
case CHARTYPE_PERIOD: // '.'
axis = Axis.CURRENT_COMPONENT;
nameTest = WILDCARD;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_ZERO: // '0'
axis = Axis.SCHEMA_ELEMENT; // Element without a name. This will
// never match anything.
nameTest = ZERO;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_STAR: // '*'
axis = Axis.SCHEMA_ELEMENT;
nameTest = WILDCARD;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_NC_NAMESTART: // isXML11NCNameStart()
QName name = readQName(step, newPosition, currentPosition,
nsContext); // 0 handles a and a:b
int newPos = newPosition[0];
if (newPosition[0] == step.length()) {
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
} else if (charAt(step, newPos) == ':'
&& charAt(step, newPos + 1) == ':') {
// TODO: what to do with extension axes?
// Could be a hashtable look up; fail if extension axis
axis = Axis.qnameToAxis(name.rawname);
if (axis == Axis.EXTENSION_AXIS) {
throw new SCDException(
"Error in SCP: Extension axis {"+name.rawname+"} not supported!");
}
nameTest = readNameTest(step, newPosition, newPos + 2,
nsContext);
} else if (charAt(step, newPos) == '(') {
throw new SCDException(
"Error in SCP: Extension accessor not supported!");
} else if (charAt(step, newPos) == '/') { // /abc:def/...
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
return new Step(axis, nameTest, predicate);
} else { // /abc:def[6]
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
}
break;
default:
throw new SCDException("Error in SCP: Invalid character \'"
+ charAt(step, currentPosition) + "\' at position "
+ currentPosition);
}
if (newPosition[0] < step.length()) {
if (charAt(step, newPosition[0]) == '[') {
predicate = readPredicate(step, newPosition, newPosition[0] + 1); // Also consumes right-bracket
} else if (charAt(step, newPosition[0]) == '/') { // /a::a/a...
return new Step(axis, nameTest, predicate);
} else {
throw new SCDException("Error in SCP: Unexpected character \'"
+ charAt(step, newPosition[0]) + "\' at position "
+ newPosition[0]);
}
// TODO: handle what if not?
}
if (charAt(step, newPosition[0]) == '/') {// /abc:def[6]/...
return new Step(axis, nameTest, predicate);
}
if (newPosition[0] < step.length()) {
throw new SCDException("Error in SCP: Unexpected character \'"
+ step.charAt(newPosition[0]) + "\' at the end");
}
return new Step(axis, nameTest, predicate);
} // processStep()
/**
* Creates a list of Step objects from the input relative SCD string by
* parsing it
* @param relativeSCD
* @param isIncompleteSCD if the relative SCD in the first parameter an incomplete SCD
* @return the list of Step objects
*/
public List parseRelativeSCD(String relativeSCD, boolean isIncompleteSCD) throws SCDException {
// xmlns(p=http://example.com/schema/po)xscd(/type::p:USAddress)
int[] currentPosition = new int[] { 0 };
NamespaceContext nsContext = new NamespaceSupport();
//System.out.println("Relative SCD## " + relativeSCD);
while (currentPosition[0] < relativeSCD.length()) {
if ("xmlns".equals(relativeSCD.substring(currentPosition[0], currentPosition[0] + 5))) { // TODO catch string out of bound exception
currentPosition[0] = readxmlns(relativeSCD, nsContext, currentPosition[0] + 5);
} else if ("xscd".equals(relativeSCD.substring(currentPosition[0], currentPosition[0] + 4))) { // (/type::p:USAddress) part
// process xscd() part
String data = relativeSCD.substring(currentPosition[0] + 4, relativeSCD.length());
if (charAt(data, 0) == '('
&& charAt(data, data.length() - 1) == ')') {
return parseSCP(data.substring(1, data.length() - 1), nsContext, isIncompleteSCD);
}
throw new SCDException("Error in SCD: xscd() part is invalid at position "
+ ++currentPosition[0]);
} else {
throw new SCDException("Error in SCD: Expected \'xmlns\' or \'xscd\' at position "
+ ++currentPosition[0]);
}
}
throw new SCDException("Error in SCD: Error at position "
+ ++currentPosition[0]);
} // createSteps()
private static int readxmlns(String data, NamespaceContext nsContext,
int currentPosition) throws SCDException {
if (charAt(data, currentPosition++) == '(') {
// readNCName
int pos = currentPosition;
currentPosition = scanNCName(data, currentPosition);
if (currentPosition == pos) {
throw new SCDException(
"Error in SCD: Missing namespace name at position "
+ ++currentPosition);
}
String name = data.substring(pos, currentPosition);
// skip S
currentPosition = skipWhiteSpaces(data, currentPosition);
// read '='
if (charAt(data, currentPosition) != '=') {
throw new SCDException("Error in SCD: Expected a \'=\' character at position "
+ ++currentPosition);
}
// skip S
currentPosition = skipWhiteSpaces(data, ++currentPosition);
// read uri
pos = currentPosition;
currentPosition = scanXmlnsSchemeData(data, currentPosition);
if (currentPosition == pos) {
throw new SCDException("Error in SCD: Missing namespace value at position "
+ ++currentPosition);
}
String uri = data.substring(pos, currentPosition);
if (charAt(data, currentPosition) == ')') {
nsContext.declarePrefix(name.intern(), uri.intern());
return ++currentPosition;
}
throw new SCDException("Error in SCD: Invalid xmlns pointer part at position "
+ ++currentPosition);
}
throw new SCDException("Error in SCD: Invalid xmlns pointer part at position "
+ ++currentPosition);
} // readxmlns()
}
| RackerWilliams/xercesj | src/org/apache/xerces/impl/scd/SCDParser.java | Java | apache-2.0 | 21,399 |
/*
Copyright 2011 LinkedIn Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.linkedin.sample;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.*;
import org.scribe.oauth.OAuthService;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static final String PROTECTED_RESOURCE_URL = "http://api.linkedin.com/v1/people/~/connections:(y,last-name)";
private static String API_KEY = "77mahxt83mbma8";
private static String API_SECRET = "vpSWVa01dWq4dFfO";
public static void main(String[] args) {
/*
we need a OAuthService to handle authentication and the subsequent calls.
Since we are going to use the REST APIs we need to generate a request token as the first step in the call.
Once we get an access toke we can continue to use that until the API key changes or auth is revoked.
Therefore, to make this sample easier to re-use we serialize the AuthHandler (which stores the access token) to
disk and then reuse it.
When you first run this code please insure that you fill in the API_KEY and API_SECRET above with your own
credentials and if there is a service.dat file in the code please delete it.
*/
//The Access Token is used in all Data calls to the APIs - it basically says our application has been given access
//to the approved information in LinkedIn
//Token accessToken = null;
//Using the Scribe library we enter the information needed to begin the chain of Oauth2 calls.
OAuthService service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.build();
/*************************************
* This first piece of code handles all the pieces needed to be granted access to make a data call
*/
Scanner in = new Scanner(System.in);
System.out.println("=== LinkedIn's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
/*try{
File file = new File("service.txt");
if(file.exists()){
//if the file exists we assume it has the AuthHandler in it - which in turn contains the Access Token
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
AuthHandler authHandler = (AuthHandler) inputStream.readObject();
accessToken = authHandler.getAccessToken();
} else {
System.out.println("There is no stored Access token we need to make one");
//In the constructor the AuthHandler goes through the chain of calls to create an Access Token
AuthHandler authHandler = new AuthHandler(service);
System.out.println("test");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("service.txt"));
outputStream.writeObject( authHandler);
outputStream.close();
accessToken = authHandler.getAccessToken();
}
}catch (Exception e){
System.out.println("Threw an exception when serializing: " + e.getClass() + " :: " + e.getMessage());
}
*//*
* We are all done getting access - time to get busy getting data
*************************************//*
*//**************************
*
* Querying the LinkedIn API
*
**************************//*
System.out.println();
System.out.println("********A basic user profile call********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/profile-api
String url = "http://api.linkedin.com/v1/people/~";
OAuthRequest request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get the profile in JSON********");
//This basic call profile in JSON format
//You can read more about JSON here http://json.org
url = "http://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
request.addHeader("x-li-format", "json");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get the profile in JSON using query parameter********");
//This basic call profile in JSON format. Please note the call above is the preferred method.
//You can read more about JSON here http://json.org
url = "http://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("format", "json");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get my connections - going into a resource********");
//This basic call gets all your connections each one will be in a person tag with some profile information
//https://developer.linkedin.com/documents/connections-api
url = "http://api.linkedin.com/v1/people/~/connections";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get only 10 connections - using parameters********");
//This basic call gets only 10 connections - each one will be in a person tag with some profile information
//https://developer.linkedin.com/documents/connections-api
//more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string
url = "http://api.linkedin.com/v1/people/~/connections";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("count", "10");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********GET network updates that are CONN and SHAR********");
//This basic call get connection updates from your connections
//https://developer.linkedin.com/documents/get-network-updates-and-statistics-api
//specifics on updates https://developer.linkedin.com/documents/network-update-types
url = "http://api.linkedin.com/v1/people/~/network/updates";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("type","SHAR");
request.addQuerystringParameter("type","CONN");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********");
//This basic call get connection updates from your connections
//https://developer.linkedin.com/documents/people-search-api#Facets
//Why doesn't this look like
//people-search?title=developer&location=fr&industry=4
//url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0";
url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("title", "Développeur");
request.addQuerystringParameter("facet", "industry,4");
request.addQuerystringParameter("facets", "location,industry");
System.out.println(request.getUrl());
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
/////////////////field selectors
System.out.println("********A basic user profile call with field selectors********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/field-selectors
url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A basic user profile call with field selectors going into a subresource********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/field-selectors
url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A basic user profile call into a subresource return data in JSON********");
//The ~ means yourself - so this should return the basic default information for your profile
//https://developer.linkedin.com/documents/field-selectors
url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A more complicated example using postings into groups********");
//https://developer.linkedin.com/documents/field-selectors
//https://developer.linkedin.com/documents/groups-api
url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();*/
/**************************
*
* Wrting to the LinkedIn API
*
**************************/
/*
* Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out
* some code. Uncomment if you'd like to see writes in action.
*
*
System.out.println("********Write to the share - using XML********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addHeader("Content-Type", "text/xml");
//Make an XML document
Document doc = DocumentHelper.createDocument();
Element share = doc.addElement("share");
share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs");
Element content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
share.addElement("visibility").addElement("code").addText("anyone");
request.addPayload(doc.asXML());
service.signRequest(accessToken, request);
response = request.send();
//there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
System.out.println("********Write to the share and to Twitter - using XML********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addQuerystringParameter("twitter-post","true");
request.addHeader("Content-Type", "text/xml");
//Make an XML document
doc = DocumentHelper.createDocument();
share = doc.addElement("share");
share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter");
content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
share.addElement("visibility").addElement("code").addText("anyone");
request.addPayload(doc.asXML());
service.signRequest(accessToken, request);
response = request.send();
//there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
System.out.println("********Write to the share and to twitter - using JSON ********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
//NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
//set the headers to the server knows what we are sending
request.addHeader("Content-Type", "application/json");
request.addHeader("x-li-format", "json");
//make the json payload using json-simple
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("comment", "Posting from the API using JSON");
JSONObject contentObject = new JSONObject();
contentObject.put("title", "This is a another test post");
contentObject.put("submitted-url","http://www.linkedin.com");
contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg");
jsonMap.put("content", contentObject);
JSONObject visibilityObject = new JSONObject();
visibilityObject.put("code", "anyone");
jsonMap.put("visibility", visibilityObject);
request.addPayload(JSONValue.toJSONString(jsonMap));
service.signRequest(accessToken, request);
response = request.send();
//again no body - just headers
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
*/
/**************************
*
* Understanding the response, creating logging, request and response headers
*
**************************/
/*System.out.println();
System.out.println("********A basic user profile call and response dissected********");
//This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle
//https://developer.linkedin.com/documents/debugging-api-calls
url = "https://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
//get all the headers
System.out.println("Request headers: " + request.getHeaders().toString());
System.out.println("Response headers: " + response.getHeaders().toString());
//url requested
System.out.println("Original location is: " + request.getHeaders().get("content-location"));
//Date of response
System.out.println("The datetime of the response is: " + response.getHeader("Date"));
//the format of the response
System.out.println("Format is: " + response.getHeader("x-li-format"));
//Content-type of the response
System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n");
//get the HTTP response code - such as 200 or 404
int responseNumber = response.getCode();
if(responseNumber >= 199 && responseNumber < 300){
System.out.println("HOORAY IT WORKED!!");
System.out.println(response.getBody());
} else if (responseNumber >= 500 && responseNumber < 600){
//you could actually raise an exception here in your own code
System.out.println("Ruh Roh application error of type 500: " + responseNumber);
System.out.println(response.getBody());
} else if (responseNumber == 403){
System.out.println("A 403 was returned which usually means you have reached a throttle limit");
} else if (responseNumber == 401){
System.out.println("A 401 was returned which is a Oauth signature error");
System.out.println(response.getBody());
} else if (responseNumber == 405){
System.out.println("A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc).");
}else {
System.out.println("We got a different response that we should add to the list: " + responseNumber + " and report it in the forums");
System.out.println(response.getBody());
}
System.out.println();System.out.println();
System.out.println("********A basic error logging function********");
// Now demonstrate how to make a logging function which provides us the info we need to
// properly help debug issues. Please use the logged block from here when requesting
// help in the forums.
url = "https://api.linkedin.com/v1/people/FOOBARBAZ";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
responseNumber = response.getCode();
if(responseNumber < 200 || responseNumber >= 300){
logDiagnostics(request, response);
} else {
System.out.println("You were supposed to submit a bad request");
}
System.out.println("******Finished******");
}
private static void logDiagnostics(OAuthRequest request, Response response){
System.out.println("\n\n[********************LinkedIn API Diagnostics**************************]\n");
System.out.println("Key: |-> " + API_KEY + " <-|");
System.out.println("\n|-> [******Sent*****] <-|");
System.out.println("Headers: |-> " + request.getHeaders().toString() + " <-|");
System.out.println("URL: |-> " + request.getUrl() + " <-|");
System.out.println("Query Params: |-> " + request.getQueryStringParams().toString() + " <-|");
System.out.println("Body Contents: |-> " + request.getBodyContents() + " <-|");
System.out.println("\n|-> [*****Received*****] <-|");
System.out.println("Headers: |-> " + response.getHeaders().toString() + " <-|");
System.out.println("Body: |-> " + response.getBody() + " <-|");
System.out.println("\n[******************End LinkedIn API Diagnostics************************]\n\n");
}*/
}
| smoothpanda1981/linkedin | java/src/com/linkedin/sample/Main.java | Java | apache-2.0 | 22,732 |
/*
* Copyright 2013 Square, Inc.
* Copyright 2016 PKWARE, 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.pkware.truth.androidx.appcompat.widget;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.SearchView;
import androidx.cursoradapter.widget.CursorAdapter;
import com.google.common.truth.FailureMetadata;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Propositions for {@link SearchView} subjects.
*/
public class SearchViewSubject extends AbstractLinearLayoutCompatSubject<SearchView> {
@Nullable
private final SearchView actual;
public SearchViewSubject(@Nonnull FailureMetadata failureMetadata, @Nullable SearchView actual) {
super(failureMetadata, actual);
this.actual = actual;
}
public void hasImeOptions(int options) {
check("getImeOptions()").that(actual.getImeOptions()).isEqualTo(options);
}
public void hasInputType(int type) {
check("getInputType()").that(actual.getInputType()).isEqualTo(type);
}
public void hasMaximumWidth(int width) {
check("getMaxWidth()").that(actual.getMaxWidth()).isEqualTo(width);
}
public void hasQuery(@Nullable String query) {
check("getQuery()").that(actual.getQuery().toString()).isEqualTo(query);
}
public void hasQueryHint(@Nullable String hint) {
CharSequence actualHint = actual.getQueryHint();
String actualHintString;
if (actualHint == null) {
actualHintString = null;
} else {
actualHintString = actualHint.toString();
}
check("getQueryHint()").that(actualHintString).isEqualTo(hint);
}
public void hasQueryHint(@StringRes int resId) {
hasQueryHint(actual.getContext().getString(resId));
}
public void hasSuggestionsAdapter(@Nullable CursorAdapter adapter) {
check("getSuggestionsAdapter()").that(actual.getSuggestionsAdapter()).isSameInstanceAs(adapter);
}
public void isIconifiedByDefault() {
check("isIconfiedByDefault()").that(actual.isIconfiedByDefault()).isTrue();
}
public void isNotIconifiedByDefault() {
check("isIconfiedByDefault()").that(actual.isIconfiedByDefault()).isFalse();
}
public void isIconified() {
check("isIconified()").that(actual.isIconified()).isTrue();
}
public void isNotIconified() {
check("isIconified()").that(actual.isIconified()).isFalse();
}
public void isQueryRefinementEnabled() {
check("isQueryRefinementEnabled()").that(actual.isQueryRefinementEnabled()).isTrue();
}
public void isQueryRefinementDisabled() {
check("isQueryRefinementEnabled()").that(actual.isQueryRefinementEnabled()).isFalse();
}
public void isSubmitButtonEnabled() {
check("isSubmitButtonEnabled()").that(actual.isSubmitButtonEnabled()).isTrue();
}
public void isSubmitButtonDisabled() {
check("isSubmitButtonEnabled()").that(actual.isSubmitButtonEnabled()).isFalse();
}
}
| pkware/truth-android | truth-android-appcompat/src/main/java/com/pkware/truth/androidx/appcompat/widget/SearchViewSubject.java | Java | apache-2.0 | 3,403 |
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.github.am0e.jbeans;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
/** Represents a field that can be accessed directly if the field is public or via an associated getter or
* setter.
* The class provides a getter and a setter to set the associated field value in an object.
*
* @author Anthony (ARPT)
*/
/**
* @author anthony
*
*/
public final class FieldInfo implements BaseInfo {
/**
* Field name
*/
final String name;
/**
* Field name hashcode.
*/
final int hash;
/**
* The bean field.
*/
final Field field;
/**
* Optional setter method. If this field is public, this will contain null.
*/
final MethodInfo setter;
/**
* Optional getter method. If this field is public, this will contain null.
*/
final MethodInfo getter;
/**
* If the field is a parameterized List or Map, this field will contain the
* class type of the value stored in the list or map. in the parameter. Eg:
* List<String> it will contain String. For Map<String,Double>
* it will contain Double.
*/
final Class<?> actualType;
FieldInfo(Field field, MethodInfo getter, MethodInfo setter) {
// Get the type of the field.
//
this.actualType = BeanUtils.getActualTypeFromMethodOrField(null, field);
this.field = field;
this.setter = setter;
this.getter = getter;
this.name = field.getName().intern();
this.hash = this.name.hashCode();
}
public Field getField() {
return field;
}
public Class<?> getType() {
return field.getType();
}
public Class<?> getActualType() {
return actualType;
}
public String getName() {
return name;
}
public String toString() {
return field.getDeclaringClass().getName() + "#" + name;
}
public boolean isField() {
return field == null ? false : true;
}
/**
* Returns true if the field value can be retrieved either through the
* public field itself or through a public getter method.
*/
public final boolean isReadable() {
return (Modifier.isPublic(field.getModifiers()) || getter != null);
}
public final boolean isSettable() {
return (Modifier.isPublic(field.getModifiers()) || setter != null);
}
public final boolean isTransient() {
return (Modifier.isTransient(field.getModifiers()));
}
public final Object callGetter(Object bean) throws BeanException {
if (bean == null)
return null;
// If the field is public, get the value directly.
//
try {
if (getter != null) {
// Use the public getter. We will always attempt to use this
// FIRST!!
//
return getter.method.invoke(bean);
}
if (!Modifier.isPublic(field.getModifiers())) {
throw BeanException.fmtExcStr("Field not gettable", bean, getName(), null);
}
return field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw BeanException.fmtExcStr("callGetter", bean, getName(), e);
} catch (InvocationTargetException e) {
throw BeanUtils.wrapError(e.getCause());
}
}
public final void callSetter(Object bean, Object value) throws BeanException {
value = BeanUtils.cast(value, field.getType());
try {
// Use the public setter. We will always attempt to use this FIRST!!
//
if (setter != null) {
setter.method.invoke(bean, value);
return;
}
if (!Modifier.isPublic(field.getModifiers())) {
throw BeanException.fmtExcStr("Field not settable", bean, getName(), null);
}
// If the field is public, set the value directly.
//
field.set(bean, value);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw BeanException.fmtExcStr("callSetter", bean, getName(), e);
} catch (InvocationTargetException e) {
throw BeanUtils.wrapError(e.getCause());
}
}
/**
* Converts a value into a value of the bean type.
*
* @param value
* The value to convert.
* @return If the value could not be converted, the value itself is
* returned. For example: if (beanField.valueOf(strVal)==strVal)
* throw new IllegalArgumentException();
*/
public final Object valueOf(Object value) {
return BeanUtils.cast(value, actualType);
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> type) {
return field.getAnnotation(type);
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> type) {
return field.getAnnotation(type) == null ? false : true;
}
@Override
public MethodHandle getHandle(Lookup lookup, boolean setter) {
try {
if (setter)
return lookup.findSetter(field.getDeclaringClass(), name, field.getType());
else
return lookup.findGetter(field.getDeclaringClass(), name, field.getType());
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new BeanException(e);
}
}
@Override
public String makeSignature(StringBuilder sb) {
sb.setLength(0);
sb.append(getType().toString());
sb.append(' ');
sb.append(getName());
return sb.toString();
}
}
| am0e/commons | src/main/java/com/github/am0e/jbeans/FieldInfo.java | Java | apache-2.0 | 7,111 |
package org.corpus_tools.annis.gui.visualizers.component.tree;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.corpus_tools.annis.gui.visualizers.VisualizerInput;
import org.corpus_tools.annis.gui.visualizers.component.tree.AnnisGraphTools;
import org.corpus_tools.salt.SaltFactory;
import org.corpus_tools.salt.common.SDominanceRelation;
import org.corpus_tools.salt.core.SAnnotation;
import org.junit.jupiter.api.Test;
class AnnisGraphToolsTest {
@Test
void extractAnnotation() {
assertNull(AnnisGraphTools.extractAnnotation(null, "some_ns", "func"));
Set<SAnnotation> annos = new LinkedHashSet<>();
SAnnotation annoFunc = SaltFactory.createSAnnotation();
annoFunc.setNamespace("some_ns");
annoFunc.setName("func");
annoFunc.setValue("value");
annos.add(annoFunc);
assertEquals("value", AnnisGraphTools.extractAnnotation(annos, null, "func"));
assertEquals("value", AnnisGraphTools.extractAnnotation(annos, "some_ns", "func"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "another_ns", "func"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "some_ns", "anno"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "another_ns", "anno"));
assertNull(AnnisGraphTools.extractAnnotation(annos, null, "anno"));
}
@Test
void isTerminalNullCheck() {
assertFalse(AnnisGraphTools.isTerminal(null, null));
VisualizerInput mockedVisInput = mock(VisualizerInput.class);
assertFalse(AnnisGraphTools.isTerminal(null, mockedVisInput));
}
@Test
void hasEdgeSubtypeForEmptyType() {
SDominanceRelation rel1 = mock(SDominanceRelation.class);
VisualizerInput input = mock(VisualizerInput.class);
// When the type is empty, this should be treated like having no type (null) at all
when(rel1.getType()).thenReturn("");
Map<String, String> mappings = new LinkedHashMap<>();
when(input.getMappings()).thenReturn(mappings);
mappings.put("edge_type", "null");
AnnisGraphTools tools = new AnnisGraphTools(input);
assertTrue(tools.hasEdgeSubtype(rel1, "null"));
SDominanceRelation rel2 = mock(SDominanceRelation.class);
when(rel1.getType()).thenReturn(null);
assertTrue(tools.hasEdgeSubtype(rel2, "null"));
}
}
| korpling/ANNIS | src/test/java/org/corpus_tools/annis/gui/visualizers/component/tree/AnnisGraphToolsTest.java | Java | apache-2.0 | 2,637 |
// ----------------------------------------------------------------------------
// Copyright 2007-2011, GeoTelematic Solutions, 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.
//
// ----------------------------------------------------------------------------
// Change History:
// 2006/08/21 Martin D. Flynn
// Initial release
// ----------------------------------------------------------------------------
package org.opengts.dbtypes;
import java.lang.*;
import java.util.*;
import java.math.*;
import java.io.*;
import java.sql.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
public class DTIPAddress
extends DBFieldType
{
// ------------------------------------------------------------------------
private IPTools.IPAddress ipAddr = null;
public DTIPAddress(IPTools.IPAddress ipAddr)
{
this.ipAddr = ipAddr;
}
public DTIPAddress(String ipAddr)
{
super(ipAddr);
this.ipAddr = new IPTools.IPAddress(ipAddr);
}
public DTIPAddress(ResultSet rs, String fldName)
throws SQLException
{
super(rs, fldName);
// set to default value if 'rs' is null
this.ipAddr = (rs != null)? new IPTools.IPAddress(rs.getString(fldName)) : null;
}
// ------------------------------------------------------------------------
public boolean isMatch(String ipAddr)
{
if (this.ipAddr != null) {
return this.ipAddr.isMatch(ipAddr);
} else {
return true;
}
}
// ------------------------------------------------------------------------
public Object getObject()
{
return this.toString();
}
public String toString()
{
return (this.ipAddr != null)? this.ipAddr.toString() : "";
}
// ------------------------------------------------------------------------
public boolean equals(Object other)
{
if (this == other) {
// same object
return true;
} else
if (other instanceof DTIPAddress) {
DTIPAddress otherList = (DTIPAddress)other;
if (otherList.ipAddr == this.ipAddr) {
// will also match if both are null
return true;
} else
if ((this.ipAddr == null) || (otherList.ipAddr == null)) {
// one is null, the other isn't
return false;
} else {
// IPAddressList match
return this.ipAddr.equals(otherList.ipAddr);
}
} else {
return false;
}
}
// ------------------------------------------------------------------------
}
| CASPED/OpenGTS | src/org/opengts/dbtypes/DTIPAddress.java | Java | apache-2.0 | 3,318 |
package ru.stqa.pft.mantis.appmanager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import ru.stqa.pft.mantis.model.User;
import java.util.List;
/**
* Created by Даниил on 11.06.2017.
*/
public class DbHelper {
private final SessionFactory sessionFactory;
public DbHelper() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
}
public User getUser() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<User> result = session.createQuery("from User").list();
session.getTransaction().commit();
session.close();
return result.stream().filter((s)->(!s.getUsername().equals("administrator"))).iterator().next();
}
}
| SweetyDonut/java_pft | Mantis_tests/src/test/java/ru/stqa/pft/mantis/appmanager/DbHelper.java | Java | apache-2.0 | 1,105 |
package com.mricefox.androidhorizontalcalendar.library.calendar;
import android.database.Observable;
/**
* Author:zengzifeng email:zeng163mail@163.com
* Description:
* Date:2015/12/25
*/
public class DataSetObservable extends Observable<DataSetObserver> {
public boolean hasObservers() {
synchronized (mObservers) {
return !mObservers.isEmpty();
}
}
public void notifyChanged() {
synchronized (mObservers) {//mObservers register and notify maybe in different thread
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
}
public void notifyItemRangeChanged(long from, long to) {
synchronized (mObservers) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeChanged(from, to);
}
}
}
}
| MrIceFox/AndroidHorizontalCalendar | library/src/main/java/com/mricefox/androidhorizontalcalendar/library/calendar/DataSetObservable.java | Java | apache-2.0 | 918 |
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.eclipse.ceylon.langtools.classfile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.ceylon.langtools.classfile.TypeAnnotation.Position.TypePathEntry;
/**
* See JSR 308 specification, Section 3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class TypeAnnotation {
TypeAnnotation(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
constant_pool = cr.getConstantPool();
position = read_position(cr);
annotation = new Annotation(cr);
}
public TypeAnnotation(ConstantPool constant_pool,
Annotation annotation, Position position) {
this.constant_pool = constant_pool;
this.position = position;
this.annotation = annotation;
}
public int length() {
int n = annotation.length();
n += position_length(position);
return n;
}
@Override
public String toString() {
try {
return "@" + constant_pool.getUTF8Value(annotation.type_index).toString().substring(1) +
" pos: " + position.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
public final ConstantPool constant_pool;
public final Position position;
public final Annotation annotation;
private static Position read_position(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
// Copied from ClassReader
int tag = cr.readUnsignedByte(); // TargetType tag is a byte
if (!TargetType.isValidTargetTypeValue(tag))
throw new Annotation.InvalidAnnotation("TypeAnnotation: Invalid type annotation target type value: " + String.format("0x%02X", tag));
TargetType type = TargetType.fromTargetTypeValue(tag);
Position position = new Position();
position.type = type;
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
position.offset = cr.readUnsignedShort();
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
int table_length = cr.readUnsignedShort();
position.lvarOffset = new int[table_length];
position.lvarLength = new int[table_length];
position.lvarIndex = new int[table_length];
for (int i = 0; i < table_length; ++i) {
position.lvarOffset[i] = cr.readUnsignedShort();
position.lvarLength[i] = cr.readUnsignedShort();
position.lvarIndex[i] = cr.readUnsignedShort();
}
break;
// exception parameter
case EXCEPTION_PARAMETER:
position.exception_index = cr.readUnsignedShort();
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
position.parameter_index = cr.readUnsignedByte();
position.bound_index = cr.readUnsignedByte();
break;
// class extends or implements clause
case CLASS_EXTENDS:
int in = cr.readUnsignedShort();
if (in == 0xFFFF)
in = -1;
position.type_index = in;
break;
// throws
case THROWS:
position.type_index = cr.readUnsignedShort();
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
position.offset = cr.readUnsignedShort();
position.type_index = cr.readUnsignedByte();
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + type);
}
{ // Write type path
int len = cr.readUnsignedByte();
List<Integer> loc = new ArrayList<Integer>(len);
for (int i = 0; i < len * TypePathEntry.bytesPerEntry; ++i)
loc.add(cr.readUnsignedByte());
position.location = Position.getTypePathFromBinary(loc);
}
return position;
}
private static int position_length(Position pos) {
int n = 0;
n += 1; // TargetType tag is a byte
switch (pos.type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
n += 2; // offset
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
n += 2; // table_length;
int table_length = pos.lvarOffset.length;
n += 2 * table_length; // offset
n += 2 * table_length; // length
n += 2 * table_length; // index
break;
// exception parameter
case EXCEPTION_PARAMETER:
n += 2; // exception_index
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
n += 1; // parameter_index
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
n += 1; // parameter_index
n += 1; // bound_index
break;
// class extends or implements clause
case CLASS_EXTENDS:
n += 2; // type_index
break;
// throws
case THROWS:
n += 2; // type_index
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
n += 1; // parameter_index
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
n += 2; // offset
n += 1; // type index
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + pos.type);
}
{
n += 1; // length
n += TypePathEntry.bytesPerEntry * pos.location.size(); // bytes for actual array
}
return n;
}
// Code duplicated from org.eclipse.ceylon.langtools.tools.javac.code.TypeAnnotationPosition
public static class Position {
public enum TypePathEntryKind {
ARRAY(0),
INNER_TYPE(1),
WILDCARD(2),
TYPE_ARGUMENT(3);
public final int tag;
private TypePathEntryKind(int tag) {
this.tag = tag;
}
}
public static class TypePathEntry {
/** The fixed number of bytes per TypePathEntry. */
public static final int bytesPerEntry = 2;
public final TypePathEntryKind tag;
public final int arg;
public static final TypePathEntry ARRAY = new TypePathEntry(TypePathEntryKind.ARRAY);
public static final TypePathEntry INNER_TYPE = new TypePathEntry(TypePathEntryKind.INNER_TYPE);
public static final TypePathEntry WILDCARD = new TypePathEntry(TypePathEntryKind.WILDCARD);
private TypePathEntry(TypePathEntryKind tag) {
if (!(tag == TypePathEntryKind.ARRAY ||
tag == TypePathEntryKind.INNER_TYPE ||
tag == TypePathEntryKind.WILDCARD)) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = 0;
}
public TypePathEntry(TypePathEntryKind tag, int arg) {
if (tag != TypePathEntryKind.TYPE_ARGUMENT) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = arg;
}
public static TypePathEntry fromBinary(int tag, int arg) {
if (arg != 0 && tag != TypePathEntryKind.TYPE_ARGUMENT.tag) {
throw new AssertionError("Invalid TypePathEntry tag/arg: " + tag + "/" + arg);
}
switch (tag) {
case 0:
return ARRAY;
case 1:
return INNER_TYPE;
case 2:
return WILDCARD;
case 3:
return new TypePathEntry(TypePathEntryKind.TYPE_ARGUMENT, arg);
default:
throw new AssertionError("Invalid TypePathEntryKind tag: " + tag);
}
}
@Override
public String toString() {
return tag.toString() +
(tag == TypePathEntryKind.TYPE_ARGUMENT ? ("(" + arg + ")") : "");
}
@Override
public boolean equals(Object other) {
if (! (other instanceof TypePathEntry)) {
return false;
}
TypePathEntry tpe = (TypePathEntry) other;
return this.tag == tpe.tag && this.arg == tpe.arg;
}
@Override
public int hashCode() {
return this.tag.hashCode() * 17 + this.arg;
}
}
public TargetType type = TargetType.UNKNOWN;
// For generic/array types.
// TODO: or should we use null? Noone will use this object.
public List<TypePathEntry> location = new ArrayList<TypePathEntry>(0);
// Tree position.
public int pos = -1;
// For typecasts, type tests, new (and locals, as start_pc).
public boolean isValidOffset = false;
public int offset = -1;
// For locals. arrays same length
public int[] lvarOffset = null;
public int[] lvarLength = null;
public int[] lvarIndex = null;
// For type parameter bound
public int bound_index = Integer.MIN_VALUE;
// For type parameter and method parameter
public int parameter_index = Integer.MIN_VALUE;
// For class extends, implements, and throws clauses
public int type_index = Integer.MIN_VALUE;
// For exception parameters, index into exception table
public int exception_index = Integer.MIN_VALUE;
public Position() {}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
sb.append(type);
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
sb.append(", offset = ");
sb.append(offset);
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
if (lvarOffset == null) {
sb.append(", lvarOffset is null!");
break;
}
sb.append(", {");
for (int i = 0; i < lvarOffset.length; ++i) {
if (i != 0) sb.append("; ");
sb.append("start_pc = ");
sb.append(lvarOffset[i]);
sb.append(", length = ");
sb.append(lvarLength[i]);
sb.append(", index = ");
sb.append(lvarIndex[i]);
}
sb.append("}");
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
sb.append(", param_index = ");
sb.append(parameter_index);
sb.append(", bound_index = ");
sb.append(bound_index);
break;
// class extends or implements clause
case CLASS_EXTENDS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// throws
case THROWS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// exception parameter
case EXCEPTION_PARAMETER:
sb.append(", exception_index = ");
sb.append(exception_index);
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
sb.append(", offset = ");
sb.append(offset);
sb.append(", type_index = ");
sb.append(type_index);
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
sb.append(", position UNKNOWN!");
break;
default:
throw new AssertionError("Unknown target type: " + type);
}
// Append location data for generics/arrays.
if (!location.isEmpty()) {
sb.append(", location = (");
sb.append(location);
sb.append(")");
}
sb.append(", pos = ");
sb.append(pos);
sb.append(']');
return sb.toString();
}
/**
* Indicates whether the target tree of the annotation has been optimized
* away from classfile or not.
* @return true if the target has not been optimized away
*/
public boolean emitToClassfile() {
return !type.isLocal() || isValidOffset;
}
/**
* Decode the binary representation for a type path and set
* the {@code location} field.
*
* @param list The bytecode representation of the type path.
*/
public static List<TypePathEntry> getTypePathFromBinary(List<Integer> list) {
List<TypePathEntry> loc = new ArrayList<TypePathEntry>(list.size() / TypePathEntry.bytesPerEntry);
int idx = 0;
while (idx < list.size()) {
if (idx + 1 == list.size()) {
throw new AssertionError("Could not decode type path: " + list);
}
loc.add(TypePathEntry.fromBinary(list.get(idx), list.get(idx + 1)));
idx += 2;
}
return loc;
}
public static List<Integer> getBinaryFromTypePath(List<TypePathEntry> locs) {
List<Integer> loc = new ArrayList<Integer>(locs.size() * TypePathEntry.bytesPerEntry);
for (TypePathEntry tpe : locs) {
loc.add(tpe.tag.tag);
loc.add(tpe.arg);
}
return loc;
}
}
// Code duplicated from org.eclipse.ceylon.langtools.tools.javac.code.TargetType
// The IsLocal flag could be removed here.
public enum TargetType {
/** For annotations on a class type parameter declaration. */
CLASS_TYPE_PARAMETER(0x00),
/** For annotations on a method type parameter declaration. */
METHOD_TYPE_PARAMETER(0x01),
/** For annotations on the type of an "extends" or "implements" clause. */
CLASS_EXTENDS(0x10),
/** For annotations on a bound of a type parameter of a class. */
CLASS_TYPE_PARAMETER_BOUND(0x11),
/** For annotations on a bound of a type parameter of a method. */
METHOD_TYPE_PARAMETER_BOUND(0x12),
/** For annotations on a field. */
FIELD(0x13),
/** For annotations on a method return type. */
METHOD_RETURN(0x14),
/** For annotations on the method receiver. */
METHOD_RECEIVER(0x15),
/** For annotations on a method parameter. */
METHOD_FORMAL_PARAMETER(0x16),
/** For annotations on a throws clause in a method declaration. */
THROWS(0x17),
/** For annotations on a local variable. */
LOCAL_VARIABLE(0x40, true),
/** For annotations on a resource variable. */
RESOURCE_VARIABLE(0x41, true),
/** For annotations on an exception parameter. */
EXCEPTION_PARAMETER(0x42, true),
/** For annotations on a type test. */
INSTANCEOF(0x43, true),
/** For annotations on an object creation expression. */
NEW(0x44, true),
/** For annotations on a constructor reference receiver. */
CONSTRUCTOR_REFERENCE(0x45, true),
/** For annotations on a method reference receiver. */
METHOD_REFERENCE(0x46, true),
/** For annotations on a typecast. */
CAST(0x47, true),
/** For annotations on a type argument of an object creation expression. */
CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT(0x48, true),
/** For annotations on a type argument of a method call. */
METHOD_INVOCATION_TYPE_ARGUMENT(0x49, true),
/** For annotations on a type argument of a constructor reference. */
CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT(0x4A, true),
/** For annotations on a type argument of a method reference. */
METHOD_REFERENCE_TYPE_ARGUMENT(0x4B, true),
/** For annotations with an unknown target. */
UNKNOWN(0xFF);
private static final int MAXIMUM_TARGET_TYPE_VALUE = 0x4B;
private final int targetTypeValue;
private final boolean isLocal;
private TargetType(int targetTypeValue) {
this(targetTypeValue, false);
}
private TargetType(int targetTypeValue, boolean isLocal) {
if (targetTypeValue < 0
|| targetTypeValue > 255)
throw new AssertionError("Attribute type value needs to be an unsigned byte: " + String.format("0x%02X", targetTypeValue));
this.targetTypeValue = targetTypeValue;
this.isLocal = isLocal;
}
/**
* Returns whether or not this TargetType represents an annotation whose
* target is exclusively a tree in a method body
*
* Note: wildcard bound targets could target a local tree and a class
* member declaration signature tree
*/
public boolean isLocal() {
return isLocal;
}
public int targetTypeValue() {
return this.targetTypeValue;
}
private static final TargetType[] targets;
static {
targets = new TargetType[MAXIMUM_TARGET_TYPE_VALUE + 1];
TargetType[] alltargets = values();
for (TargetType target : alltargets) {
if (target.targetTypeValue != UNKNOWN.targetTypeValue)
targets[target.targetTypeValue] = target;
}
for (int i = 0; i <= MAXIMUM_TARGET_TYPE_VALUE; ++i) {
if (targets[i] == null)
targets[i] = UNKNOWN;
}
}
public static boolean isValidTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return true;
return (tag >= 0 && tag < targets.length);
}
public static TargetType fromTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return UNKNOWN;
if (tag < 0 || tag >= targets.length)
throw new AssertionError("Unknown TargetType: " + tag);
return targets[tag];
}
}
}
| ceylon/ceylon | langtools-classfile/src/org/eclipse/ceylon/langtools/classfile/TypeAnnotation.java | Java | apache-2.0 | 23,331 |
package com.ticktick.testimagecropper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.ticktick.imagecropper.CropImageActivity;
import com.ticktick.imagecropper.CropIntent;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final int REQUEST_CODE_PICK_IMAGE = 0x1;
public static final int REQUEST_CODE_IMAGE_CROPPER = 0x2;
public static final String CROPPED_IMAGE_FILEPATH = "/sdcard/test.jpg";
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView)findViewById(R.id.CroppedImageView);
}
public void onClickButton(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_CODE_PICK_IMAGE);
}
public void startCropImage( Uri uri ) {
Intent intent = new Intent(this,CropImageActivity.class);
intent.setData(uri);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(CROPPED_IMAGE_FILEPATH)));
//intent.putExtra("aspectX",2);
//intent.putExtra("aspectY",1);
//intent.putExtra("outputX",320);
//intent.putExtra("outputY",240);
//intent.putExtra("maxOutputX",640);
//intent.putExtra("maxOutputX",480);
startActivityForResult(intent, REQUEST_CODE_IMAGE_CROPPER);
}
public void startCropImageByCropIntent( Uri uri ) {
CropIntent intent = new CropIntent();
intent.setImagePath(uri);
intent.setOutputPath(CROPPED_IMAGE_FILEPATH);
//intent.setAspect(2, 1);
//intent.setOutputSize(480,320);
//intent.setMaxOutputSize(480,320);
startActivityForResult(intent.getIntent(this), REQUEST_CODE_IMAGE_CROPPER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if( requestCode == REQUEST_CODE_PICK_IMAGE ) {
startCropImage(data.getData());
}
else if( requestCode == REQUEST_CODE_IMAGE_CROPPER ) {
Uri croppedUri = data.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT);
InputStream in = null;
try {
in = getContentResolver().openInputStream(croppedUri);
Bitmap b = BitmapFactory.decodeStream(in);
mImageView.setImageBitmap(b);
Toast.makeText(this,"Crop success,saved at"+CROPPED_IMAGE_FILEPATH,Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| msdgwzhy6/ImageCropper | TestImageCropper/src/com/ticktick/testimagecropper/MainActivity.java | Java | apache-2.0 | 3,086 |
/*
* 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.felix.deploymentadmin;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import org.osgi.framework.Version;
import org.osgi.service.deploymentadmin.BundleInfo;
import org.osgi.service.deploymentadmin.DeploymentException;
/**
* Implementation of the <code>BundleInfo</code> interface as defined by the OSGi mobile specification.
*/
public class BundleInfoImpl extends AbstractInfo implements BundleInfo {
private final Version m_version;
private final String m_symbolicName;
private final boolean m_customizer;
/**
* Creates an instance of this class.
*
* @param path The path / resource-id of the bundle resource.
* @param attributes Set of attributes describing the bundle resource.
* @throws DeploymentException If the specified attributes do not describe a valid bundle.
*/
public BundleInfoImpl(String path, Attributes attributes) throws DeploymentException {
super(path, attributes);
String bundleSymbolicName = attributes.getValue(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME);
if (bundleSymbolicName == null) {
throw new DeploymentException(DeploymentException.CODE_MISSING_HEADER, "Missing '" + org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME + "' header for manifest entry '" + getPath() + "'");
} else if (bundleSymbolicName.trim().equals("")) {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME + "' header for manifest entry '" + getPath() + "'");
} else {
m_symbolicName = parseSymbolicName(bundleSymbolicName);
}
String version = attributes.getValue(org.osgi.framework.Constants.BUNDLE_VERSION);
if (version == null || version == "") {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_VERSION + "' header for manifest entry '" + getPath() + "'");
}
try {
m_version = Version.parseVersion(version);
} catch (IllegalArgumentException e) {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_VERSION + "' header for manifest entry '" + getPath() + "'");
}
m_customizer = parseBooleanHeader(attributes, Constants.DEPLOYMENTPACKAGE_CUSTOMIZER);
}
/**
* Strips parameters from the bundle symbolic name such as "foo;singleton:=true".
*
* @param name full name as found in the manifest of the deployment package
* @return name without parameters
*/
private String parseSymbolicName(String name) {
// note that we don't explicitly check if there are tokens, because that
// check has already been made before we are invoked here
StringTokenizer st = new StringTokenizer(name, ";");
return st.nextToken();
}
public String getSymbolicName() {
return m_symbolicName;
}
public Version getVersion() {
return m_version;
}
/**
* Determine whether this bundle resource is a customizer bundle.
*
* @return True if the bundle is a customizer bundle, false otherwise.
*/
public boolean isCustomizer() {
return m_customizer;
}
/**
* Verify if the specified attributes describe a bundle resource.
*
* @param attributes Attributes describing the resource
* @return true if the attributes describe a bundle resource, false otherwise
*/
public static boolean isBundleResource(Attributes attributes) {
return (attributes.getValue(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME) != null);
}
}
| boneman1231/org.apache.felix | trunk/deploymentadmin/deploymentadmin/src/main/java/org/apache/felix/deploymentadmin/BundleInfoImpl.java | Java | apache-2.0 | 4,581 |
package com.zlwh.hands.api.domain.base;
public class PageDomain {
private String pageNo;
private String pageSize = "15";
private long pageTime; // 上次刷新时间,分页查询时,防止分页数据错乱
public String getPageNo() {
return pageNo;
}
public void setPageNo(String pageNo) {
this.pageNo = pageNo;
}
public String getPageSize() {
return pageSize;
}
public void setPageSize(String pageSize) {
this.pageSize = pageSize;
}
public long getPageTime() {
return pageTime;
}
public void setPageTime(long pageTime) {
this.pageTime = pageTime;
}
}
| javyuan/jeesite-api | src/main/java/com/zlwh/hands/api/domain/base/PageDomain.java | Java | apache-2.0 | 593 |
package io.github.thankpoint.security.impl;
import java.security.Provider;
import java.security.Security;
import io.github.thankpoint.security.api.provider.SecurityProviderBuilder;
/**
* Implementation of {@link SecurityProviderBuilder}.
*
* @param <B> type of the returned builder.
* @author thks
*/
public interface AbstractSecurityProviderBuilderImpl<B> extends SecurityProviderBuilder<B> {
@Override
default B provider() {
return provider((Provider) null);
}
@Override
default B provider(String name) {
return provider(Security.getProvider(name));
}
}
| thankpoint/thanks4java | security/src/main/java/io/github/thankpoint/security/impl/AbstractSecurityProviderBuilderImpl.java | Java | apache-2.0 | 589 |
package com.github.saulis.enumerables;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class EmptyIterator<T> implements Iterator<T> {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
}
| Saulis/enumerables | src/main/java/com/github/saulis/enumerables/EmptyIterator.java | Java | apache-2.0 | 326 |
package com.squarespace.template.expr;
import java.util.Arrays;
/**
* Token representing a variable name. Could hold a reference or
* a definition.
*/
public class VarToken extends Token {
public final Object[] name;
public VarToken(Object[] name) {
super(ExprTokenType.VARIABLE);
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof VarToken) {
return Arrays.equals(name, ((VarToken)obj).name);
}
return false;
}
@Override
public String toString() {
return "VarToken[" + Arrays.toString(name) + "]";
}
}
| Squarespace/template-compiler | core/src/main/java/com/squarespace/template/expr/VarToken.java | Java | apache-2.0 | 594 |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.jsonoutput;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.apache.commons.vfs.FileObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Converts input rows to one or more XML files.
*
* @author Matt
* @since 14-jan-2006
*/
public class JsonOutput extends BaseStep implements StepInterface
{
private static Class<?> PKG = JsonOutput.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private JsonOutputMeta meta;
private JsonOutputData data;
private interface CompatibilityFactory {
public void execute(Object[] row) throws KettleException;
}
@SuppressWarnings("unchecked")
private class CompatibilityMode implements CompatibilityFactory {
public void execute(Object[] row) throws KettleException {
for (int i=0;i<data.nrFields;i++) {
JsonOutputField outputField = meta.getOutputFields()[i];
ValueMetaInterface v = data.inputRowMeta.getValueMeta(data.fieldIndexes[i]);
// Create a new object with specified fields
JSONObject jo = new JSONObject();
switch (v.getType()) {
case ValueMeta.TYPE_BOOLEAN:
jo.put(outputField.getElementName(), data.inputRowMeta.getBoolean(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_INTEGER:
jo.put(outputField.getElementName(), data.inputRowMeta.getInteger(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_NUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getNumber(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_BIGNUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getBigNumber(row, data.fieldIndexes[i]));
break;
default:
jo.put(outputField.getElementName(), data.inputRowMeta.getString(row, data.fieldIndexes[i]));
break;
}
data.ja.add(jo);
}
data.nrRow++;
if(data.nrRowsInBloc>0) {
// System.out.println("data.nrRow%data.nrRowsInBloc = "+ data.nrRow%data.nrRowsInBloc);
if(data.nrRow%data.nrRowsInBloc==0) {
// We can now output an object
// System.out.println("outputting the row.");
outPutRow(row);
}
}
}
}
@SuppressWarnings("unchecked")
private class FixedMode implements CompatibilityFactory {
public void execute(Object[] row) throws KettleException {
// Create a new object with specified fields
JSONObject jo = new JSONObject();
for (int i=0;i<data.nrFields;i++) {
JsonOutputField outputField = meta.getOutputFields()[i];
ValueMetaInterface v = data.inputRowMeta.getValueMeta(data.fieldIndexes[i]);
switch (v.getType()) {
case ValueMeta.TYPE_BOOLEAN:
jo.put(outputField.getElementName(), data.inputRowMeta.getBoolean(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_INTEGER:
jo.put(outputField.getElementName(), data.inputRowMeta.getInteger(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_NUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getNumber(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_BIGNUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getBigNumber(row, data.fieldIndexes[i]));
break;
default:
jo.put(outputField.getElementName(), data.inputRowMeta.getString(row, data.fieldIndexes[i]));
break;
}
}
data.ja.add(jo);
data.nrRow++;
if(data.nrRowsInBloc > 0) {
// System.out.println("data.nrRow%data.nrRowsInBloc = "+ data.nrRow%data.nrRowsInBloc);
if(data.nrRow%data.nrRowsInBloc==0) {
// We can now output an object
// System.out.println("outputting the row.");
outPutRow(row);
}
}
}
}
private CompatibilityFactory compatibilityFactory;
public JsonOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
// Here we decide whether or not to build the structure in
// compatible mode or fixed mode
JsonOutputMeta jsonOutputMeta = (JsonOutputMeta)(stepMeta.getStepMetaInterface());
if (jsonOutputMeta.isCompatibilityMode()) {
compatibilityFactory = new CompatibilityMode();
}
else {
compatibilityFactory = new FixedMode();
}
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
Object[] r = getRow(); // This also waits for a row to be finished.
if (r==null) {
// no more input to be expected...
if(!data.rowsAreSafe) {
// Let's output the remaining unsafe data
outPutRow(r);
}
setOutputDone();
return false;
}
if (first) {
first=false;
data.inputRowMeta=getInputRowMeta();
data.inputRowMetaSize=data.inputRowMeta.size();
if(data.outputValue) {
data.outputRowMeta = data.inputRowMeta.clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
}
// Cache the field name indexes
//
data.nrFields=meta.getOutputFields().length;
data.fieldIndexes = new int[data.nrFields];
for (int i=0;i<data.nrFields;i++) {
data.fieldIndexes[i] = data.inputRowMeta.indexOfValue(meta.getOutputFields()[i].getFieldName());
if (data.fieldIndexes[i]<0) {
throw new KettleException(BaseMessages.getString(PKG, "JsonOutput.Exception.FieldNotFound")); //$NON-NLS-1$
}
JsonOutputField field = meta.getOutputFields()[i];
field.setElementName(environmentSubstitute(field.getElementName()));
}
}
data.rowsAreSafe=false;
compatibilityFactory.execute(r);
if(data.writeToFile && !data.outputValue) {
putRow(data.inputRowMeta,r ); // in case we want it go further...
incrementLinesOutput();
}
return true;
}
@SuppressWarnings("unchecked")
private void outPutRow(Object[] rowData) throws KettleStepException {
// We can now output an object
data.jg = new JSONObject();
data.jg.put(data.realBlocName, data.ja);
String value = data.jg.toJSONString();
if(data.outputValue) {
Object[] outputRowData = RowDataUtil.addValueData(rowData, data.inputRowMetaSize, value);
incrementLinesOutput();
putRow(data.outputRowMeta, outputRowData);
}
if(data.writeToFile) {
// Open a file
if (!openNewFile()) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.OpenNewFile", buildFilename()));
}
// Write data to file
try {
data.writer.write(value);
}catch(Exception e) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.Writing"), e);
}
// Close file
closeFile();
}
// Data are safe
data.rowsAreSafe=true;
data.ja = new JSONArray();
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
if(super.init(smi, sdi)) {
data.writeToFile = (meta.getOperationType() != JsonOutputMeta.OPERATION_TYPE_OUTPUT_VALUE);
data.outputValue = (meta.getOperationType() != JsonOutputMeta.OPERATION_TYPE_WRITE_TO_FILE);
if(data.outputValue) {
// We need to have output field name
if(Const.isEmpty(environmentSubstitute(meta.getOutputValue()))) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.MissingOutputFieldName"));
stopAll();
setErrors(1);
return false;
}
}
if(data.writeToFile) {
// We need to have output field name
if(!meta.isServletOutput() && Const.isEmpty(meta.getFileName())) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.MissingTargetFilename"));
stopAll();
setErrors(1);
return false;
}
if(!meta.isDoNotOpenNewFileInit()) {
if (!openNewFile()) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.OpenNewFile", buildFilename()));
stopAll();
setErrors(1);
return false;
}
}
}
data.realBlocName = Const.NVL(environmentSubstitute(meta.getJsonBloc()), "");
data.nrRowsInBloc = Const.toInt(environmentSubstitute(meta.getNrRowsInBloc()), 0);
return true;
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
if(data.ja!=null) data.ja=null;
if(data.jg!=null) data.jg=null;
closeFile();
super.dispose(smi, sdi);
}
private void createParentFolder(String filename) throws KettleStepException {
if(!meta.isCreateParentFolder()) return;
// Check for parent folder
FileObject parentfolder=null;
try {
// Get parent folder
parentfolder=KettleVFS.getFileObject(filename, getTransMeta()).getParent();
if(!parentfolder.exists()) {
if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "JsonOutput.Error.ParentFolderNotExist", parentfolder.getName()));
parentfolder.createFolder();
if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "JsonOutput.Log.ParentFolderCreated"));
}
}catch (Exception e) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.ErrorCreatingParentFolder", parentfolder.getName()));
} finally {
if ( parentfolder != null ){
try {
parentfolder.close();
}catch ( Exception ex ) {};
}
}
}
public boolean openNewFile()
{
if(data.writer!=null) return true;
boolean retval=false;
try {
if (meta.isServletOutput()) {
data.writer = getTrans().getServletPrintWriter();
} else {
String filename = buildFilename();
createParentFolder(filename);
if (meta.AddToResult()) {
// Add this to the result file names...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(filename, getTransMeta()), getTransMeta().getName(), getStepname());
resultFile.setComment(BaseMessages.getString(PKG, "JsonOutput.ResultFilenames.Comment"));
addResultFile(resultFile);
}
OutputStream outputStream;
OutputStream fos = KettleVFS.getOutputStream(filename, getTransMeta(), meta.isFileAppended());
outputStream=fos;
if (!Const.isEmpty(meta.getEncoding())) {
data.writer = new OutputStreamWriter(new BufferedOutputStream(outputStream, 5000), environmentSubstitute(meta.getEncoding()));
} else {
data.writer = new OutputStreamWriter(new BufferedOutputStream(outputStream, 5000));
}
if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JsonOutput.FileOpened", filename));
data.splitnr++;
}
retval=true;
} catch(Exception e) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.OpeningFile", e.toString()));
}
return retval;
}
public String buildFilename() {
return meta.buildFilename(environmentSubstitute(meta.getFileName()), getCopy(), data.splitnr);
}
private boolean closeFile()
{
if(data.writer==null) return true;
boolean retval=false;
try
{
data.writer.close();
data.writer=null;
retval=true;
}
catch(Exception e)
{
logError(BaseMessages.getString(PKG, "JsonOutput.Error.ClosingFile", e.toString()));
setErrors(1);
retval = false;
}
return retval;
}
} | jjeb/kettle-trunk | engine/src/org/pentaho/di/trans/steps/jsonoutput/JsonOutput.java | Java | apache-2.0 | 14,853 |
package io.indexr.query.expr.arith;
import com.google.common.collect.Lists;
import java.util.List;
import io.indexr.query.expr.BinaryExpression;
import io.indexr.query.expr.Expression;
import io.indexr.query.types.DataType;
public abstract class BinaryArithmetic extends Expression implements BinaryExpression {
public Expression left, right;
protected DataType dataType;
protected DataType leftType;
protected DataType rightType;
public BinaryArithmetic(Expression left, Expression right) {
this.left = left;
this.right = right;
}
protected DataType defaultType() {
return null;
}
protected void initType() {
if (dataType == null) {
leftType = left.dataType();
rightType = right.dataType();
DataType defaultType = defaultType();
if (defaultType == null) {
dataType = BinaryArithmetic.calType(left.dataType(), right.dataType());
} else {
dataType = defaultType;
}
}
}
@Override
public Expression left() {
return left;
}
@Override
public Expression right() {
return right;
}
@Override
public DataType dataType() {
initType();
return dataType;
}
@Override
public List<Expression> children() {
return Lists.newArrayList(left, right);
}
@Override
public boolean resolved() {
return childrenResolved() && checkInputDataTypes().isSuccess;
}
public static DataType calType(DataType type1, DataType type2) {
return type1.ordinal() >= type2.ordinal() ? type1 : type2;
}
}
| shunfei/indexr | indexr-query-opt/src/main/java/io/indexr/query/expr/arith/BinaryArithmetic.java | Java | apache-2.0 | 1,684 |
package org.ovirt.engine.ui.common.widget.table.column;
import org.ovirt.engine.core.common.businessentities.Disk;
import com.google.gwt.user.cellview.client.Column;
public class DiskStatusColumn extends Column<Disk, Disk> {
public DiskStatusColumn() {
super(new DiskStatusCell());
}
@Override
public Disk getValue(Disk object) {
return object;
}
}
| derekhiggins/ovirt-engine | frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/table/column/DiskStatusColumn.java | Java | apache-2.0 | 391 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.text.tx3g;
import static com.google.common.truth.Truth.assertThat;
import android.graphics.Color;
import android.graphics.Typeface;
import android.test.InstrumentationTestCase;
import android.text.SpannedString;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.Subtitle;
import com.google.android.exoplayer2.text.SubtitleDecoderException;
import java.io.IOException;
import java.util.Collections;
/**
* Unit test for {@link Tx3gDecoder}.
*/
public final class Tx3gDecoderTest extends InstrumentationTestCase {
private static final String NO_SUBTITLE = "tx3g/no_subtitle";
private static final String SAMPLE_JUST_TEXT = "tx3g/sample_just_text";
private static final String SAMPLE_WITH_STYL = "tx3g/sample_with_styl";
private static final String SAMPLE_WITH_STYL_ALL_DEFAULTS = "tx3g/sample_with_styl_all_defaults";
private static final String SAMPLE_UTF16_BE_NO_STYL = "tx3g/sample_utf16_be_no_styl";
private static final String SAMPLE_UTF16_LE_NO_STYL = "tx3g/sample_utf16_le_no_styl";
private static final String SAMPLE_WITH_MULTIPLE_STYL = "tx3g/sample_with_multiple_styl";
private static final String SAMPLE_WITH_OTHER_EXTENSION = "tx3g/sample_with_other_extension";
private static final String SAMPLE_WITH_TBOX = "tx3g/sample_with_tbox";
private static final String INITIALIZATION = "tx3g/initialization";
private static final String INITIALIZATION_ALL_DEFAULTS = "tx3g/initialization_all_defaults";
public void testDecodeNoSubtitle() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), NO_SUBTITLE);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertThat(subtitle.getCues(0)).isEmpty();
}
public void testDecodeJustText() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_JUST_TEXT);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(3);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, 6, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithStylAllDefaults() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL_ALL_DEFAULTS);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeUtf16BeNoStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_UTF16_BE_NO_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("你好");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeUtf16LeNoStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_UTF16_LE_NO_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("你好");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithMultipleStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_MULTIPLE_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("Line 2\nLine 3");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(4);
StyleSpan styleSpan = findSpan(text, 0, 5, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.ITALIC);
findSpan(text, 7, 12, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 5, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
colorSpan = findSpan(text, 7, 12, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithOtherExtension() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_OTHER_EXTENSION);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(2);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testInitializationDecodeWithStyl() throws IOException, SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(5);
StyleSpan styleSpan = findSpan(text, 0, text.length(), StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, text.length(), UnderlineSpan.class);
TypefaceSpan typefaceSpan = findSpan(text, 0, text.length(), TypefaceSpan.class);
assertThat(typefaceSpan.getFamily()).isEqualTo(C.SERIF_NAME);
ForegroundColorSpan colorSpan = findSpan(text, 0, text.length(), ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.RED);
colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.1f);
}
public void testInitializationDecodeWithTbox() throws IOException, SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_TBOX);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(4);
StyleSpan styleSpan = findSpan(text, 0, text.length(), StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, text.length(), UnderlineSpan.class);
TypefaceSpan typefaceSpan = findSpan(text, 0, text.length(), TypefaceSpan.class);
assertThat(typefaceSpan.getFamily()).isEqualTo(C.SERIF_NAME);
ForegroundColorSpan colorSpan = findSpan(text, 0, text.length(), ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.RED);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.1875f);
}
public void testInitializationAllDefaultsDecodeWithStyl() throws IOException,
SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION_ALL_DEFAULTS);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(3);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, 6, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
private static <T> T findSpan(SpannedString testObject, int expectedStart, int expectedEnd,
Class<T> expectedType) {
T[] spans = testObject.getSpans(0, testObject.length(), expectedType);
for (T span : spans) {
if (testObject.getSpanStart(span) == expectedStart
&& testObject.getSpanEnd(span) == expectedEnd) {
return span;
}
}
fail("Span not found.");
return null;
}
private static void assertFractionalLinePosition(Cue cue, float expectedFraction) {
assertThat(cue.lineType).isEqualTo(Cue.LINE_TYPE_FRACTION);
assertThat(cue.lineAnchor).isEqualTo(Cue.ANCHOR_TYPE_START);
assertThat(Math.abs(expectedFraction - cue.line) < 1e-6).isTrue();
}
}
| KiminRyu/ExoPlayer | library/core/src/androidTest/java/com/google/android/exoplayer2/text/tx3g/Tx3gDecoderTest.java | Java | apache-2.0 | 12,407 |
/*
* Copyright 1999-2017 YaoTrue.
*
* 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.yaotrue.web.command;
import java.io.Serializable;
/**
* @author <a href="mailto:yaotrue@163.com">yaotrue</a>
* 2017年8月16日 下午9:15:05
*/
public class BaseCommand implements Serializable {
/**
* <code>{@value}</code>
*/
private static final long serialVersionUID = 6878114738264710696L;
}
| yaotrue/learn-parent | learn-lang/src/main/java/com/yaotrue/web/command/BaseCommand.java | Java | apache-2.0 | 950 |
/**
* <pre>
* Project: cargo-itest Created on: 26 nov. 2014 File: fCommonDBConfiguration.java
* Package: nl.tranquilizedquality.itest.configuration
*
* Copyright (c) 2014 Tranquilized Quality www.tr-quality.com All rights
* reserved.
*
* This software is the confidential and proprietary information of Dizizid
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with Tranquilized Quality.
* </pre>
*/
package nl.tranquilizedquality.itest.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
/**
* @author Salomo Petrus (salomo.petrus@tr-quality.com)
* @since 26 nov. 2014
*
*/
@Configuration
public class CommonDBConfiguration extends DatasourceConfiguration {
@Bean(name = "transactionManager")
public DataSourceTransactionManager dataSourceTransactionManager(final SingleConnectionDataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
| snkpetrus/cargo-itest | src/main/java/nl/tranquilizedquality/itest/configuration/CommonDBConfiguration.java | Java | apache-2.0 | 1,293 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glaf.j2cache;
public class CacheException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CacheException(String s) {
super(s);
}
public CacheException(String s, Throwable e) {
super(s, e);
}
public CacheException(Throwable e) {
super(e);
}
}
| jior/glaf | workspace/glaf-core/src/main/java/com/glaf/j2cache/CacheException.java | Java | apache-2.0 | 1,115 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.tpch;
import com.facebook.presto.spi.Index;
import com.facebook.presto.spi.RecordSet;
import com.google.common.base.Function;
import static com.facebook.presto.tpch.TpchIndexedData.IndexedTable;
import static com.google.common.base.Preconditions.checkNotNull;
public class TpchIndex
implements Index
{
private final Function<RecordSet, RecordSet> keyFormatter;
private final Function<RecordSet, RecordSet> outputFormatter;
private final IndexedTable indexedTable;
public TpchIndex(Function<RecordSet, RecordSet> keyFormatter, Function<RecordSet, RecordSet> outputFormatter, IndexedTable indexedTable)
{
this.keyFormatter = checkNotNull(keyFormatter, "keyFormatter is null");
this.outputFormatter = checkNotNull(outputFormatter, "outputFormatter is null");
this.indexedTable = checkNotNull(indexedTable, "indexedTable is null");
}
@Override
public RecordSet lookup(RecordSet rawInputRecordSet)
{
// convert the input record set from the column ordering in the query to
// match the column ordering of the index
RecordSet inputRecordSet = keyFormatter.apply(rawInputRecordSet);
// lookup the values in the index
RecordSet rawOutputRecordSet = indexedTable.lookupKeys(inputRecordSet);
// convert the output record set of the index into the column ordering
// expect by the query
return outputFormatter.apply(rawOutputRecordSet);
}
}
| FlxRobin/presto | presto-main/src/test/java/com/facebook/presto/tpch/TpchIndex.java | Java | apache-2.0 | 2,063 |
/*
* Copyright 2018-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.net.pi.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import org.junit.Test;
import org.onosproject.TestApplicationId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.GroupId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.group.DefaultGroup;
import org.onosproject.net.group.DefaultGroupBucket;
import org.onosproject.net.group.DefaultGroupDescription;
import org.onosproject.net.group.Group;
import org.onosproject.net.group.GroupBucket;
import org.onosproject.net.group.GroupBuckets;
import org.onosproject.net.group.GroupDescription;
import org.onosproject.net.pi.runtime.PiGroupKey;
import org.onosproject.net.pi.runtime.PiMulticastGroupEntry;
import org.onosproject.net.pi.runtime.PiPreReplica;
import java.util.List;
import java.util.Set;
import static org.onosproject.net.group.GroupDescription.Type.ALL;
import static org.onosproject.pipelines.basic.BasicConstants.INGRESS_WCMP_CONTROL_WCMP_SELECTOR;
import static org.onosproject.pipelines.basic.BasicConstants.INGRESS_WCMP_CONTROL_WCMP_TABLE;
/**
* Test for {@link PiMulticastGroupTranslatorImpl}.
*/
public class PiMulticastGroupTranslatorImplTest {
private static final DeviceId DEVICE_ID = DeviceId.deviceId("device:dummy:1");
private static final ApplicationId APP_ID = TestApplicationId.create("dummy");
private static final GroupId GROUP_ID = GroupId.valueOf(1);
private static final PiGroupKey GROUP_KEY = new PiGroupKey(
INGRESS_WCMP_CONTROL_WCMP_TABLE, INGRESS_WCMP_CONTROL_WCMP_SELECTOR, GROUP_ID.id());
private static final List<GroupBucket> BUCKET_LIST = ImmutableList.of(
allOutputBucket(1),
allOutputBucket(2),
allOutputBucket(3));
private static final List<GroupBucket> BUCKET_LIST_2 = ImmutableList.of(
allOutputBucket(1),
allOutputBucket(2),
allOutputBucket(2),
allOutputBucket(3),
allOutputBucket(3));
private static final Set<PiPreReplica> REPLICAS = ImmutableSet.of(
new PiPreReplica(PortNumber.portNumber(1), 1),
new PiPreReplica(PortNumber.portNumber(2), 1),
new PiPreReplica(PortNumber.portNumber(3), 1));
private static final Set<PiPreReplica> REPLICAS_2 = ImmutableSet.of(
new PiPreReplica(PortNumber.portNumber(1), 1),
new PiPreReplica(PortNumber.portNumber(2), 1),
new PiPreReplica(PortNumber.portNumber(2), 2),
new PiPreReplica(PortNumber.portNumber(3), 1),
new PiPreReplica(PortNumber.portNumber(3), 2));
private static final PiMulticastGroupEntry PI_MULTICAST_GROUP =
PiMulticastGroupEntry.builder()
.withGroupId(GROUP_ID.id())
.addReplicas(REPLICAS)
.build();
private static final PiMulticastGroupEntry PI_MULTICAST_GROUP_2 =
PiMulticastGroupEntry.builder()
.withGroupId(GROUP_ID.id())
.addReplicas(REPLICAS_2)
.build();
private static final GroupBuckets BUCKETS = new GroupBuckets(BUCKET_LIST);
private static final GroupBuckets BUCKETS_2 = new GroupBuckets(BUCKET_LIST_2);
private static final GroupDescription ALL_GROUP_DESC = new DefaultGroupDescription(
DEVICE_ID, ALL, BUCKETS, GROUP_KEY, GROUP_ID.id(), APP_ID);
private static final Group ALL_GROUP = new DefaultGroup(GROUP_ID, ALL_GROUP_DESC);
private static final GroupDescription ALL_GROUP_DESC_2 = new DefaultGroupDescription(
DEVICE_ID, ALL, BUCKETS_2, GROUP_KEY, GROUP_ID.id(), APP_ID);
private static final Group ALL_GROUP_2 = new DefaultGroup(GROUP_ID, ALL_GROUP_DESC_2);
private static GroupBucket allOutputBucket(int portNum) {
TrafficTreatment treatment = DefaultTrafficTreatment.builder()
.setOutput(PortNumber.portNumber(portNum))
.build();
return DefaultGroupBucket.createAllGroupBucket(treatment);
}
@Test
public void testTranslatePreGroups() throws Exception {
PiMulticastGroupEntry multicastGroup = PiMulticastGroupTranslatorImpl
.translate(ALL_GROUP, null, null);
PiMulticastGroupEntry multicastGroup2 = PiMulticastGroupTranslatorImpl
.translate(ALL_GROUP_2, null, null);
new EqualsTester()
.addEqualityGroup(multicastGroup, PI_MULTICAST_GROUP)
.addEqualityGroup(multicastGroup2, PI_MULTICAST_GROUP_2)
.testEquals();
}
}
| kuujo/onos | core/net/src/test/java/org/onosproject/net/pi/impl/PiMulticastGroupTranslatorImplTest.java | Java | apache-2.0 | 5,443 |
package models;
/**
* This class is for boxing the response sent back to slack by the bot.
* @author sabinapokhrel
*/
public class ResponseToClient {
public String status; // Status of the response sent back to slack. It can be either success or fail.
public String message; // The message sent back to the slack by the bot.\
public ResponseToClient(String status, String message) {
this.status = status;
this.message = message;
}
}
| agiledigital/poet-slack-bot | server/app/models/ResponseToClient.java | Java | apache-2.0 | 455 |
package com.sequenceiq.redbeams.converter.stack;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Answers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.test.util.ReflectionTestUtils;
import com.sequenceiq.cloudbreak.api.endpoint.v4.common.DatabaseVendor;
import com.sequenceiq.cloudbreak.auth.CrnUser;
import com.sequenceiq.cloudbreak.auth.altus.EntitlementService;
import com.sequenceiq.cloudbreak.auth.crn.Crn;
import com.sequenceiq.cloudbreak.auth.crn.CrnTestUtil;
import com.sequenceiq.cloudbreak.auth.security.CrnUserDetailsService;
import com.sequenceiq.cloudbreak.cloud.model.CloudSubnet;
import com.sequenceiq.cloudbreak.cloud.model.StackTags;
import com.sequenceiq.cloudbreak.common.exception.BadRequestException;
import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform;
import com.sequenceiq.cloudbreak.common.mappable.MappableBase;
import com.sequenceiq.cloudbreak.common.mappable.ProviderParameterCalculator;
import com.sequenceiq.cloudbreak.common.mappable.ProviderParametersBase;
import com.sequenceiq.cloudbreak.common.service.Clock;
import com.sequenceiq.cloudbreak.tag.CostTagging;
import com.sequenceiq.environment.api.v1.environment.model.response.DetailedEnvironmentResponse;
import com.sequenceiq.environment.api.v1.environment.model.response.EnvironmentNetworkResponse;
import com.sequenceiq.environment.api.v1.environment.model.response.LocationResponse;
import com.sequenceiq.environment.api.v1.environment.model.response.SecurityAccessResponse;
import com.sequenceiq.environment.api.v1.environment.model.response.TagResponse;
import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.requests.AllocateDatabaseServerV4Request;
import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.requests.SslConfigV4Request;
import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.requests.SslMode;
import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.responses.SslCertificateType;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.DatabaseServerV4StackRequest;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.NetworkV4StackRequest;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.SecurityGroupV4StackRequest;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.aws.AwsNetworkV4Parameters;
import com.sequenceiq.redbeams.api.model.common.DetailedDBStackStatus;
import com.sequenceiq.redbeams.api.model.common.Status;
import com.sequenceiq.redbeams.configuration.DatabaseServerSslCertificateConfig;
import com.sequenceiq.redbeams.configuration.SslCertificateEntry;
import com.sequenceiq.redbeams.domain.stack.DBStack;
import com.sequenceiq.redbeams.domain.stack.SslConfig;
import com.sequenceiq.redbeams.service.AccountTagService;
import com.sequenceiq.redbeams.service.EnvironmentService;
import com.sequenceiq.redbeams.service.PasswordGeneratorService;
import com.sequenceiq.redbeams.service.UserGeneratorService;
import com.sequenceiq.redbeams.service.UuidGeneratorService;
import com.sequenceiq.redbeams.service.crn.CrnService;
import com.sequenceiq.redbeams.service.network.NetworkParameterAdder;
import com.sequenceiq.redbeams.service.network.SubnetChooserService;
import com.sequenceiq.redbeams.service.network.SubnetListerService;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class AllocateDatabaseServerV4RequestToDBStackConverterTest {
private static final String OWNER_CRN = "crn:cdp:iam:us-west-1:cloudera:user:external/bob@cloudera.com";
private static final String ENVIRONMENT_CRN = "myenv";
private static final String CLUSTER_CRN = "crn:cdp:datahub:us-west-1:cloudera:stack:id";
private static final String ENVIRONMENT_NAME = "myenv-amazing-env";
private static final Instant NOW = Instant.now();
private static final Map<String, Object> ALLOCATE_REQUEST_PARAMETERS = Map.of("key", "value");
private static final Map<String, Object> SUBNET_ID_REQUEST_PARAMETERS = Map.of("netkey", "netvalue");
private static final String PASSWORD = "password";
private static final String USERNAME = "username";
private static final String DEFAULT_SECURITY_GROUP_ID = "defaultSecurityGroupId";
private static final String UNKNOWN_CLOUD_PLATFORM = "UnknownCloudPlatform";
private static final String USER_EMAIL = "userEmail";
private static final CloudPlatform AWS_CLOUD_PLATFORM = CloudPlatform.AWS;
private static final CloudPlatform AZURE_CLOUD_PLATFORM = CloudPlatform.AZURE;
private static final String CLOUD_PROVIDER_IDENTIFIER_V2 = "cert-id-2";
private static final String CLOUD_PROVIDER_IDENTIFIER_V3 = "cert-id-3";
private static final String CERT_PEM_V2 = "super-cert-2";
private static final String CERT_PEM_V3 = "super-cert-3";
private static final String REGION = "myRegion";
private static final String DATABASE_VENDOR = "postgres";
private static final String REDBEAMS_DB_MAJOR_VERSION = "10";
private static final String FIELD_DB_SERVICE_SUPPORTED_PLATFORMS = "dbServiceSupportedPlatforms";
private static final String FIELD_REDBEAMS_DB_MAJOR_VERSION = "redbeamsDbMajorVersion";
private static final String FIELD_SSL_ENABLED = "sslEnabled";
private static final int MAX_VERSION = 3;
private static final int VERSION_1 = 1;
private static final int VERSION_2 = 2;
private static final int VERSION_3 = 3;
private static final int NO_CERTS = 0;
private static final int SINGLE_CERT = 1;
private static final int TWO_CERTS = 2;
private static final int THREE_CERTS = 3;
@Mock
private EnvironmentService environmentService;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private ProviderParameterCalculator providerParameterCalculator;
@Mock
private Clock clock;
@Mock
private SubnetListerService subnetListerService;
@Mock
private SubnetChooserService subnetChooserService;
@Mock
private UserGeneratorService userGeneratorService;
@Mock
private PasswordGeneratorService passwordGeneratorService;
@Mock
private NetworkParameterAdder networkParameterAdder;
@Mock
private UuidGeneratorService uuidGeneratorService;
@Mock
private CrnUserDetailsService crnUserDetailsService;
@Mock
private CostTagging costTagging;
@Mock
private CrnService crnService;
@Mock
private EntitlementService entitlementService;
@Mock
private AccountTagService accountTagService;
@Mock
private DatabaseServerSslCertificateConfig databaseServerSslCertificateConfig;
@Mock
private X509Certificate x509Certificate;
@InjectMocks
private AllocateDatabaseServerV4RequestToDBStackConverter underTest;
private AllocateDatabaseServerV4Request allocateRequest;
private NetworkV4StackRequest networkRequest;
private DatabaseServerV4StackRequest databaseServerRequest;
private SecurityGroupV4StackRequest securityGroupRequest;
private SslCertificateEntry sslCertificateEntryV2;
private SslCertificateEntry sslCertificateEntryV3;
@BeforeEach
public void setUp() {
ReflectionTestUtils.setField(underTest, FIELD_DB_SERVICE_SUPPORTED_PLATFORMS, Set.of("AWS", "AZURE"));
ReflectionTestUtils.setField(underTest, FIELD_REDBEAMS_DB_MAJOR_VERSION, REDBEAMS_DB_MAJOR_VERSION);
ReflectionTestUtils.setField(underTest, FIELD_SSL_ENABLED, true);
allocateRequest = new AllocateDatabaseServerV4Request();
networkRequest = new NetworkV4StackRequest();
allocateRequest.setNetwork(networkRequest);
databaseServerRequest = new DatabaseServerV4StackRequest();
allocateRequest.setDatabaseServer(databaseServerRequest);
securityGroupRequest = new SecurityGroupV4StackRequest();
databaseServerRequest.setSecurityGroup(securityGroupRequest);
when(crnUserDetailsService.loadUserByUsername(OWNER_CRN)).thenReturn(getCrnUser());
when(uuidGeneratorService.randomUuid()).thenReturn("uuid");
when(accountTagService.list()).thenReturn(new HashMap<>());
when(uuidGeneratorService.uuidVariableParts(anyInt())).thenReturn("parts");
when(entitlementService.internalTenant(anyString())).thenReturn(true);
sslCertificateEntryV2 = new SslCertificateEntry(VERSION_2, CLOUD_PROVIDER_IDENTIFIER_V2, CERT_PEM_V2, x509Certificate);
sslCertificateEntryV3 = new SslCertificateEntry(VERSION_3, CLOUD_PROVIDER_IDENTIFIER_V3, CERT_PEM_V3, x509Certificate);
when(databaseServerSslCertificateConfig.getMaxVersionByCloudPlatformAndRegion(anyString(), eq(REGION))).thenReturn(MAX_VERSION);
when(clock.getCurrentInstant()).thenReturn(NOW);
when(crnService.createCrn(any(DBStack.class))).thenReturn(CrnTestUtil.getDatabaseServerCrnBuilder()
.setAccountId("accountid")
.setResource("1")
.build());
}
@Test
void conversionTestWhenOptionalElementsAreProvided() throws IOException {
setupAllocateRequest(true);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV3);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(AWS_CLOUD_PLATFORM.name())
.withCrn(ENVIRONMENT_CRN)
.withLocation(LocationResponse.LocationResponseBuilder.aLocationResponse().withName(REGION).build())
.withName(ENVIRONMENT_NAME)
.withTag(new TagResponse())
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
assertEquals(allocateRequest.getName(), dbStack.getName());
assertEquals(allocateRequest.getEnvironmentCrn(), dbStack.getEnvironmentId());
assertEquals(REGION, dbStack.getRegion());
assertEquals(AWS_CLOUD_PLATFORM.name(), dbStack.getCloudPlatform());
assertEquals(AWS_CLOUD_PLATFORM.name(), dbStack.getPlatformVariant());
assertEquals(1, dbStack.getParameters().size());
assertEquals("value", dbStack.getParameters().get("key"));
assertEquals(Crn.safeFromString(OWNER_CRN), dbStack.getOwnerCrn());
assertEquals(USER_EMAIL, dbStack.getUserName());
assertEquals(Status.REQUESTED, dbStack.getStatus());
assertEquals(DetailedDBStackStatus.PROVISION_REQUESTED, dbStack.getDbStackStatus().getDetailedDBStackStatus());
assertEquals(NOW.toEpochMilli(), dbStack.getDbStackStatus().getCreated().longValue());
assertEquals("n-uuid", dbStack.getNetwork().getName());
assertEquals(1, dbStack.getNetwork().getAttributes().getMap().size());
assertEquals("netvalue", dbStack.getNetwork().getAttributes().getMap().get("netkey"));
assertEquals("dbsvr-uuid", dbStack.getDatabaseServer().getName());
assertEquals(databaseServerRequest.getInstanceType(), dbStack.getDatabaseServer().getInstanceType());
assertEquals(DatabaseVendor.fromValue(databaseServerRequest.getDatabaseVendor()), dbStack.getDatabaseServer().getDatabaseVendor());
assertEquals("org.postgresql.Driver", dbStack.getDatabaseServer().getConnectionDriver());
assertEquals(databaseServerRequest.getStorageSize(), dbStack.getDatabaseServer().getStorageSize());
assertEquals(databaseServerRequest.getRootUserName(), dbStack.getDatabaseServer().getRootUserName());
assertEquals(databaseServerRequest.getRootUserPassword(), dbStack.getDatabaseServer().getRootPassword());
assertEquals(2, dbStack.getDatabaseServer().getAttributes().getMap().size());
assertEquals("dbvalue", dbStack.getDatabaseServer().getAttributes().getMap().get("dbkey"));
assertEquals(REDBEAMS_DB_MAJOR_VERSION, dbStack.getDatabaseServer().getAttributes().getMap().get("engineVersion"));
assertEquals(securityGroupRequest.getSecurityGroupIds(), dbStack.getDatabaseServer().getSecurityGroup().getSecurityGroupIds());
assertEquals(dbStack.getTags().get(StackTags.class).getUserDefinedTags().get("DistroXKey1"), "DistroXValue1");
verifySsl(dbStack, Set.of(CERT_PEM_V3), CLOUD_PROVIDER_IDENTIFIER_V3);
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
verify(providerParameterCalculator).get(allocateRequest);
verify(providerParameterCalculator).get(networkRequest);
verify(subnetListerService, never()).listSubnets(any(), any());
verify(subnetChooserService, never()).chooseSubnets(anyList(), any(), any());
verify(networkParameterAdder, never()).addSubnetIds(any(), any(), any(), any());
verify(userGeneratorService, never()).generateUserName();
verify(passwordGeneratorService, never()).generatePassword(any());
}
private CrnUser getCrnUser() {
return new CrnUser("", "", "", USER_EMAIL, "", "");
}
@Test
void conversionTestWhenOptionalElementsGenerated() throws IOException {
setupAllocateRequest(false);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV3);
List<CloudSubnet> cloudSubnets = List.of(
new CloudSubnet("subnet-1", "", "az-a", ""),
new CloudSubnet("subnet-2", "", "az-b", "")
);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(AWS_CLOUD_PLATFORM.name())
.withName(ENVIRONMENT_NAME)
.withCrn(ENVIRONMENT_CRN)
.withTag(new TagResponse())
.withLocation(LocationResponse.LocationResponseBuilder.aLocationResponse().withName(REGION).build())
.withSecurityAccess(SecurityAccessResponse.builder().withDefaultSecurityGroupId(DEFAULT_SECURITY_GROUP_ID).build())
.withNetwork(EnvironmentNetworkResponse.builder()
.withSubnetMetas(
Map.of(
"subnet-1", cloudSubnets.get(0),
"subnet-2", cloudSubnets.get(1)
)
)
.build())
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
when(subnetListerService.listSubnets(any(), any())).thenReturn(cloudSubnets);
when(subnetChooserService.chooseSubnets(any(), any(), any())).thenReturn(cloudSubnets);
when(networkParameterAdder.addSubnetIds(any(), any(), any(), any())).thenReturn(SUBNET_ID_REQUEST_PARAMETERS);
when(userGeneratorService.generateUserName()).thenReturn(USERNAME);
when(passwordGeneratorService.generatePassword(any())).thenReturn(PASSWORD);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
assertEquals(ENVIRONMENT_NAME + "-dbstck-parts", dbStack.getName());
assertEquals(PASSWORD, dbStack.getDatabaseServer().getRootPassword());
assertEquals(USERNAME, dbStack.getDatabaseServer().getRootUserName());
assertEquals("n-uuid", dbStack.getNetwork().getName());
assertEquals(1, dbStack.getNetwork().getAttributes().getMap().size());
assertEquals("netvalue", dbStack.getNetwork().getAttributes().getMap().get("netkey"));
assertThat(dbStack.getDatabaseServer().getSecurityGroup().getSecurityGroupIds()).hasSize(1);
assertEquals(dbStack.getDatabaseServer().getSecurityGroup().getSecurityGroupIds().iterator().next(), DEFAULT_SECURITY_GROUP_ID);
assertEquals(dbStack.getTags().get(StackTags.class).getUserDefinedTags().get("DistroXKey1"), "DistroXValue1");
verifySsl(dbStack, Set.of(CERT_PEM_V3), CLOUD_PROVIDER_IDENTIFIER_V3);
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
verify(providerParameterCalculator).get(allocateRequest);
verify(providerParameterCalculator, never()).get(networkRequest);
verify(subnetListerService).listSubnets(any(), any());
verify(subnetChooserService).chooseSubnets(anyList(), any(), any());
verify(networkParameterAdder).addSubnetIds(any(), any(), any(), any());
verify(userGeneratorService).generateUserName();
verify(passwordGeneratorService).generatePassword(any());
}
@Test
void conversionTestWhenRequestAndEnvironmentCloudPlatformsDiffer() {
allocateRequest.setCloudPlatform(AWS_CLOUD_PLATFORM);
allocateRequest.setTags(new HashMap<>());
allocateRequest.setEnvironmentCrn(ENVIRONMENT_CRN);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(UNKNOWN_CLOUD_PLATFORM)
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
BadRequestException badRequestException = assertThrows(BadRequestException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(badRequestException).hasMessage("Cloud platform of the request AWS and the environment " + UNKNOWN_CLOUD_PLATFORM + " do not match.");
}
@Test
void conversionTestWhenUnsupportedCloudPlatform() {
allocateRequest.setCloudPlatform(CloudPlatform.YARN);
allocateRequest.setTags(new HashMap<>());
allocateRequest.setEnvironmentCrn(ENVIRONMENT_CRN);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(CloudPlatform.YARN.name())
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
BadRequestException badRequestException = assertThrows(BadRequestException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(badRequestException).hasMessage("Cloud platform YARN not supported yet.");
}
static Object[][] conversionTestWhenSslDisabledDataProvider() {
return new Object[][]{
// testCaseName fieldSslEnabled sslConfigV4Request
{"false, null", false, null},
{"true, null", true, null},
{"false, request with sslMode=null", false, new SslConfigV4Request()},
{"true, request with sslMode=null", true, new SslConfigV4Request()},
{"false, request with sslMode=DISABLED", false, createSslConfigV4Request(SslMode.DISABLED)},
{"true, request with sslMode=DISABLED", true, createSslConfigV4Request(SslMode.DISABLED)},
{"false, request with sslMode=ENABLED", false, createSslConfigV4Request(SslMode.ENABLED)},
};
}
@ParameterizedTest(name = "{0}")
@MethodSource("conversionTestWhenSslDisabledDataProvider")
void conversionTestWhenSslDisabled(String testCaseName, boolean fieldSslEnabled, SslConfigV4Request sslConfigV4Request) {
setupMinimalValid(sslConfigV4Request, AWS_CLOUD_PLATFORM);
ReflectionTestUtils.setField(underTest, FIELD_SSL_ENABLED, fieldSslEnabled);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
SslConfig sslConfig = dbStack.getSslConfig();
assertThat(sslConfig).isNotNull();
Set<String> sslCertificates = sslConfig.getSslCertificates();
assertThat(sslCertificates).isNotNull();
assertThat(sslCertificates).isEmpty();
assertThat(sslConfig.getSslCertificateType()).isEqualTo(SslCertificateType.NONE);
}
private void setupMinimalValid(SslConfigV4Request sslConfigV4Request, CloudPlatform cloudPlatform) {
allocateRequest.setEnvironmentCrn(ENVIRONMENT_CRN);
allocateRequest.setTags(new HashMap<>());
allocateRequest.setClusterCrn(CLUSTER_CRN);
allocateRequest.setSslConfig(sslConfigV4Request);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(cloudPlatform.name())
.withCrn(ENVIRONMENT_CRN)
.withLocation(LocationResponse.LocationResponseBuilder.aLocationResponse().withName(REGION).build())
.withName(ENVIRONMENT_NAME)
.withTag(new TagResponse())
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
databaseServerRequest.setDatabaseVendor(DATABASE_VENDOR);
}
@Test
void conversionTestWhenSslEnabledAndAwsAndNoCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(NO_CERTS);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
verifySsl(dbStack, Set.of(), null);
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCert() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndSingleCertReturnedInternal(AWS_CLOUD_PLATFORM.name(), SINGLE_CERT);
}
private void conversionTestWhenSslEnabledAndSingleCertReturnedInternal(String cloudPlatform, int numOfCerts) {
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(cloudPlatform, REGION)).thenReturn(numOfCerts);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(cloudPlatform, REGION, VERSION_3)).thenReturn(sslCertificateEntryV3);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
verifySsl(dbStack, Set.of(CERT_PEM_V3), CLOUD_PROVIDER_IDENTIFIER_V3);
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCertErrorNullCert() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3)).thenReturn(null);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException).hasMessage("Could not find SSL certificate version 3 for cloud platform \"AWS\"");
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCertErrorVersionMismatch() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV2);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException).hasMessage("SSL certificate version mismatch for cloud platform \"AWS\": expected=3, actual=2");
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCertErrorBlankCloudProviderIdentifier() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
SslCertificateEntry sslCertificateEntryV3Broken = new SslCertificateEntry(VERSION_3, "", CERT_PEM_V3, x509Certificate);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV3Broken);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException).hasMessage("Blank CloudProviderIdentifier in SSL certificate version 3 for cloud platform \"AWS\"");
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCertErrorBlankPem() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
SslCertificateEntry sslCertificateEntryV3Broken = new SslCertificateEntry(VERSION_3, CLOUD_PROVIDER_IDENTIFIER_V3, "", x509Certificate);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV3Broken);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException).hasMessage("Blank PEM in SSL certificate version 3 for cloud platform \"AWS\"");
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndSingleCert() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndSingleCertReturnedInternal(AZURE_CLOUD_PLATFORM.name(), SINGLE_CERT);
}
@Test
void conversionTestWhenSslEnabledAndAwsAndTwoCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndSingleCertReturnedInternal(AWS_CLOUD_PLATFORM.name(), TWO_CERTS);
}
@Test
void conversionTestWhenSslEnabledAndAwsAndThreeCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndSingleCertReturnedInternal(AWS_CLOUD_PLATFORM.name(), THREE_CERTS);
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndTwoCertsReturnedInternal(AZURE_CLOUD_PLATFORM.name(), TWO_CERTS);
}
private void conversionTestWhenSslEnabledAndTwoCertsReturnedInternal(String cloudPlatform, int numOfCerts) {
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(cloudPlatform, REGION)).thenReturn(numOfCerts);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(cloudPlatform, REGION, VERSION_2, VERSION_3))
.thenReturn(Set.of(sslCertificateEntryV2, sslCertificateEntryV3));
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
verifySsl(dbStack, Set.of(CERT_PEM_V2, CERT_PEM_V3), CLOUD_PROVIDER_IDENTIFIER_V3);
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCertsErrorNullCert() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AZURE_CLOUD_PLATFORM.name(), REGION)).thenReturn(TWO_CERTS);
Set<SslCertificateEntry> certs = new HashSet<>();
certs.add(sslCertificateEntryV3);
certs.add(null);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(AZURE_CLOUD_PLATFORM.name(), REGION, VERSION_2, VERSION_3))
.thenReturn(certs);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException)
.hasMessage("Could not find SSL certificate(s) when requesting versions [2, 3] for cloud platform \"AZURE\": expected 2 certificates, got 1");
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCertsErrorFewerCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AZURE_CLOUD_PLATFORM.name(), REGION)).thenReturn(TWO_CERTS);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(AZURE_CLOUD_PLATFORM.name(), REGION, VERSION_2, VERSION_3))
.thenReturn(Set.of(sslCertificateEntryV3));
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException)
.hasMessage("Could not find SSL certificate(s) when requesting versions [2, 3] for cloud platform \"AZURE\": expected 2 certificates, got 1");
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCertsErrorDuplicatedCertPem() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
SslCertificateEntry sslCertificateEntryV2DuplicateOfV3 = new SslCertificateEntry(VERSION_2, CLOUD_PROVIDER_IDENTIFIER_V3, CERT_PEM_V3, x509Certificate);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AZURE_CLOUD_PLATFORM.name(), REGION)).thenReturn(TWO_CERTS);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(AZURE_CLOUD_PLATFORM.name(), REGION, VERSION_2, VERSION_3))
.thenReturn(Set.of(sslCertificateEntryV2DuplicateOfV3, sslCertificateEntryV3));
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException)
.hasMessage("Received duplicated SSL certificate PEM when requesting versions [2, 3] for cloud platform \"AZURE\"");
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCertsErrorVersionMismatch() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
SslCertificateEntry sslCertificateEntryV2Broken = new SslCertificateEntry(VERSION_1, CLOUD_PROVIDER_IDENTIFIER_V2, CERT_PEM_V2, x509Certificate);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AZURE_CLOUD_PLATFORM.name(), REGION)).thenReturn(TWO_CERTS);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(AZURE_CLOUD_PLATFORM.name(), REGION, VERSION_2, VERSION_3))
.thenReturn(Set.of(sslCertificateEntryV2Broken, sslCertificateEntryV3));
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException)
.hasMessage("Could not find SSL certificate version 2 for cloud platform \"AZURE\"");
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndThreeCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndTwoCertsReturnedInternal(AZURE_CLOUD_PLATFORM.name(), THREE_CERTS);
}
private void verifySsl(DBStack dbStack, Set<String> sslCertificatesExpected, String cloudProviderIdentifierExpected) {
SslConfig sslConfig = dbStack.getSslConfig();
assertThat(sslConfig).isNotNull();
Set<String> sslCertificates = sslConfig.getSslCertificates();
assertThat(sslCertificates).isNotNull();
assertThat(sslCertificates).isEqualTo(sslCertificatesExpected);
assertThat(sslConfig.getSslCertificateType()).isEqualTo(SslCertificateType.CLOUD_PROVIDER_OWNED);
assertThat(sslConfig.getSslCertificateActiveVersion()).isEqualTo(MAX_VERSION);
assertThat(sslConfig.getSslCertificateActiveCloudProviderIdentifier()).isEqualTo(cloudProviderIdentifierExpected);
}
private void setupAllocateRequest(boolean provideOptionalFields) {
allocateRequest.setEnvironmentCrn(ENVIRONMENT_CRN);
allocateRequest.setTags(Map.of("DistroXKey1", "DistroXValue1"));
allocateRequest.setClusterCrn(CLUSTER_CRN);
if (provideOptionalFields) {
allocateRequest.setName("myallocation");
AwsNetworkV4Parameters awsNetworkV4Parameters = new AwsNetworkV4Parameters();
awsNetworkV4Parameters.setSubnetId("subnet-1,subnet-2");
allocateRequest.getNetwork().setAws(awsNetworkV4Parameters);
setupProviderCalculatorResponse(networkRequest, SUBNET_ID_REQUEST_PARAMETERS);
} else {
allocateRequest.setNetwork(null);
allocateRequest.getDatabaseServer().setSecurityGroup(null);
}
allocateRequest.setSslConfig(createSslConfigV4Request(SslMode.ENABLED));
databaseServerRequest.setInstanceType("db.m3.medium");
databaseServerRequest.setDatabaseVendor(DATABASE_VENDOR);
databaseServerRequest.setConnectionDriver("org.postgresql.Driver");
databaseServerRequest.setStorageSize(50L);
if (provideOptionalFields) {
databaseServerRequest.setRootUserName("root");
databaseServerRequest.setRootUserPassword("cloudera");
}
setupProviderCalculatorResponse(allocateRequest, ALLOCATE_REQUEST_PARAMETERS);
setupProviderCalculatorResponse(databaseServerRequest, new HashMap<>(Map.of("dbkey", "dbvalue")));
securityGroupRequest.setSecurityGroupIds(Set.of("sg-1234"));
}
private static SslConfigV4Request createSslConfigV4Request(SslMode sslMode) {
SslConfigV4Request sslConfigV4Request = new SslConfigV4Request();
sslConfigV4Request.setSslMode(sslMode);
return sslConfigV4Request;
}
private void setupProviderCalculatorResponse(ProviderParametersBase request, Map<String, Object> response) {
MappableBase providerCalculatorResponse = mock(MappableBase.class);
when(providerCalculatorResponse.asMap()).thenReturn(response);
when(providerParameterCalculator.get(request)).thenReturn(providerCalculatorResponse);
}
}
| hortonworks/cloudbreak | redbeams/src/test/java/com/sequenceiq/redbeams/converter/stack/AllocateDatabaseServerV4RequestToDBStackConverterTest.java | Java | apache-2.0 | 37,660 |
package padroesprojeto.criacional.abstractfactorymethod.outroexemplo.model;
/**
* Created by felansu on 03/06/2015.
*/
public interface Roupa {
void vestir();
}
| felansu/calmanddev | src/main/padroesprojeto/criacional/abstractfactorymethod/outroexemplo/model/Roupa.java | Java | apache-2.0 | 168 |
/*
* 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.accumulo.core.conf;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.accumulo.core.conf.PropertyType.PortRange;
import org.apache.accumulo.core.spi.scan.SimpleScanDispatcher;
import org.apache.accumulo.core.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
/**
* A configuration object.
*/
public abstract class AccumuloConfiguration implements Iterable<Entry<String,String>> {
private static class PrefixProps {
final long updateCount;
final Map<String,String> props;
PrefixProps(Map<String,String> props, long updateCount) {
this.updateCount = updateCount;
this.props = props;
}
}
private volatile EnumMap<Property,PrefixProps> cachedPrefixProps = new EnumMap<>(Property.class);
private Lock prefixCacheUpdateLock = new ReentrantLock();
private static final Logger log = LoggerFactory.getLogger(AccumuloConfiguration.class);
/**
* Gets a property value from this configuration.
*
* <p>
* Note: this is inefficient, but convenient on occasion. For retrieving multiple properties, use
* {@link #getProperties(Map, Predicate)} with a custom filter.
*
* @param property
* property to get
* @return property value
*/
public String get(String property) {
Map<String,String> propMap = new HashMap<>(1);
getProperties(propMap, key -> Objects.equals(property, key));
return propMap.get(property);
}
/**
* Gets a property value from this configuration.
*
* @param property
* property to get
* @return property value
*/
public abstract String get(Property property);
/**
* Given a property and a deprecated property determine which one to use base on which one is set.
*/
public Property resolve(Property property, Property deprecatedProperty) {
if (isPropertySet(property, true)) {
return property;
} else if (isPropertySet(deprecatedProperty, true)) {
return deprecatedProperty;
} else {
return property;
}
}
/**
* Returns property key/value pairs in this configuration. The pairs include those defined in this
* configuration which pass the given filter, and those supplied from the parent configuration
* which are not included from here.
*
* @param props
* properties object to populate
* @param filter
* filter for accepting properties from this configuration
*/
public abstract void getProperties(Map<String,String> props, Predicate<String> filter);
/**
* Returns an iterator over property key/value pairs in this configuration. Some implementations
* may elect to omit properties.
*
* @return iterator over properties
*/
@Override
public Iterator<Entry<String,String>> iterator() {
Predicate<String> all = x -> true;
TreeMap<String,String> entries = new TreeMap<>();
getProperties(entries, all);
return entries.entrySet().iterator();
}
private static void checkType(Property property, PropertyType type) {
if (!property.getType().equals(type)) {
String msg = "Configuration method intended for type " + type + " called with a "
+ property.getType() + " argument (" + property.getKey() + ")";
IllegalArgumentException err = new IllegalArgumentException(msg);
log.error(msg, err);
throw err;
}
}
/**
* Each time configuration changes, this counter should increase. Anything that caches information
* that is derived from configuration can use this method to know when to update.
*/
public long getUpdateCount() {
return 0;
}
/**
* Gets all properties under the given prefix in this configuration.
*
* @param property
* prefix property, must be of type PropertyType.PREFIX
* @return a map of property keys to values
* @throws IllegalArgumentException
* if property is not a prefix
*/
public Map<String,String> getAllPropertiesWithPrefix(Property property) {
checkType(property, PropertyType.PREFIX);
PrefixProps prefixProps = cachedPrefixProps.get(property);
if (prefixProps == null || prefixProps.updateCount != getUpdateCount()) {
prefixCacheUpdateLock.lock();
try {
// Very important that update count is read before getting properties. Also only read it
// once.
long updateCount = getUpdateCount();
prefixProps = cachedPrefixProps.get(property);
if (prefixProps == null || prefixProps.updateCount != updateCount) {
Map<String,String> propMap = new HashMap<>();
// The reason this caching exists is to avoid repeatedly making this expensive call.
getProperties(propMap, key -> key.startsWith(property.getKey()));
propMap = Map.copyOf(propMap);
// So that locking is not needed when reading from enum map, always create a new one.
// Construct and populate map using a local var so its not visible
// until ready.
EnumMap<Property,PrefixProps> localPrefixes = new EnumMap<>(Property.class);
// carry forward any other cached prefixes
localPrefixes.putAll(cachedPrefixProps);
// put the updates
prefixProps = new PrefixProps(propMap, updateCount);
localPrefixes.put(property, prefixProps);
// make the newly constructed map available
cachedPrefixProps = localPrefixes;
}
} finally {
prefixCacheUpdateLock.unlock();
}
}
return prefixProps.props;
}
/**
* Gets a property of type {@link PropertyType#BYTES} or {@link PropertyType#MEMORY}, interpreting
* the value properly.
*
* @param property
* Property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public long getAsBytes(Property property) {
String memString = get(property);
if (property.getType() == PropertyType.MEMORY) {
return ConfigurationTypeHelper.getMemoryAsBytes(memString);
} else if (property.getType() == PropertyType.BYTES) {
return ConfigurationTypeHelper.getFixedMemoryAsBytes(memString);
} else {
throw new IllegalArgumentException(property.getKey() + " is not of BYTES or MEMORY type");
}
}
/**
* Gets a property of type {@link PropertyType#TIMEDURATION}, interpreting the value properly.
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public long getTimeInMillis(Property property) {
checkType(property, PropertyType.TIMEDURATION);
return ConfigurationTypeHelper.getTimeInMillis(get(property));
}
/**
* Gets a property of type {@link PropertyType#BOOLEAN}, interpreting the value properly (using
* <code>Boolean.parseBoolean()</code>).
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public boolean getBoolean(Property property) {
checkType(property, PropertyType.BOOLEAN);
return Boolean.parseBoolean(get(property));
}
/**
* Gets a property of type {@link PropertyType#FRACTION}, interpreting the value properly.
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public double getFraction(Property property) {
checkType(property, PropertyType.FRACTION);
return ConfigurationTypeHelper.getFraction(get(property));
}
/**
* Gets a property of type {@link PropertyType#PORT}, interpreting the value properly (as an
* integer within the range of non-privileged ports).
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public int[] getPort(Property property) {
checkType(property, PropertyType.PORT);
String portString = get(property);
int[] ports = null;
try {
Pair<Integer,Integer> portRange = PortRange.parse(portString);
int low = portRange.getFirst();
int high = portRange.getSecond();
ports = new int[high - low + 1];
for (int i = 0, j = low; j <= high; i++, j++) {
ports[i] = j;
}
} catch (IllegalArgumentException e) {
ports = new int[1];
try {
int port = Integer.parseInt(portString);
if (port == 0) {
ports[0] = port;
} else {
if (port < 1024 || port > 65535) {
log.error("Invalid port number {}; Using default {}", port, property.getDefaultValue());
ports[0] = Integer.parseInt(property.getDefaultValue());
} else {
ports[0] = port;
}
}
} catch (NumberFormatException e1) {
throw new IllegalArgumentException("Invalid port syntax. Must be a single positive "
+ "integers or a range (M-N) of positive integers");
}
}
return ports;
}
/**
* Gets a property of type {@link PropertyType#COUNT}, interpreting the value properly (as an
* integer).
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public int getCount(Property property) {
checkType(property, PropertyType.COUNT);
String countString = get(property);
return Integer.parseInt(countString);
}
/**
* Gets a property of type {@link PropertyType#PATH}.
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public String getPath(Property property) {
checkType(property, PropertyType.PATH);
String pathString = get(property);
if (pathString == null) {
return null;
}
if (pathString.contains("$ACCUMULO_")) {
throw new IllegalArgumentException("Environment variable interpolation not supported here. "
+ "Consider using '${env:ACCUMULO_HOME}' or similar in your configuration file.");
}
return pathString;
}
/**
* Gets the maximum number of files per tablet from this configuration.
*
* @return maximum number of files per tablet
* @see Property#TABLE_FILE_MAX
* @see Property#TSERV_SCAN_MAX_OPENFILES
*/
public int getMaxFilesPerTablet() {
int maxFilesPerTablet = getCount(Property.TABLE_FILE_MAX);
if (maxFilesPerTablet <= 0) {
maxFilesPerTablet = getCount(Property.TSERV_SCAN_MAX_OPENFILES) - 1;
log.debug("Max files per tablet {}", maxFilesPerTablet);
}
return maxFilesPerTablet;
}
public class ScanExecutorConfig {
public final String name;
public final int maxThreads;
public final OptionalInt priority;
public final Optional<String> prioritizerClass;
public final Map<String,String> prioritizerOpts;
public ScanExecutorConfig(String name, int maxThreads, OptionalInt priority,
Optional<String> comparatorFactory, Map<String,String> comparatorFactoryOpts) {
this.name = name;
this.maxThreads = maxThreads;
this.priority = priority;
this.prioritizerClass = comparatorFactory;
this.prioritizerOpts = comparatorFactoryOpts;
}
/**
* Re-reads the max threads from the configuration that created this class
*/
public int getCurrentMaxThreads() {
Integer depThreads = getDeprecatedScanThreads(name);
if (depThreads != null) {
return depThreads;
}
String prop = Property.TSERV_SCAN_EXECUTORS_PREFIX.getKey() + name + "." + SCAN_EXEC_THREADS;
String val = getAllPropertiesWithPrefix(Property.TSERV_SCAN_EXECUTORS_PREFIX).get(prop);
return Integer.parseInt(val);
}
}
public boolean isPropertySet(Property prop, boolean cacheAndWatch) {
throw new UnsupportedOperationException();
}
// deprecation property warning could get spammy in tserver so only warn once
boolean depPropWarned = false;
@SuppressWarnings("deprecation")
Integer getDeprecatedScanThreads(String name) {
Property prop;
Property deprecatedProp;
if (name.equals(SimpleScanDispatcher.DEFAULT_SCAN_EXECUTOR_NAME)) {
prop = Property.TSERV_SCAN_EXECUTORS_DEFAULT_THREADS;
deprecatedProp = Property.TSERV_READ_AHEAD_MAXCONCURRENT;
} else if (name.equals("meta")) {
prop = Property.TSERV_SCAN_EXECUTORS_META_THREADS;
deprecatedProp = Property.TSERV_METADATA_READ_AHEAD_MAXCONCURRENT;
} else {
return null;
}
if (!isPropertySet(prop, true) && isPropertySet(deprecatedProp, true)) {
if (!depPropWarned) {
depPropWarned = true;
log.warn("Property {} is deprecated, use {} instead.", deprecatedProp.getKey(),
prop.getKey());
}
return Integer.valueOf(get(deprecatedProp));
} else if (isPropertySet(prop, true) && isPropertySet(deprecatedProp, true) && !depPropWarned) {
depPropWarned = true;
log.warn("Deprecated property {} ignored because {} is set", deprecatedProp.getKey(),
prop.getKey());
}
return null;
}
private static class RefCount<T> {
T obj;
long count;
RefCount(long c, T r) {
this.count = c;
this.obj = r;
}
}
private class DeriverImpl<T> implements Deriver<T> {
private final AtomicReference<RefCount<T>> refref = new AtomicReference<>();
private final Function<AccumuloConfiguration,T> converter;
DeriverImpl(Function<AccumuloConfiguration,T> converter) {
this.converter = converter;
}
/**
* This method was written with the goal of avoiding thread contention and minimizing
* recomputation. Configuration can be accessed frequently by many threads. Ideally, threads
* working on unrelated task would not impeded each other because of accessing config.
*
* To avoid thread contention, synchronization and needless calls to compare and set were
* avoided. For example if 100 threads are all calling compare and set in a loop this could
* cause significant contention.
*/
@Override
public T derive() {
// very important to obtain this before possibly recomputing object
long uc = getUpdateCount();
RefCount<T> rc = refref.get();
if (rc == null || rc.count != uc) {
T newObj = converter.apply(AccumuloConfiguration.this);
// very important to record the update count that was obtained before recomputing.
RefCount<T> nrc = new RefCount<>(uc, newObj);
/*
* The return value of compare and set is intentionally ignored here. This code could loop
* calling compare and set inorder to avoid returning a stale object. However after this
* function returns, the object could immediately become stale. So in the big picture stale
* objects can not be prevented. Looping here could cause thread contention, but it would
* not solve the overall stale object problem. That is why the return value was ignored. The
* following line is a least effort attempt to make the result of this recomputation
* available to the next caller.
*/
refref.compareAndSet(rc, nrc);
return nrc.obj;
}
return rc.obj;
}
}
/**
* Automatically regenerates an object whenever configuration changes. When configuration is not
* changing, keeps returning the same object. Implementations should be thread safe and eventually
* consistent. See {@link AccumuloConfiguration#newDeriver(Function)}
*/
public interface Deriver<T> {
T derive();
}
/**
* Enables deriving an object from configuration and automatically deriving a new object any time
* configuration changes.
*
* @param converter
* This functions is used to create an object from configuration. A reference to this
* function will be kept and called by the returned deriver.
* @return The returned supplier will automatically re-derive the object any time this
* configuration changes. When configuration is not changing, the same object is returned.
*
*/
public <T> Deriver<T> newDeriver(Function<AccumuloConfiguration,T> converter) {
return new DeriverImpl<>(converter);
}
private static final String SCAN_EXEC_THREADS = "threads";
private static final String SCAN_EXEC_PRIORITY = "priority";
private static final String SCAN_EXEC_PRIORITIZER = "prioritizer";
private static final String SCAN_EXEC_PRIORITIZER_OPTS = "prioritizer.opts.";
public Collection<ScanExecutorConfig> getScanExecutors() {
Map<String,Map<String,String>> propsByName = new HashMap<>();
List<ScanExecutorConfig> scanResources = new ArrayList<>();
for (Entry<String,String> entry : getAllPropertiesWithPrefix(
Property.TSERV_SCAN_EXECUTORS_PREFIX).entrySet()) {
String suffix =
entry.getKey().substring(Property.TSERV_SCAN_EXECUTORS_PREFIX.getKey().length());
String[] tokens = suffix.split("\\.", 2);
String name = tokens[0];
propsByName.computeIfAbsent(name, k -> new HashMap<>()).put(tokens[1], entry.getValue());
}
for (Entry<String,Map<String,String>> entry : propsByName.entrySet()) {
String name = entry.getKey();
Integer threads = null;
Integer prio = null;
String prioritizerClass = null;
Map<String,String> prioritizerOpts = new HashMap<>();
for (Entry<String,String> subEntry : entry.getValue().entrySet()) {
String opt = subEntry.getKey();
String val = subEntry.getValue();
if (opt.equals(SCAN_EXEC_THREADS)) {
Integer depThreads = getDeprecatedScanThreads(name);
if (depThreads == null) {
threads = Integer.parseInt(val);
} else {
threads = depThreads;
}
} else if (opt.equals(SCAN_EXEC_PRIORITY)) {
prio = Integer.parseInt(val);
} else if (opt.equals(SCAN_EXEC_PRIORITIZER)) {
prioritizerClass = val;
} else if (opt.startsWith(SCAN_EXEC_PRIORITIZER_OPTS)) {
String key = opt.substring(SCAN_EXEC_PRIORITIZER_OPTS.length());
if (key.isEmpty()) {
throw new IllegalStateException("Invalid scan executor option : " + opt);
}
prioritizerOpts.put(key, val);
} else {
throw new IllegalStateException("Unkown scan executor option : " + opt);
}
}
Preconditions.checkArgument(threads != null && threads > 0,
"Scan resource %s incorrectly specified threads", name);
scanResources.add(new ScanExecutorConfig(name, threads,
prio == null ? OptionalInt.empty() : OptionalInt.of(prio),
Optional.ofNullable(prioritizerClass), prioritizerOpts));
}
return scanResources;
}
/**
* Invalidates the <code>ZooCache</code> used for storage and quick retrieval of properties for
* this configuration.
*/
public void invalidateCache() {}
}
| ivakegg/accumulo | core/src/main/java/org/apache/accumulo/core/conf/AccumuloConfiguration.java | Java | apache-2.0 | 20,603 |
/**
* Copyright (c) 2011 Jonathan Leibiusky
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.navercorp.redis.cluster;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.navercorp.redis.cluster.pipeline.BuilderFactory;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.Tuple;
/**
* The Class RedisCluster.
*
* @author jaehong.kim
*/
public class RedisCluster extends BinaryRedisCluster implements
RedisClusterCommands {
/**
* Instantiates a new redis cluster.
*
* @param host the host
*/
public RedisCluster(final String host) {
super(host);
}
/**
* Instantiates a new redis cluster.
*
* @param host the host
* @param port the port
*/
public RedisCluster(final String host, final int port) {
super(host, port);
}
/**
* Instantiates a new redis cluster.
*
* @param host the host
* @param port the port
* @param timeout the timeout
*/
public RedisCluster(final String host, final int port, final int timeout) {
super(host, port, timeout);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Keys
public Long del(final String... keys) {
client.del(keys);
return client.getIntegerReply();
}
public Boolean exists(final String key) {
client.exists(key);
return client.getIntegerReply() == 1;
}
public Long expire(final String key, final int seconds) {
client.expire(key, seconds);
return client.getIntegerReply();
}
public Long expireAt(final String key, final long secondsTimestamp) {
client.expireAt(key, secondsTimestamp);
return client.getIntegerReply();
}
public Long pexpire(final String key, final long milliseconds) {
client.pexpire(key, milliseconds);
return client.getIntegerReply();
}
public Long pexpireAt(final String key, final long millisecondsTimestamp) {
client.pexpireAt(key, millisecondsTimestamp);
return client.getIntegerReply();
}
public Long objectRefcount(String string) {
client.objectRefcount(string);
return client.getIntegerReply();
}
public String objectEncoding(String string) {
client.objectEncoding(string);
return client.getBulkReply();
}
public Long objectIdletime(String string) {
client.objectIdletime(string);
return client.getIntegerReply();
}
public Long ttl(final String key) {
client.ttl(key);
return client.getIntegerReply();
}
public Long pttl(final String key) {
client.pttl(key);
return client.getIntegerReply();
}
public String type(final String key) {
client.type(key);
return client.getStatusCodeReply();
}
public Long persist(final String key) {
client.persist(key);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Strings
public Long append(final String key, final String value) {
client.append(key, value);
return client.getIntegerReply();
}
public Long decr(final String key) {
client.decr(key);
return client.getIntegerReply();
}
public Long decrBy(final String key, final long integer) {
client.decrBy(key, integer);
return client.getIntegerReply();
}
public String get(final String key) {
client.get(key);
return client.getBulkReply();
}
public Boolean getbit(String key, long offset) {
client.getbit(key, offset);
return client.getIntegerReply() == 1;
}
public String getrange(String key, long startOffset, long endOffset) {
client.getrange(key, startOffset, endOffset);
return client.getBulkReply();
}
public String substr(final String key, final int start, final int end) {
client.substr(key, start, end);
return client.getBulkReply();
}
public String getSet(final String key, final String value) {
client.getSet(key, value);
return client.getBulkReply();
}
public Long incr(final String key) {
client.incr(key);
return client.getIntegerReply();
}
public Long incrBy(final String key, final long integer) {
client.incrBy(key, integer);
return client.getIntegerReply();
}
public Double incrByFloat(final String key, final double increment) {
client.incrByFloat(key, increment);
String reply = client.getBulkReply();
return (reply != null ? new Double(reply) : null);
}
public String set(final String key, String value) {
client.set(key, value);
return client.getStatusCodeReply();
}
public Boolean setbit(String key, long offset, boolean value) {
client.setbit(key, offset, value);
return client.getIntegerReply() == 1;
}
public String setex(final String key, final int seconds, final String value) {
client.setex(key, seconds, value);
return client.getStatusCodeReply();
}
public Long setnx(final String key, final String value) {
client.setnx(key, value);
return client.getIntegerReply();
}
public Long setrange(String key, long offset, String value) {
client.setrange(key, offset, value);
return client.getIntegerReply();
}
public Long strlen(final String key) {
client.strlen(key);
return client.getIntegerReply();
}
public List<String> mget(final String... keys) {
client.mget(keys);
return client.getMultiBulkReply();
}
public String psetex(final String key, final long milliseconds,
final String value) {
client.psetex(key, milliseconds, value);
return client.getStatusCodeReply();
}
public String mset(String... keysvalues) {
client.mset(keysvalues);
return client.getStatusCodeReply();
}
public Long bitcount(final String key) {
client.bitcount(key);
return client.getIntegerReply();
}
public Long bitcount(final String key, long start, long end) {
client.bitcount(key, start, end);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hashes
public Long hdel(final String key, final String... fields) {
client.hdel(key, fields);
return client.getIntegerReply();
}
public Boolean hexists(final String key, final String field) {
client.hexists(key, field);
return client.getIntegerReply() == 1;
}
public String hget(final String key, final String field) {
client.hget(key, field);
return client.getBulkReply();
}
public Map<String, String> hgetAll(final String key) {
client.hgetAll(key);
return BuilderFactory.STRING_MAP
.build(client.getBinaryMultiBulkReply());
}
public Long hincrBy(final String key, final String field, final long value) {
client.hincrBy(key, field, value);
return client.getIntegerReply();
}
public Double hincrByFloat(final String key, final String field,
double increment) {
client.hincrByFloat(key, field, increment);
String reply = client.getBulkReply();
return (reply != null ? new Double(reply) : null);
}
public Set<String> hkeys(final String key) {
client.hkeys(key);
return BuilderFactory.STRING_SET
.build(client.getBinaryMultiBulkReply());
}
public Long hlen(final String key) {
client.hlen(key);
return client.getIntegerReply();
}
public List<String> hmget(final String key, final String... fields) {
client.hmget(key, fields);
return client.getMultiBulkReply();
}
public String hmset(final String key, final Map<String, String> hash) {
client.hmset(key, hash);
return client.getStatusCodeReply();
}
public Long hset(final String key, final String field, final String value) {
client.hset(key, field, value);
return client.getIntegerReply();
}
public Long hsetnx(final String key, final String field, final String value) {
client.hsetnx(key, field, value);
return client.getIntegerReply();
}
public List<String> hvals(final String key) {
client.hvals(key);
final List<String> lresult = client.getMultiBulkReply();
return lresult;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Lists
public String lindex(final String key, final long index) {
client.lindex(key, index);
return client.getBulkReply();
}
public Long linsert(final String key, final LIST_POSITION where,
final String pivot, final String value) {
client.linsert(key, where, pivot, value);
return client.getIntegerReply();
}
public Long llen(final String key) {
client.llen(key);
return client.getIntegerReply();
}
public String lpop(final String key) {
client.lpop(key);
return client.getBulkReply();
}
public Long lpush(final String key, final String... strings) {
client.lpush(key, strings);
return client.getIntegerReply();
}
public Long lpushx(final String key, final String string) {
client.lpushx(key, string);
return client.getIntegerReply();
}
public List<String> lrange(final String key, final long start,
final long end) {
client.lrange(key, start, end);
return client.getMultiBulkReply();
}
public Long lrem(final String key, final long count, final String value) {
client.lrem(key, count, value);
return client.getIntegerReply();
}
public String lset(final String key, final long index, final String value) {
client.lset(key, index, value);
return client.getStatusCodeReply();
}
public String ltrim(final String key, final long start, final long end) {
client.ltrim(key, start, end);
return client.getStatusCodeReply();
}
public String rpop(final String key) {
client.rpop(key);
return client.getBulkReply();
}
public Long rpush(final String key, final String... strings) {
client.rpush(key, strings);
return client.getIntegerReply();
}
public Long rpushx(final String key, final String string) {
client.rpushx(key, string);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sets
public Long sadd(final String key, final String... members) {
client.sadd(key, members);
return client.getIntegerReply();
}
public Long scard(final String key) {
client.scard(key);
return client.getIntegerReply();
}
public Boolean sismember(final String key, final String member) {
client.sismember(key, member);
return client.getIntegerReply() == 1;
}
public Set<String> smembers(final String key) {
client.smembers(key);
final List<String> members = client.getMultiBulkReply();
return new HashSet<String>(members);
}
public String srandmember(final String key) {
client.srandmember(key);
return client.getBulkReply();
}
public List<String> srandmember(final String key, final int count) {
client.srandmember(key, count);
return client.getMultiBulkReply();
}
public Long srem(final String key, final String... members) {
client.srem(key, members);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sorted Sets
public Long zadd(final String key, final double score, final String member) {
client.zadd(key, score, member);
return client.getIntegerReply();
}
public Long zadd(final String key, final Map<Double, String> scoreMembers) {
client.zadd(key, scoreMembers);
return client.getIntegerReply();
}
public Long zadd2(final String key, final Map<String, Double> scoreMembers) {
client.zadd2(key, scoreMembers);
return client.getIntegerReply();
}
public Long zcard(final String key) {
client.zcard(key);
return client.getIntegerReply();
}
public Long zcount(final String key, final double min, final double max) {
client.zcount(key, min, max);
return client.getIntegerReply();
}
public Long zcount(final String key, final String min, final String max) {
client.zcount(key, min, max);
return client.getIntegerReply();
}
public Double zincrby(final String key, final double score,
final String member) {
client.zincrby(key, score, member);
String newscore = client.getBulkReply();
return Double.valueOf(newscore);
}
public Set<String> zrange(final String key, final long start, final long end) {
client.zrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
return new LinkedHashSet<String>(members);
}
public Set<String> zrangeByScore(final String key, final double min,
final double max) {
client.zrangeByScore(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final String min,
final String max) {
client.zrangeByScore(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final double min,
final double max, final int offset, final int count) {
client.zrangeByScore(key, min, max, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final String min,
final String max, final int offset, final int count) {
client.zrangeByScore(key, min, max, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrangeWithScores(final String key, final long start,
final long end) {
client.zrangeWithScores(key, start, end);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final double min, final double max) {
client.zrangeByScoreWithScores(key, min, max);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final String min, final String max) {
client.zrangeByScoreWithScores(key, min, max);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final double min, final double max, final int offset,
final int count) {
client.zrangeByScoreWithScores(key, min, max, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final String min, final String max, final int offset,
final int count) {
client.zrangeByScoreWithScores(key, min, max, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Long zrank(final String key, final String member) {
client.zrank(key, member);
return client.getIntegerReply();
}
public Long zrem(final String key, final String... members) {
client.zrem(key, members);
return client.getIntegerReply();
}
public Long zremrangeByRank(final String key, final long start,
final long end) {
client.zremrangeByRank(key, start, end);
return client.getIntegerReply();
}
public Long zremrangeByScore(final String key, final double start,
final double end) {
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
public Long zremrangeByScore(final String key, final String start,
final String end) {
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
public Set<String> zrevrange(final String key, final long start,
final long end) {
client.zrevrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
return new LinkedHashSet<String>(members);
}
public Set<Tuple> zrevrangeWithScores(final String key, final long start,
final long end) {
client.zrevrangeWithScores(key, start, end);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<String> zrevrangeByScore(final String key, final double max,
final double min) {
client.zrevrangeByScore(key, max, min);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrevrangeByScore(final String key, final String max,
final String min) {
client.zrevrangeByScore(key, max, min);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrevrangeByScore(final String key, final double max,
final double min, final int offset, final int count) {
client.zrevrangeByScore(key, max, min, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final double max, final double min) {
client.zrevrangeByScoreWithScores(key, max, min);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final double max, final double min, final int offset,
final int count) {
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final String max, final String min, final int offset,
final int count) {
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<String> zrevrangeByScore(final String key, final String max,
final String min, final int offset, final int count) {
client.zrevrangeByScore(key, max, min, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final String max, final String min) {
client.zrevrangeByScoreWithScores(key, max, min);
Set<Tuple> set = getTupledSet();
return set;
}
public Long zrevrank(final String key, final String member) {
client.zrevrank(key, member);
return client.getIntegerReply();
}
public Double zscore(final String key, final String member) {
client.zscore(key, member);
final String score = client.getBulkReply();
return (score != null ? new Double(score) : null);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Connection
public String ping() {
client.ping();
return client.getStatusCodeReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Server
public String info() {
client.info();
return client.getBulkReply();
}
public String info(final String section) {
client.info(section);
return client.getBulkReply();
}
public Long dbSize() {
client.dbSize();
return client.getIntegerReply();
}
public byte[] dump(final String key) {
client.dump(key);
return client.getBinaryBulkReply();
}
public String restore(final String key, final long ttl,
final byte[] serializedValue) {
client.restore(key, ttl, serializedValue);
return client.getStatusCodeReply();
}
/**
* Quit.
*
* @return the string
*/
public String quit() {
client.quit();
return client.getStatusCodeReply();
}
/**
* Connect.
*/
public void connect() {
client.connect();
}
/**
* Disconnect.
*/
public void disconnect() {
client.disconnect();
}
/**
* Checks if is connected.
*
* @return true, if is connected
*/
public boolean isConnected() {
return client.isConnected();
}
/**
* Gets the tupled set.
*
* @return the tupled set
*/
private Set<Tuple> getTupledSet() {
List<String> membersWithScores = client.getMultiBulkReply();
Set<Tuple> set = new LinkedHashSet<Tuple>();
Iterator<String> iterator = membersWithScores.iterator();
while (iterator.hasNext()) {
set.add(new Tuple(iterator.next(), Double.valueOf(iterator.next())));
}
return set;
}
} | cl9200/nbase-arc | api/java/src/main/java/com/navercorp/redis/cluster/RedisCluster.java | Java | apache-2.0 | 23,864 |
/*
* 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.chime.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.chime.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetMediaCapturePipelineRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetMediaCapturePipelineRequestProtocolMarshaller implements Marshaller<Request<GetMediaCapturePipelineRequest>, GetMediaCapturePipelineRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/media-capture-pipelines/{mediaPipelineId}").httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false)
.hasPayloadMembers(false).serviceName("AmazonChime").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public GetMediaCapturePipelineRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<GetMediaCapturePipelineRequest> marshall(GetMediaCapturePipelineRequest getMediaCapturePipelineRequest) {
if (getMediaCapturePipelineRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<GetMediaCapturePipelineRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, getMediaCapturePipelineRequest);
protocolMarshaller.startMarshalling();
GetMediaCapturePipelineRequestMarshaller.getInstance().marshall(getMediaCapturePipelineRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-chime/src/main/java/com/amazonaws/services/chime/model/transform/GetMediaCapturePipelineRequestProtocolMarshaller.java | Java | apache-2.0 | 2,781 |
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Xabber project; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, Version 3.
*
* Xabber is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.itracker.android.data.roster;
import android.text.TextUtils;
import com.itracker.android.data.account.StatusMode;
import org.jivesoftware.smack.roster.RosterEntry;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Contact in roster.
* <p/>
* {@link #getUser()} always will be bare jid.
*
* @author alexander.ivanov
*/
public class RosterContact extends AbstractContact {
/**
* Contact's name.
*/
protected String name;
/**
* Used groups with its names.
*/
protected final Map<String, RosterGroupReference> groupReferences;
/**
* Whether there is subscription of type "both" or "to".
*/
protected boolean subscribed;
/**
* Whether contact`s account is connected.
*/
protected boolean connected;
/**
* Whether contact`s account is enabled.
*/
protected boolean enabled;
/**
* Data id to view contact information from system contact list.
* <p/>
* Warning: not implemented yet.
*/
private Long viewId;
public RosterContact(String account, RosterEntry rosterEntry) {
this(account, rosterEntry.getUser(), rosterEntry.getName());
}
public RosterContact(String account, String user, String name) {
super(account, user);
if (name == null) {
this.name = null;
} else {
this.name = name.trim();
}
groupReferences = new HashMap<>();
subscribed = true;
connected = true;
enabled = true;
viewId = null;
}
void setName(String name) {
this.name = name;
}
@Override
public Collection<RosterGroupReference> getGroups() {
return Collections.unmodifiableCollection(groupReferences.values());
}
Collection<String> getGroupNames() {
return Collections.unmodifiableCollection(groupReferences.keySet());
}
void addGroupReference(RosterGroupReference groupReference) {
groupReferences.put(groupReference.getName(), groupReference);
}
void setSubscribed(boolean subscribed) {
this.subscribed = subscribed;
}
@Override
public StatusMode getStatusMode() {
return PresenceManager.getInstance().getStatusMode(account, user);
}
@Override
public String getName() {
if (TextUtils.isEmpty(name)) {
return super.getName();
} else {
return name;
}
}
@Override
public boolean isConnected() {
return connected;
}
void setConnected(boolean connected) {
this.connected = connected;
}
public boolean isEnabled() {
return enabled;
}
void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Long getViewId() {
return viewId;
}
}
| bigbugbb/iTracker | app/src/main/java/com/itracker/android/data/roster/RosterContact.java | Java | apache-2.0 | 3,496 |
/*
* Copyright 2011-2015 The Trustees of the University of Pennsylvania
*
* 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 edu.upenn.library.xmlaminar.parallel;
import static edu.upenn.library.xmlaminar.parallel.JoiningXMLFilter.GROUP_BY_SYSTEMID_FEATURE_NAME;
import edu.upenn.library.xmlaminar.parallel.callback.OutputCallback;
import edu.upenn.library.xmlaminar.parallel.callback.StdoutCallback;
import edu.upenn.library.xmlaminar.parallel.callback.XMLReaderCallback;
import edu.upenn.library.xmlaminar.VolatileSAXSource;
import edu.upenn.library.xmlaminar.VolatileXMLFilterImpl;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import javax.xml.transform.sax.SAXSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.XMLFilterImpl;
/**
*
* @author Michael Gibney
*/
public class SplittingXMLFilter extends QueueSourceXMLFilter implements OutputCallback {
private static final Logger LOG = LoggerFactory.getLogger(SplittingXMLFilter.class);
private final AtomicBoolean parsing = new AtomicBoolean(false);
private volatile Future<?> consumerTask;
private int level = -1;
private int startEventLevel = -1;
private final ArrayDeque<StructuralStartEvent> startEventStack = new ArrayDeque<StructuralStartEvent>();
public static void main(String[] args) throws Exception {
LevelSplittingXMLFilter sxf = new LevelSplittingXMLFilter();
sxf.setChunkSize(1);
sxf.setOutputCallback(new StdoutCallback());
sxf.setInputType(InputType.indirect);
sxf.parse(new InputSource("../cli/whole-indirect.txt"));
}
public void ensureCleanInitialState() {
if (level != -1) {
throw new IllegalStateException("level != -1: "+level);
}
if (startEventLevel != -1) {
throw new IllegalStateException("startEventLevel != -1: "+startEventLevel);
}
if (!startEventStack.isEmpty()) {
throw new IllegalStateException("startEventStack not empty: "+startEventStack.size());
}
if (parsing.get()) {
throw new IllegalStateException("already parsing");
}
if (consumerTask != null) {
throw new IllegalStateException("consumerTask not null");
}
if (producerThrowable != null || consumerThrowable != null) {
throw new IllegalStateException("throwable not null: "+producerThrowable+", "+consumerThrowable);
}
int arrived;
if ((arrived = parseBeginPhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseBeginPhaser arrived count: "+arrived);
}
if ((arrived = parseEndPhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseEndPhaser arrived count: "+arrived);
}
if ((arrived = parseChunkDonePhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseChunkDonePhaser arrived count: "+arrived);
}
}
@Override
protected void initialParse(VolatileSAXSource in) {
synchronousParser.setParent(this);
setupParse(in.getInputSource());
}
@Override
protected void repeatParse(VolatileSAXSource in) {
reset(false);
setupParse(in.getInputSource());
}
private void setupParse(InputSource in) {
setContentHandler(synchronousParser);
if (!parsing.compareAndSet(false, true)) {
throw new IllegalStateException("failed setting parsing = true");
}
OutputLooper outputLoop = new OutputLooper(in, null, Thread.currentThread());
consumerTask = getExecutor().submit(outputLoop);
}
@Override
protected void finished() throws SAXException {
reset(false);
}
public void reset() {
try {
setFeature(RESET_PROPERTY_NAME, true);
} catch (SAXException ex) {
throw new AssertionError(ex);
}
}
protected void reset(boolean cancel) {
try {
if (consumerTask != null) {
if (cancel) {
consumerTask.cancel(true);
} else {
consumerTask.get();
}
}
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
} catch (ExecutionException ex) {
throw new RuntimeException(ex);
}
consumerTask = null;
consumerThrowable = null;
producerThrowable = null;
if (splitDirector != null) {
splitDirector.reset();
}
startEventStack.clear();
if (!parsing.compareAndSet(false, false) && !cancel) {
LOG.warn("at {}.reset(), parsing had been set to true", SplittingXMLFilter.class.getName(), new IllegalStateException());
}
}
@Override
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
if (RESET_PROPERTY_NAME.equals(name) && value) {
try {
super.setFeature(name, value);
} catch (SAXException ex) {
/*
* could run here if only want to run if deepest resettable parent.
* ... but I don't think that's the case here.
*/
}
/*
* reset(false) because the downstream consumer thread issued this
* reset request (initiated the interruption).
*/
reset(true);
} else {
super.setFeature(name, value);
}
}
@Override
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
if (RESET_PROPERTY_NAME.equals(name)) {
try {
return super.getFeature(name) && consumerTask == null;
} catch (SAXException ex) {
return consumerTask == null;
}
} else if (GROUP_BY_SYSTEMID_FEATURE_NAME.equals(name)) {
return false;
}else {
return super.getFeature(name);
}
}
private final SynchronousParser synchronousParser = new SynchronousParser();
@Override
public boolean allowOutputCallback() {
return true;
}
private class SynchronousParser extends VolatileXMLFilterImpl {
@Override
public void parse(InputSource input) throws SAXException, IOException {
parse();
}
@Override
public void parse(String systemId) throws SAXException, IOException {
parse();
}
private void parse() throws SAXException, IOException {
parseBeginPhaser.arrive();
try {
parseEndPhaser.awaitAdvanceInterruptibly(parseEndPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
parseChunkDonePhaser.arrive();
}
}
private final Phaser parseBeginPhaser = new Phaser(2);
private final Phaser parseEndPhaser = new Phaser(2);
private final Phaser parseChunkDonePhaser = new Phaser(2);
private class OutputLooper implements Runnable {
private final InputSource input;
private final String systemId;
private final Thread producer;
private OutputLooper(InputSource in, String systemId, Thread producer) {
this.input = in;
this.systemId = systemId;
this.producer = producer;
}
private void parseLoop(InputSource input, String systemId) throws SAXException, IOException {
if (input != null) {
while (parsing.get()) {
outputCallback.callback(new VolatileSAXSource(synchronousParser, input));
try {
parseChunkDonePhaser.awaitAdvanceInterruptibly(parseChunkDonePhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
} else {
throw new NullPointerException("null InputSource");
}
}
@Override
public void run() {
try {
parseLoop(input, systemId);
} catch (Throwable t) {
if (producerThrowable == null) {
consumerThrowable = t;
producer.interrupt();
} else {
t = producerThrowable;
producerThrowable = null;
throw new RuntimeException(t);
}
}
}
}
@Override
public void parse(InputSource input) throws SAXException, IOException {
parse(input, null);
}
@Override
public void parse(String systemId) throws SAXException, IOException {
parse(null, systemId);
}
private void parse(InputSource input, String systemId) {
try {
if (input != null) {
super.parse(input);
} else {
super.parse(systemId);
}
} catch (Throwable t) {
try {
if (consumerThrowable == null) {
producerThrowable = t;
reset(true);
} else {
t = consumerThrowable;
consumerThrowable = null;
}
} finally {
if (outputCallback != null) {
outputCallback.finished(t);
}
throw new RuntimeException(t);
}
}
outputCallback.finished(null);
}
@Override
public XMLReaderCallback getOutputCallback() {
return outputCallback;
}
@Override
public void setOutputCallback(XMLReaderCallback xmlReaderCallback) {
this.outputCallback = xmlReaderCallback;
}
private volatile XMLReaderCallback outputCallback;
private volatile Throwable consumerThrowable;
private volatile Throwable producerThrowable;
@Override
public void startDocument() throws SAXException {
try {
parseBeginPhaser.awaitAdvanceInterruptibly(parseBeginPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
startEventStack.push(new StructuralStartEvent());
super.startDocument();
level++;
startEventLevel++;
}
@Override
public void endDocument() throws SAXException {
startEventLevel--;
level--;
super.endDocument();
startEventStack.pop();
if (!parsing.compareAndSet(true, false)) {
throw new IllegalStateException("failed at endDocument setting parsing = false");
}
parseEndPhaser.arrive();
}
private int bypassLevel = Integer.MAX_VALUE;
private int bypassStartEventLevel = Integer.MAX_VALUE;
protected final void split() throws SAXException {
writeSyntheticEndEvents();
parseEndPhaser.arrive();
try {
parseBeginPhaser.awaitAdvanceInterruptibly(parseBeginPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
writeSyntheticStartEvents();
}
private void writeSyntheticEndEvents() throws SAXException {
Iterator<StructuralStartEvent> iter = startEventStack.iterator();
while (iter.hasNext()) {
StructuralStartEvent next = iter.next();
switch (next.type) {
case DOCUMENT:
super.endDocument();
break;
case PREFIX_MAPPING:
super.endPrefixMapping(next.one);
break;
case ELEMENT:
super.endElement(next.one, next.two, next.three);
}
}
}
private void writeSyntheticStartEvents() throws SAXException {
Iterator<StructuralStartEvent> iter = startEventStack.descendingIterator();
while (iter.hasNext()) {
StructuralStartEvent next = iter.next();
switch (next.type) {
case DOCUMENT:
super.startDocument();
break;
case PREFIX_MAPPING:
super.startPrefixMapping(next.one, next.two);
break;
case ELEMENT:
super.startElement(next.one, next.two, next.three, next.atts);
}
}
}
private SplitDirector splitDirector = new SplitDirector();
public SplitDirector getSplitDirector() {
return splitDirector;
}
public void setSplitDirector(SplitDirector splitDirector) {
this.splitDirector = splitDirector;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (level < bypassLevel && handleDirective(splitDirector.startElement(uri, localName, qName, atts, level))) {
startEventStack.push(new StructuralStartEvent(uri, localName, qName, atts));
}
super.startElement(uri, localName, qName, atts);
level++;
startEventLevel++;
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
if (level < bypassLevel && handleDirective(splitDirector.startPrefixMapping(prefix, uri, level))) {
startEventStack.push(new StructuralStartEvent(prefix, uri));
}
super.startPrefixMapping(prefix, uri);
startEventLevel++;
}
/**
* Returns true if the generating event should be added to
* the startEvent stack
* @param directive
* @return
* @throws SAXException
*/
private boolean handleDirective(SplitDirective directive) throws SAXException {
switch (directive) {
case SPLIT:
bypassLevel = level;
bypassStartEventLevel = startEventLevel;
split();
return false;
case SPLIT_NO_BYPASS:
split();
return true;
case NO_SPLIT_BYPASS:
bypassLevel = level;
bypassStartEventLevel = startEventLevel;
return false;
case NO_SPLIT:
return true;
default:
throw new AssertionError();
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
startEventLevel--;
level--;
super.endElement(uri, localName, qName);
if (handleStructuralEndEvent()) {
handleDirective(splitDirector.endElement(uri, localName, qName, level));
}
}
private boolean handleStructuralEndEvent() {
if (level > bypassLevel) {
return false;
} else if (level < bypassLevel) {
startEventStack.pop();
return true;
} else {
if (startEventLevel == bypassStartEventLevel) {
bypassEnd();
return true;
} else if (startEventLevel < bypassStartEventLevel) {
startEventStack.pop();
return true;
} else {
return false;
}
}
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
startEventLevel--;
super.endPrefixMapping(prefix);
if (handleStructuralEndEvent()) {
handleDirective(splitDirector.endPrefixMapping(prefix, level));
}
}
private void bypassEnd() {
bypassLevel = Integer.MAX_VALUE;
bypassStartEventLevel = Integer.MAX_VALUE;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.characters(ch, start, length, level));
}
super.characters(ch, start, length);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.ignorableWhitespace(ch, start, length, level));
}
super.ignorableWhitespace(ch, start, length);
}
@Override
public void skippedEntity(String name) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.skippedEntity(name, level));
}
super.skippedEntity(name);
}
public static enum SplitDirective { SPLIT, NO_SPLIT, SPLIT_NO_BYPASS, NO_SPLIT_BYPASS }
public static class SplitDirector {
public void reset() {
// default NOOP implementation
}
public SplitDirective startPrefixMapping(String prefix, String uri, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective endPrefixMapping(String prefix, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective startElement(String uri, String localName, String qName, Attributes atts, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective endElement(String uri, String localName, String qName, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective characters(char[] ch, int start, int length, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective ignorableWhitespace(char[] ch, int start, int length, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective skippedEntity(String name, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
}
}
| upenn-libraries/xmlaminar | parallel/src/main/java/edu/upenn/library/xmlaminar/parallel/SplittingXMLFilter.java | Java | apache-2.0 | 19,266 |
package bamboo.crawl;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class RecordStats {
private static final Date MAX_TIME = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(900));
private static final Date MIN_TIME = new Date(631152000000L);
private long records;
private long recordBytes;
private Date startTime = null;
private Date endTime = null;
public void update(long recordLength, Date time) {
records += 1;
recordBytes += recordLength;
if (time.after(MIN_TIME) && time.before(MAX_TIME)) {
if (startTime == null || time.before(startTime)) {
startTime = time;
}
if (endTime == null || time.after(endTime)) {
endTime = time;
}
}
}
public long getRecords() {
return records;
}
public long getRecordBytes() {
return recordBytes;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
@Override
public String toString() {
return "RecordStats{" +
"records=" + records +
", recordBytes=" + recordBytes +
", startTime=" + startTime +
", endTime=" + endTime +
'}';
}
}
| nla/bamboo | ui/src/bamboo/crawl/RecordStats.java | Java | apache-2.0 | 1,362 |
package com.example.nm_gql_go_link_example;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
}
| google/note-maps | flutter/nm_gql_go_link/example/android/app/src/main/java/com/example/nm_gql_go_link_example/MainActivity.java | Java | apache-2.0 | 153 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.hyracks.storage.am.lsm.invertedindex.util;
import java.util.List;
import org.apache.hyracks.api.comm.IFrameTupleAccessor;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.api.exceptions.ErrorCode;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.api.io.IIOManager;
import org.apache.hyracks.storage.am.bloomfilter.impls.BloomFilterFactory;
import org.apache.hyracks.storage.am.btree.frames.BTreeLeafFrameType;
import org.apache.hyracks.storage.am.btree.frames.BTreeNSMInteriorFrameFactory;
import org.apache.hyracks.storage.am.btree.tuples.BTreeTypeAwareTupleWriterFactory;
import org.apache.hyracks.storage.am.btree.util.BTreeUtils;
import org.apache.hyracks.storage.am.common.api.IMetadataPageManagerFactory;
import org.apache.hyracks.storage.am.common.api.IPageManager;
import org.apache.hyracks.storage.am.common.api.IPageManagerFactory;
import org.apache.hyracks.storage.am.common.api.ITreeIndexFrameFactory;
import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleWriterFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponentFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationScheduler;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicy;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTracker;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMPageWriteCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.IVirtualBufferCache;
import org.apache.hyracks.storage.am.lsm.common.frames.LSMComponentFilterFrameFactory;
import org.apache.hyracks.storage.am.lsm.common.impls.BTreeFactory;
import org.apache.hyracks.storage.am.lsm.common.impls.ComponentFilterHelper;
import org.apache.hyracks.storage.am.lsm.common.impls.LSMComponentFilterManager;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListBuilder;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListBuilderFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.fulltext.IFullTextConfigEvaluatorFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndexDiskComponentFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndexFileManager;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.PartitionedLSMInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.inmemory.InMemoryInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.inmemory.PartitionedInMemoryInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.InvertedListBuilderFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.OnDiskInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.OnDiskInvertedIndexFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.PartitionedOnDiskInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.PartitionedOnDiskInvertedIndexFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeElementInvertedListBuilder;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeInvertedListSearchResultFrameTupleAccessor;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.variablesize.VariableSizeInvertedListSearchResultFrameTupleAccessor;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.variablesize.VariableSizeInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizerFactory;
import org.apache.hyracks.storage.common.buffercache.IBufferCache;
import org.apache.hyracks.util.trace.ITracer;
public class InvertedIndexUtils {
public static final String EXPECT_ALL_FIX_GET_VAR_SIZE =
"expecting all type traits to be fixed-size while getting at least one variable-length one";
public static final String EXPECT_VAR_GET_ALL_FIX_SIZE =
"expecting at least one variable-size type trait while all are fixed-size";
public static InMemoryInvertedIndex createInMemoryBTreeInvertedindex(IBufferCache memBufferCache,
IPageManager virtualFreePageManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, FileReference btreeFileRef)
throws HyracksDataException {
return new InMemoryInvertedIndex(memBufferCache, virtualFreePageManager, invListTypeTraits, invListCmpFactories,
tokenTypeTraits, tokenCmpFactories, tokenizerFactory, fullTextConfigEvaluatorFactory, btreeFileRef);
}
public static InMemoryInvertedIndex createPartitionedInMemoryBTreeInvertedindex(IBufferCache memBufferCache,
IPageManager virtualFreePageManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, FileReference btreeFileRef)
throws HyracksDataException {
return new PartitionedInMemoryInvertedIndex(memBufferCache, virtualFreePageManager, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, btreeFileRef);
}
public static OnDiskInvertedIndex createOnDiskInvertedIndex(IIOManager ioManager, IBufferCache bufferCache,
ITypeTraits[] invListTypeTraits, IBinaryComparatorFactory[] invListCmpFactories,
ITypeTraits[] tokenTypeTraits, IBinaryComparatorFactory[] tokenCmpFactories, FileReference invListsFile,
IPageManagerFactory pageManagerFactory) throws HyracksDataException {
IInvertedListBuilder builder = new FixedSizeElementInvertedListBuilder(invListTypeTraits);
FileReference btreeFile = getBTreeFile(ioManager, invListsFile);
return new OnDiskInvertedIndex(bufferCache, builder, invListTypeTraits, invListCmpFactories, tokenTypeTraits,
tokenCmpFactories, btreeFile, invListsFile, pageManagerFactory);
}
public static PartitionedOnDiskInvertedIndex createPartitionedOnDiskInvertedIndex(IIOManager ioManager,
IBufferCache bufferCache, ITypeTraits[] invListTypeTraits, IBinaryComparatorFactory[] invListCmpFactories,
ITypeTraits[] tokenTypeTraits, IBinaryComparatorFactory[] tokenCmpFactories, FileReference invListsFile,
IPageManagerFactory pageManagerFactory) throws HyracksDataException {
IInvertedListBuilder builder = new FixedSizeElementInvertedListBuilder(invListTypeTraits);
FileReference btreeFile = getBTreeFile(ioManager, invListsFile);
return new PartitionedOnDiskInvertedIndex(bufferCache, builder, invListTypeTraits, invListCmpFactories,
tokenTypeTraits, tokenCmpFactories, btreeFile, invListsFile, pageManagerFactory);
}
public static FileReference getBTreeFile(IIOManager ioManager, FileReference invListsFile)
throws HyracksDataException {
return ioManager.resolveAbsolutePath(invListsFile.getFile().getPath() + "_btree");
}
public static BTreeFactory createDeletedKeysBTreeFactory(IIOManager ioManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, IBufferCache diskBufferCache,
IPageManagerFactory freePageManagerFactory) throws HyracksDataException {
BTreeTypeAwareTupleWriterFactory tupleWriterFactory =
new BTreeTypeAwareTupleWriterFactory(invListTypeTraits, false);
ITreeIndexFrameFactory leafFrameFactory =
BTreeUtils.getLeafFrameFactory(tupleWriterFactory, BTreeLeafFrameType.REGULAR_NSM);
ITreeIndexFrameFactory interiorFrameFactory = new BTreeNSMInteriorFrameFactory(tupleWriterFactory);
return new BTreeFactory(ioManager, diskBufferCache, freePageManagerFactory, interiorFrameFactory,
leafFrameFactory, invListCmpFactories, invListCmpFactories.length);
}
public static LSMInvertedIndex createLSMInvertedIndex(IIOManager ioManager,
List<IVirtualBufferCache> virtualBufferCaches, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, IBufferCache diskBufferCache,
String absoluteOnDiskDir, double bloomFilterFalsePositiveRate, ILSMMergePolicy mergePolicy,
ILSMOperationTracker opTracker, ILSMIOOperationScheduler ioScheduler,
ILSMIOOperationCallbackFactory ioOpCallbackFactory, ILSMPageWriteCallbackFactory pageWriteCallbackFactory,
int[] invertedIndexFields, ITypeTraits[] filterTypeTraits, IBinaryComparatorFactory[] filterCmpFactories,
int[] filterFields, int[] filterFieldsForNonBulkLoadOps, int[] invertedIndexFieldsForNonBulkLoadOps,
boolean durable, IMetadataPageManagerFactory pageManagerFactory, ITracer tracer)
throws HyracksDataException {
BTreeFactory deletedKeysBTreeFactory = createDeletedKeysBTreeFactory(ioManager, invListTypeTraits,
invListCmpFactories, diskBufferCache, pageManagerFactory);
int[] bloomFilterKeyFields = new int[invListCmpFactories.length];
for (int i = 0; i < invListCmpFactories.length; i++) {
bloomFilterKeyFields[i] = i;
}
BloomFilterFactory bloomFilterFactory = new BloomFilterFactory(diskBufferCache, bloomFilterKeyFields);
FileReference onDiskDirFileRef = ioManager.resolveAbsolutePath(absoluteOnDiskDir);
LSMInvertedIndexFileManager fileManager =
new LSMInvertedIndexFileManager(ioManager, onDiskDirFileRef, deletedKeysBTreeFactory);
IInvertedListBuilderFactory invListBuilderFactory =
new InvertedListBuilderFactory(tokenTypeTraits, invListTypeTraits);
OnDiskInvertedIndexFactory invIndexFactory =
new OnDiskInvertedIndexFactory(ioManager, diskBufferCache, invListBuilderFactory, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, fileManager, pageManagerFactory);
ComponentFilterHelper filterHelper = null;
LSMComponentFilterFrameFactory filterFrameFactory = null;
LSMComponentFilterManager filterManager = null;
if (filterCmpFactories != null) {
TypeAwareTupleWriterFactory filterTupleWriterFactory = new TypeAwareTupleWriterFactory(filterTypeTraits);
filterHelper = new ComponentFilterHelper(filterTupleWriterFactory, filterCmpFactories);
filterFrameFactory = new LSMComponentFilterFrameFactory(filterTupleWriterFactory);
filterManager = new LSMComponentFilterManager(filterFrameFactory);
}
ILSMDiskComponentFactory componentFactory = new LSMInvertedIndexDiskComponentFactory(invIndexFactory,
deletedKeysBTreeFactory, bloomFilterFactory, filterHelper);
return new LSMInvertedIndex(ioManager, virtualBufferCaches, componentFactory, filterHelper, filterFrameFactory,
filterManager, bloomFilterFalsePositiveRate, diskBufferCache, fileManager, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, mergePolicy, opTracker, ioScheduler, ioOpCallbackFactory,
pageWriteCallbackFactory, invertedIndexFields, filterFields, filterFieldsForNonBulkLoadOps,
invertedIndexFieldsForNonBulkLoadOps, durable, tracer);
}
public static PartitionedLSMInvertedIndex createPartitionedLSMInvertedIndex(IIOManager ioManager,
List<IVirtualBufferCache> virtualBufferCaches, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, IBufferCache diskBufferCache,
String absoluteOnDiskDir, double bloomFilterFalsePositiveRate, ILSMMergePolicy mergePolicy,
ILSMOperationTracker opTracker, ILSMIOOperationScheduler ioScheduler,
ILSMIOOperationCallbackFactory ioOpCallbackFactory, ILSMPageWriteCallbackFactory pageWriteCallbackFactory,
int[] invertedIndexFields, ITypeTraits[] filterTypeTraits, IBinaryComparatorFactory[] filterCmpFactories,
int[] filterFields, int[] filterFieldsForNonBulkLoadOps, int[] invertedIndexFieldsForNonBulkLoadOps,
boolean durable, IPageManagerFactory pageManagerFactory, ITracer tracer) throws HyracksDataException {
BTreeFactory deletedKeysBTreeFactory = createDeletedKeysBTreeFactory(ioManager, invListTypeTraits,
invListCmpFactories, diskBufferCache, pageManagerFactory);
int[] bloomFilterKeyFields = new int[invListCmpFactories.length];
for (int i = 0; i < invListCmpFactories.length; i++) {
bloomFilterKeyFields[i] = i;
}
BloomFilterFactory bloomFilterFactory = new BloomFilterFactory(diskBufferCache, bloomFilterKeyFields);
FileReference onDiskDirFileRef = ioManager.resolveAbsolutePath(absoluteOnDiskDir);
LSMInvertedIndexFileManager fileManager =
new LSMInvertedIndexFileManager(ioManager, onDiskDirFileRef, deletedKeysBTreeFactory);
IInvertedListBuilderFactory invListBuilderFactory =
new InvertedListBuilderFactory(tokenTypeTraits, invListTypeTraits);
PartitionedOnDiskInvertedIndexFactory invIndexFactory = new PartitionedOnDiskInvertedIndexFactory(ioManager,
diskBufferCache, invListBuilderFactory, invListTypeTraits, invListCmpFactories, tokenTypeTraits,
tokenCmpFactories, fileManager, pageManagerFactory);
ComponentFilterHelper filterHelper = null;
LSMComponentFilterFrameFactory filterFrameFactory = null;
LSMComponentFilterManager filterManager = null;
if (filterCmpFactories != null) {
TypeAwareTupleWriterFactory filterTupleWriterFactory = new TypeAwareTupleWriterFactory(filterTypeTraits);
filterHelper = new ComponentFilterHelper(filterTupleWriterFactory, filterCmpFactories);
filterFrameFactory = new LSMComponentFilterFrameFactory(filterTupleWriterFactory);
filterManager = new LSMComponentFilterManager(filterFrameFactory);
}
ILSMDiskComponentFactory componentFactory = new LSMInvertedIndexDiskComponentFactory(invIndexFactory,
deletedKeysBTreeFactory, bloomFilterFactory, filterHelper);
return new PartitionedLSMInvertedIndex(ioManager, virtualBufferCaches, componentFactory, filterHelper,
filterFrameFactory, filterManager, bloomFilterFalsePositiveRate, diskBufferCache, fileManager,
invListTypeTraits, invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, mergePolicy, opTracker, ioScheduler, ioOpCallbackFactory,
pageWriteCallbackFactory, invertedIndexFields, filterFields, filterFieldsForNonBulkLoadOps,
invertedIndexFieldsForNonBulkLoadOps, durable, tracer);
}
public static boolean checkTypeTraitsAllFixed(ITypeTraits[] typeTraits) {
for (int i = 0; i < typeTraits.length; i++) {
if (!typeTraits[i].isFixedLength()) {
return false;
}
}
return true;
}
public static void verifyAllFixedSizeTypeTrait(ITypeTraits[] typeTraits) throws HyracksDataException {
if (InvertedIndexUtils.checkTypeTraitsAllFixed(typeTraits) == false) {
throw HyracksDataException.create(ErrorCode.INVALID_INVERTED_LIST_TYPE_TRAITS,
InvertedIndexUtils.EXPECT_ALL_FIX_GET_VAR_SIZE);
}
}
public static void verifyHasVarSizeTypeTrait(ITypeTraits[] typeTraits) throws HyracksDataException {
if (InvertedIndexUtils.checkTypeTraitsAllFixed(typeTraits) == true) {
throw HyracksDataException.create(ErrorCode.INVALID_INVERTED_LIST_TYPE_TRAITS,
InvertedIndexUtils.EXPECT_VAR_GET_ALL_FIX_SIZE);
}
}
public static IInvertedListTupleReference createInvertedListTupleReference(ITypeTraits[] typeTraits)
throws HyracksDataException {
if (checkTypeTraitsAllFixed(typeTraits)) {
return new FixedSizeInvertedListTupleReference(typeTraits);
} else {
return new VariableSizeInvertedListTupleReference(typeTraits);
}
}
public static IFrameTupleAccessor createInvertedListFrameTupleAccessor(int frameSize, ITypeTraits[] typeTraits)
throws HyracksDataException {
if (checkTypeTraitsAllFixed(typeTraits)) {
return new FixedSizeInvertedListSearchResultFrameTupleAccessor(frameSize, typeTraits);
} else {
return new VariableSizeInvertedListSearchResultFrameTupleAccessor(frameSize, typeTraits);
}
}
public static void setInvertedListFrameEndOffset(byte[] bytes, int pos) {
int off = bytes.length - 4;
bytes[off++] = (byte) (pos >> 24);
bytes[off++] = (byte) (pos >> 16);
bytes[off++] = (byte) (pos >> 8);
bytes[off] = (byte) (pos);
}
public static int getInvertedListFrameEndOffset(byte[] bytes) {
int p = bytes.length - 4;
int offsetFrameEnd = 0;
for (int i = 0; i < 4; i++) {
offsetFrameEnd = (offsetFrameEnd << 8) + (bytes[p++] & 0xFF);
}
return offsetFrameEnd;
}
}
| apache/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-storage-am-lsm-invertedindex/src/main/java/org/apache/hyracks/storage/am/lsm/invertedindex/util/InvertedIndexUtils.java | Java | apache-2.0 | 19,511 |
package info.bati11.wearprofile;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
public class AboutActivity extends Activity {
public static Intent createIntent(Context context) {
Intent intent = new Intent(context, AboutActivity.class);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
| bati11/wear-profile | mobile/src/main/java/info/bati11/wearprofile/AboutActivity.java | Java | apache-2.0 | 964 |
package com.coekie.gentyref.factory;
@SuppressWarnings("rawtypes")
public class RawOuter extends GenericOuter {}
| coekie/gentyref | src/test/java/com/coekie/gentyref/factory/RawOuter.java | Java | apache-2.0 | 114 |
/*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.support;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.propertyeditors.ClassEditor;
/**
* Convenient superclass for aspects/persistence API
* configuration classes that should be able to autowire
* objects into a factory.
* <p>
* There are two ways of doing this: by mapping managed classes to prototype bean definitions
* in the factory; and by identifying classes of which instances should be autowired into the factory
* using the autowiring capables of AutowireCapableBeanFactory. If your managed class implements
* Spring lifecycle interfaces such as BeanFactoryAware or ApplicationContextAware, you must use the
* former method. With the latter method, only properties will be set, based on automatic satisfaction
* of dependencies from other beans (singleton or non-singleton) defined in the factory.
*
* <p>Could also use attributes on persistent classes to identify those eligible for autowiring, or
* even the prototype bean name.
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory
*
* @since 1.2
* @author Rod Johnson
*/
public abstract class DependencyInjectionAspectSupport implements InitializingBean, BeanFactoryAware {
protected final Log log = LogFactory.getLog(getClass());
private BeanFactory beanFactory;
private AutowireCapableBeanFactory aabf;
/**
* Map of Class to prototype name
*/
private Map managedClassToPrototypeMap = new HashMap();
private int defaultAutowireMode = 0;
/**
* List of Class
*/
protected List autowireByTypeClasses = new LinkedList();
/**
* List of Class
*/
private List autowireByNameClasses = new LinkedList();
/**
* @return Returns the autowireAll.
*/
public int getDefaultAutowireMode() {
return defaultAutowireMode;
}
/**
* Convenient property enabling autowiring of all instances. We might want this in an
* AspectJ aspect subclass, for example, relying on the AspectJ aspect to target the
* advice.
* @param autowireAll The autowireAll to set.
*/
public void setDefaultAutowireMode(int mode) {
if (mode != 0 && mode != AutowireCapableBeanFactory.AUTOWIRE_BY_NAME && mode != AbstractAutowireCapableBeanFactory.AUTOWIRE_BY_TYPE) {
throw new IllegalArgumentException("defaultAutowireMode must be a constant on AutowireCapableBeanFactory: AUTOWIRE_BY_TYPE or AUTOWIRE_BY_NAME");
}
defaultAutowireMode = mode;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
if (beanFactory instanceof AutowireCapableBeanFactory) {
this.aabf = (AutowireCapableBeanFactory) beanFactory;
}
}
/**
* Expose the owning bean factory to subclasses.
* Call only after initialization is complete.
* @return the owning bean factory. Cannot be null in valid use of this class.
*/
protected BeanFactory getBeanFactory() {
return this.beanFactory;
}
/**
* Set the Classes or class names that will be autowired by type
* @param autowireByTypeClasses list of Class or String classname
*/
public void setAutowireByTypeClasses(List autowireByTypeClasses) {
this.autowireByTypeClasses = convertListFromStringsToClassesIfNecessary(autowireByTypeClasses);
}
/**
* Return classes autowired by type
* @return list of Class
*/
public List getAutowireByTypeClasses() {
return autowireByTypeClasses;
}
public void addAutowireByTypeClass(Class clazz) {
this.autowireByTypeClasses.add(clazz);
}
/**
* Set the Classes or class names that will be autowired by name
* @param autowireByNameClasses list of Class or String classname
*/
public void setAutowireByNameClasses(List autowireByNameClasses) {
this.autowireByNameClasses = convertListFromStringsToClassesIfNecessary(autowireByNameClasses);
}
/**
* Return classes autowired by name
* @return list of Class
*/
public List getAutowireByNameClasses() {
return autowireByNameClasses;
}
public void addAutowireByNameClass(Class clazz) {
this.autowireByNameClasses.add(clazz);
}
/**
* Property key is class FQN, value is prototype name to use to obtain a new instance
* @param persistentClassBeanNames
*/
public void setManagedClassNamesToPrototypeNames(Properties persistentClassBeanNames) {
for (Iterator i = persistentClassBeanNames.keySet().iterator(); i.hasNext();) {
String className = (String) i.next();
String beanName = persistentClassBeanNames.getProperty(className);
addManagedClassToPrototypeMapping(classNameStringToClass(className), beanName);
}
}
/**
* Utility method to convert a collection from a list of String class name to a list of Classes
* @param l list which may contain Class or String
* @return list of resolved Class instances
*/
private List convertListFromStringsToClassesIfNecessary(List l) {
List classes = new ArrayList(l.size());
for (Iterator itr = l.iterator(); itr.hasNext();) {
Object next = itr.next();
if (next instanceof String) {
next = classNameStringToClass((String) next);
}
classes.add(next);
}
return classes;
}
/**
* Resolve this FQN
* @param className name of the class to resolve
* @return the Class
*/
private Class classNameStringToClass(String className) {
ClassEditor ce = new ClassEditor();
ce.setAsText(className);
return (Class) ce.getValue();
}
/**
* Return a Map of managed classes to prototype names
* @return Map with key being FQN and value prototype bean name to use for that class
*/
public Map getManagedClassToPrototypeNames() {
return this.managedClassToPrototypeMap;
}
public void addManagedClassToPrototypeMapping(Class clazz, String beanName) {
this.managedClassToPrototypeMap.put(clazz, beanName);
}
/**
* Check that mandatory properties were set
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/
public final void afterPropertiesSet() {
if (beanFactory == null) {
throw new IllegalArgumentException("beanFactory is required");
}
validateConfiguration();
validateProperties();
}
/**
* Subclasses should implement this to validate their configuration
*/
protected abstract void validateProperties();
protected void validateConfiguration() {
if (managedClassToPrototypeMap.isEmpty() && autowireByTypeClasses.isEmpty() && autowireByNameClasses.isEmpty() && defaultAutowireMode == 0) {
throw new IllegalArgumentException("Must set persistent class information: no managed classes configured and no autowiring configuration or defaults");
}
if ((defaultAutowireMode != 0 || !autowireByTypeClasses.isEmpty() || !autowireByNameClasses.isEmpty()) && aabf == null) {
throw new IllegalArgumentException("Autowiring supported only when running in an AutowireCapableBeanFactory");
}
// Check that all persistent classes map to prototype definitions
for (Iterator itr = managedClassToPrototypeMap.keySet().iterator(); itr.hasNext(); ) {
String beanName = (String) managedClassToPrototypeMap.get(itr.next());
if (!beanFactory.containsBean(beanName)) {
throw new IllegalArgumentException("No bean with name '" + beanName + "' defined in factory");
}
if (beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean name '" + beanName + "' must be a prototype, with singleton=\"false\"");
}
}
log.info("Validated " + managedClassToPrototypeMap.size() + " persistent class to prototype mappings");
}
/**
* Subclasses can call this to autowire properties on an existing object
* @param o
* @param autowireMode
* @throws BeansException
*/
protected void autowireProperties(Object o) throws NoAutowiringConfigurationForClassException, BeansException {
if (autowireByTypeClasses.contains(o.getClass())) {
aabf.autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
}
else if (autowireByNameClasses.contains(o.getClass())) {
aabf.autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
}
else if (defaultAutowireMode == AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE) {
aabf.autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
}
else if (defaultAutowireMode == AutowireCapableBeanFactory.AUTOWIRE_BY_NAME) {
aabf.autowireBeanProperties(o, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
}
else {
throw new NoAutowiringConfigurationForClassException(o.getClass());
}
log.info("Autowired properties of persistent object with class=" + o.getClass().getName());
}
/**
* Subclasses will call this to create an object of the requisite class
* @param clazz
* @return
* @throws NoAutowiringConfigurationForClassException
*/
protected Object createAndConfigure(Class clazz) throws NoAutowiringConfigurationForClassException {
Object o = null;
String name = (String) managedClassToPrototypeMap.get(clazz);
if (name != null) {
o = beanFactory.getBean(name);
}
else {
// Fall back to trying autowiring
o = BeanUtils.instantiateClass(clazz);
autowireProperties(o);
}
if (o == null) {
throw new NoAutowiringConfigurationForClassException(clazz);
}
else {
return o;
}
}
protected class NoAutowiringConfigurationForClassException extends Exception {
public NoAutowiringConfigurationForClassException(Class clazz) {
super(clazz + " cannot be autowired");
}
}
}
| cbeams-archive/spring-framework-2.5.x | sandbox/src/org/springframework/beans/factory/support/DependencyInjectionAspectSupport.java | Java | apache-2.0 | 10,662 |
/*
* Copyright Anatoly Starostin (c) 2017.
*/
package treeton.prosody.corpus;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import treeton.core.config.BasicConfiguration;
import treeton.core.util.xml.XMLParser;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class CorpusFolder {
public CorpusFolder(String guid, Corpus corpus) {
this.guid = guid;
this.corpus = corpus;
entries = new HashMap<String, CorpusEntry>();
childFolders = new HashMap<String, CorpusFolder>();
}
private Corpus corpus;
private String guid;
private String label;
private CorpusFolder parentFolder;
private Map<String,CorpusEntry> entries;
private Map<String,CorpusFolder> childFolders;
public String getGuid() {
return guid;
}
public CorpusFolder getParentFolder() {
return parentFolder;
}
void setParentFolder(CorpusFolder parentFolder) {
if( this.parentFolder != null ) {
this.parentFolder.removeChildFolder( this );
}
this.parentFolder = parentFolder;
if( parentFolder != null ) {
parentFolder.addChildFolder(this);
}
}
void addChildFolder(CorpusFolder folder) {
childFolders.put( folder.getGuid(), folder );
}
void removeChildFolder(CorpusFolder folder) {
childFolders.remove( folder.getGuid(), folder );
}
void addEntry( CorpusEntry entry ) {
entries.put( entry.getGuid(), entry );
}
void deleteEntry( CorpusEntry entry ) {
entries.remove(entry.getGuid(), entry);
}
void load( File sourceFolder, Corpus corpus ) throws CorpusException {
File f = new File( sourceFolder, guid + ".info.xml" );
Document doc;
try {
doc = XMLParser.parse(f, new File(BasicConfiguration.getResource("/schema/corpusFolderSchema.xsd").toString()));
} catch (Exception e) {
throw new CorpusException("Corrupted entry (problem with folder info): " + guid, e);
}
Element e = doc.getDocumentElement();
label = e.getAttribute("label");
Node xmlnd = e.getFirstChild();
if( xmlnd != null ) {
if (xmlnd instanceof Element) {
Element cur = (Element) xmlnd;
if ("parent".equals(cur.getTagName())) {
String parentGuid = cur.getTextContent();
CorpusFolder pFolder = corpus.getFolder(parentGuid);
if (pFolder == null) {
throw new CorpusException("Corrupted folder (wrong parent folder " + parentGuid + " ): " + guid);
}
setParentFolder( pFolder );
} else {
throw new CorpusException("Corrupted folder (xml node contains unknown elements): " + guid);
}
} else {
throw new CorpusException("Corrupted folder (xml node contains unknown elements): " + guid);
}
}
}
void save(File targetFolder) throws CorpusException {
Document doc;
try {
doc = XMLParser.createDocument("http://starling.rinet.ru/treeton", "Document");
} catch (ParserConfigurationException e) {
throw new CorpusException("problem when trying to create xml with folder info", e);
}
Element result = doc.getDocumentElement();
result.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
result.setAttribute("xsi:schemaLocation", "http://starling.rinet.ru/treeton http://starling.rinet.ru/treeton/corpusFolderSchema.xsd");
result.setAttribute( "guid", guid );
result.setAttribute("label", label);
if( parentFolder != null ) {
Element parent = doc.createElement("parent");
parent.setTextContent(parentFolder.getGuid());
result.appendChild(parent);
}
File f = new File(targetFolder, guid + ".info.xml");
try {
XMLParser.serialize(f, doc);
} catch (IOException e) {
throw new CorpusException("problem when trying to serialize xml with folder info", e);
}
}
public Collection<CorpusFolder> getChildFolders() {
return childFolders.values();
}
public Collection<CorpusEntry> getEntries() {
return entries.values();
}
public Corpus getCorpus() {
return corpus;
}
public String getLabel() {
return label;
}
void setLabel(String label) {
this.label = label;
}
public static String getGuidByFile(File file) {
String name = file.getName();
String suffix = ".info.xml";
if( name.endsWith(suffix) ) {
return name.substring(0,name.length() - suffix.length());
}
return null;
}
public static void deleteFolderFiles(File targetFolder, String guid) throws CorpusException {
File f = new File(targetFolder, guid + ".info.xml");
if( f.exists() ) {
if( !f.delete() ) {
throw new CorpusException("unable to delete xml with folder info");
}
}
}
@Override
public String toString() {
return label;
}
}
| TreetonOrg/Treeton | dev/prosody/src/treeton/prosody/corpus/CorpusFolder.java | Java | apache-2.0 | 5,453 |
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.eclipse.ceylon.compiler.java.codegen.recovery;
/**
* The normal, error-free transformation plan.
* Instance available from {@link Errors#GENERATE}.
*/
public class Generate extends TransformationPlan {
Generate() {
super(0, null, null);
}
} | ceylon/ceylon | compiler-java/src/org/eclipse/ceylon/compiler/java/codegen/recovery/Generate.java | Java | apache-2.0 | 1,204 |
package com.github.ruediste.c3java.invocationRecording;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.annotation.ElementType;
import org.junit.Before;
import org.junit.Test;
import com.google.common.reflect.TypeToken;
@SuppressWarnings("serial")
public class MethodInvocationRecorderTest {
static interface TestClass<T> {
T getT();
String getString();
ElementType getEnum();
}
MethodInvocationRecorder recorder;
@Before
public void setup() {
recorder = new MethodInvocationRecorder();
}
@Test
public void testSingle() {
recorder.getProxy(new TypeToken<TestClass<?>>() {
}).getString();
assertEquals(1, recorder.getInvocations().size());
assertEquals(new TypeToken<TestClass<?>>() {
}, recorder.getInvocations().get(0).getInstanceType());
assertEquals("getString", recorder.getInvocations().get(0).getMethod().getName());
}
@Test
public void testGeneric() {
recorder.getProxy(new TypeToken<TestClass<?>>() {
}).getT().hashCode();
assertEquals(2, recorder.getInvocations().size());
assertEquals(new TypeToken<TestClass<?>>() {
}, recorder.getInvocations().get(0).getInstanceType());
assertEquals("getT", recorder.getInvocations().get(0).getMethod().getName());
assertEquals("capture#2-of ? extends class java.lang.Object",
recorder.getInvocations().get(1).getInstanceType().toString());
assertEquals("hashCode", recorder.getInvocations().get(1).getMethod().getName());
}
@Test
public void testTerminal() {
assertTrue(recorder.isTerminal(TypeToken.of(String.class)));
assertTrue(recorder.isTerminal(TypeToken.of(ElementType.class)));
assertFalse(recorder.isTerminal(TypeToken.of(TestClass.class)));
recorder.getProxy(String.class);
assertEquals(0, recorder.getInvocations().size());
}
@Test
public void testEnum() {
recorder.getProxy(TestClass.class).getEnum();
assertEquals(1, recorder.getInvocations().size());
assertEquals("getEnum", recorder.getInvocations().get(0).getMethod().getName());
}
@Test
public void testGeneric2() {
recorder.getProxy(new TypeToken<TestClass<TestClass<?>>>() {
}).getT().getT().hashCode();
assertEquals(3, recorder.getInvocations().size());
assertEquals(new TypeToken<TestClass<TestClass<?>>>() {
}, recorder.getInvocations().get(0).getInstanceType());
assertEquals("getT", recorder.getInvocations().get(0).getMethod().getName());
assertEquals("getT", recorder.getInvocations().get(1).getMethod().getName());
assertEquals("hashCode", recorder.getInvocations().get(2).getMethod().getName());
}
}
| ruediste/c3java | src/test/java/com/github/ruediste/c3java/invocationRecording/MethodInvocationRecorderTest.java | Java | apache-2.0 | 2,917 |
/*
* 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.homegraph.v1;
/**
* Service definition for HomeGraphService (v1).
*
* <p>
*
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/actions/smarthome/create-app#request-sync" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link HomeGraphServiceRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class HomeGraphService extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.30.10 of the HomeGraph API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://homegraph.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public HomeGraphService(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
HomeGraphService(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the AgentUsers collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code HomeGraphService homegraph = new HomeGraphService(...);}
* {@code HomeGraphService.AgentUsers.List request = homegraph.agentUsers().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public AgentUsers agentUsers() {
return new AgentUsers();
}
/**
* The "agentUsers" collection of methods.
*/
public class AgentUsers {
/**
* Unlinks the given third-party user from your smart home Action. All data related to this user
* will be deleted. For more details on how users link their accounts, see [fulfillment and
* authentication](https://developers.google.com/assistant/smarthome/concepts/fulfillment-
* authentication). The third-party user's identity is passed in via the `agent_user_id` (see
* DeleteAgentUserRequest). This request must be authorized using service account credentials from
* your Actions console project.
*
* Create a request for the method "agentUsers.delete".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param agentUserId Required. Third-party user ID.
* @return the request
*/
public Delete delete(java.lang.String agentUserId) throws java.io.IOException {
Delete result = new Delete(agentUserId);
initialize(result);
return result;
}
public class Delete extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.Empty> {
private static final String REST_PATH = "v1/{+agentUserId}";
private final java.util.regex.Pattern AGENT_USER_ID_PATTERN =
java.util.regex.Pattern.compile("^agentUsers/.*$");
/**
* Unlinks the given third-party user from your smart home Action. All data related to this user
* will be deleted. For more details on how users link their accounts, see [fulfillment and
* authentication](https://developers.google.com/assistant/smarthome/concepts/fulfillment-
* authentication). The third-party user's identity is passed in via the `agent_user_id` (see
* DeleteAgentUserRequest). This request must be authorized using service account credentials from
* your Actions console project.
*
* Create a request for the method "agentUsers.delete".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link Delete#execute()} method to invoke the remote operation.
* <p> {@link
* Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param agentUserId Required. Third-party user ID.
* @since 1.13
*/
protected Delete(java.lang.String agentUserId) {
super(HomeGraphService.this, "DELETE", REST_PATH, null, com.google.api.services.homegraph.v1.model.Empty.class);
this.agentUserId = com.google.api.client.util.Preconditions.checkNotNull(agentUserId, "Required parameter agentUserId must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(AGENT_USER_ID_PATTERN.matcher(agentUserId).matches(),
"Parameter agentUserId must conform to the pattern " +
"^agentUsers/.*$");
}
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@Override
public Delete setFields(java.lang.String fields) {
return (Delete) super.setFields(fields);
}
@Override
public Delete setKey(java.lang.String key) {
return (Delete) super.setKey(key);
}
@Override
public Delete setOauthToken(java.lang.String oauthToken) {
return (Delete) super.setOauthToken(oauthToken);
}
@Override
public Delete setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Delete) super.setPrettyPrint(prettyPrint);
}
@Override
public Delete setQuotaUser(java.lang.String quotaUser) {
return (Delete) super.setQuotaUser(quotaUser);
}
@Override
public Delete setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
/** Required. Third-party user ID. */
@com.google.api.client.util.Key
private java.lang.String agentUserId;
/** Required. Third-party user ID.
*/
public java.lang.String getAgentUserId() {
return agentUserId;
}
/** Required. Third-party user ID. */
public Delete setAgentUserId(java.lang.String agentUserId) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(AGENT_USER_ID_PATTERN.matcher(agentUserId).matches(),
"Parameter agentUserId must conform to the pattern " +
"^agentUsers/.*$");
}
this.agentUserId = agentUserId;
return this;
}
/** Request ID used for debugging. */
@com.google.api.client.util.Key
private java.lang.String requestId;
/** Request ID used for debugging.
*/
public java.lang.String getRequestId() {
return requestId;
}
/** Request ID used for debugging. */
public Delete setRequestId(java.lang.String requestId) {
this.requestId = requestId;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Devices collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code HomeGraphService homegraph = new HomeGraphService(...);}
* {@code HomeGraphService.Devices.List request = homegraph.devices().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Devices devices() {
return new Devices();
}
/**
* The "devices" collection of methods.
*/
public class Devices {
/**
* Gets the current states in Home Graph for the given set of the third-party user's devices. The
* third-party user's identity is passed in via the `agent_user_id` (see QueryRequest). This request
* must be authorized using service account credentials from your Actions console project.
*
* Create a request for the method "devices.query".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link Query#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.homegraph.v1.model.QueryRequest}
* @return the request
*/
public Query query(com.google.api.services.homegraph.v1.model.QueryRequest content) throws java.io.IOException {
Query result = new Query(content);
initialize(result);
return result;
}
public class Query extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.QueryResponse> {
private static final String REST_PATH = "v1/devices:query";
/**
* Gets the current states in Home Graph for the given set of the third-party user's devices. The
* third-party user's identity is passed in via the `agent_user_id` (see QueryRequest). This
* request must be authorized using service account credentials from your Actions console project.
*
* Create a request for the method "devices.query".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link Query#execute()} method to invoke the remote operation.
* <p> {@link
* Query#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.homegraph.v1.model.QueryRequest}
* @since 1.13
*/
protected Query(com.google.api.services.homegraph.v1.model.QueryRequest content) {
super(HomeGraphService.this, "POST", REST_PATH, content, com.google.api.services.homegraph.v1.model.QueryResponse.class);
}
@Override
public Query set$Xgafv(java.lang.String $Xgafv) {
return (Query) super.set$Xgafv($Xgafv);
}
@Override
public Query setAccessToken(java.lang.String accessToken) {
return (Query) super.setAccessToken(accessToken);
}
@Override
public Query setAlt(java.lang.String alt) {
return (Query) super.setAlt(alt);
}
@Override
public Query setCallback(java.lang.String callback) {
return (Query) super.setCallback(callback);
}
@Override
public Query setFields(java.lang.String fields) {
return (Query) super.setFields(fields);
}
@Override
public Query setKey(java.lang.String key) {
return (Query) super.setKey(key);
}
@Override
public Query setOauthToken(java.lang.String oauthToken) {
return (Query) super.setOauthToken(oauthToken);
}
@Override
public Query setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Query) super.setPrettyPrint(prettyPrint);
}
@Override
public Query setQuotaUser(java.lang.String quotaUser) {
return (Query) super.setQuotaUser(quotaUser);
}
@Override
public Query setUploadType(java.lang.String uploadType) {
return (Query) super.setUploadType(uploadType);
}
@Override
public Query setUploadProtocol(java.lang.String uploadProtocol) {
return (Query) super.setUploadProtocol(uploadProtocol);
}
@Override
public Query set(String parameterName, Object value) {
return (Query) super.set(parameterName, value);
}
}
/**
* Reports device state and optionally sends device notifications. Called by your smart home Action
* when the state of a third-party device changes or you need to send a notification about the
* device. See [Implement Report State](https://developers.google.com/assistant/smarthome/develop
* /report-state) for more information. This method updates the device state according to its
* declared [traits](https://developers.google.com/assistant/smarthome/concepts/devices-traits).
* Publishing a new state value outside of these traits will result in an `INVALID_ARGUMENT` error
* response. The third-party user's identity is passed in via the `agent_user_id` (see
* ReportStateAndNotificationRequest). This request must be authorized using service account
* credentials from your Actions console project.
*
* Create a request for the method "devices.reportStateAndNotification".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link ReportStateAndNotification#execute()} method to invoke the remote
* operation.
*
* @param content the {@link com.google.api.services.homegraph.v1.model.ReportStateAndNotificationRequest}
* @return the request
*/
public ReportStateAndNotification reportStateAndNotification(com.google.api.services.homegraph.v1.model.ReportStateAndNotificationRequest content) throws java.io.IOException {
ReportStateAndNotification result = new ReportStateAndNotification(content);
initialize(result);
return result;
}
public class ReportStateAndNotification extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.ReportStateAndNotificationResponse> {
private static final String REST_PATH = "v1/devices:reportStateAndNotification";
/**
* Reports device state and optionally sends device notifications. Called by your smart home
* Action when the state of a third-party device changes or you need to send a notification about
* the device. See [Implement Report
* State](https://developers.google.com/assistant/smarthome/develop/report-state) for more
* information. This method updates the device state according to its declared
* [traits](https://developers.google.com/assistant/smarthome/concepts/devices-traits). Publishing
* a new state value outside of these traits will result in an `INVALID_ARGUMENT` error response.
* The third-party user's identity is passed in via the `agent_user_id` (see
* ReportStateAndNotificationRequest). This request must be authorized using service account
* credentials from your Actions console project.
*
* Create a request for the method "devices.reportStateAndNotification".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link ReportStateAndNotification#execute()} method to invoke the
* remote operation. <p> {@link ReportStateAndNotification#initialize(com.google.api.client.google
* apis.services.AbstractGoogleClientRequest)} must be called to initialize this instance
* immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.homegraph.v1.model.ReportStateAndNotificationRequest}
* @since 1.13
*/
protected ReportStateAndNotification(com.google.api.services.homegraph.v1.model.ReportStateAndNotificationRequest content) {
super(HomeGraphService.this, "POST", REST_PATH, content, com.google.api.services.homegraph.v1.model.ReportStateAndNotificationResponse.class);
}
@Override
public ReportStateAndNotification set$Xgafv(java.lang.String $Xgafv) {
return (ReportStateAndNotification) super.set$Xgafv($Xgafv);
}
@Override
public ReportStateAndNotification setAccessToken(java.lang.String accessToken) {
return (ReportStateAndNotification) super.setAccessToken(accessToken);
}
@Override
public ReportStateAndNotification setAlt(java.lang.String alt) {
return (ReportStateAndNotification) super.setAlt(alt);
}
@Override
public ReportStateAndNotification setCallback(java.lang.String callback) {
return (ReportStateAndNotification) super.setCallback(callback);
}
@Override
public ReportStateAndNotification setFields(java.lang.String fields) {
return (ReportStateAndNotification) super.setFields(fields);
}
@Override
public ReportStateAndNotification setKey(java.lang.String key) {
return (ReportStateAndNotification) super.setKey(key);
}
@Override
public ReportStateAndNotification setOauthToken(java.lang.String oauthToken) {
return (ReportStateAndNotification) super.setOauthToken(oauthToken);
}
@Override
public ReportStateAndNotification setPrettyPrint(java.lang.Boolean prettyPrint) {
return (ReportStateAndNotification) super.setPrettyPrint(prettyPrint);
}
@Override
public ReportStateAndNotification setQuotaUser(java.lang.String quotaUser) {
return (ReportStateAndNotification) super.setQuotaUser(quotaUser);
}
@Override
public ReportStateAndNotification setUploadType(java.lang.String uploadType) {
return (ReportStateAndNotification) super.setUploadType(uploadType);
}
@Override
public ReportStateAndNotification setUploadProtocol(java.lang.String uploadProtocol) {
return (ReportStateAndNotification) super.setUploadProtocol(uploadProtocol);
}
@Override
public ReportStateAndNotification set(String parameterName, Object value) {
return (ReportStateAndNotification) super.set(parameterName, value);
}
}
/**
* Requests Google to send an `action.devices.SYNC`
* [intent](https://developers.google.com/assistant/smarthome/reference/intent/sync) to your smart
* home Action to update device metadata for the given user. The third-party user's identity is
* passed via the `agent_user_id` (see RequestSyncDevicesRequest). This request must be authorized
* using service account credentials from your Actions console project.
*
* Create a request for the method "devices.requestSync".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link RequestSync#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest}
* @return the request
*/
public RequestSync requestSync(com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest content) throws java.io.IOException {
RequestSync result = new RequestSync(content);
initialize(result);
return result;
}
public class RequestSync extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.RequestSyncDevicesResponse> {
private static final String REST_PATH = "v1/devices:requestSync";
/**
* Requests Google to send an `action.devices.SYNC`
* [intent](https://developers.google.com/assistant/smarthome/reference/intent/sync) to your smart
* home Action to update device metadata for the given user. The third-party user's identity is
* passed via the `agent_user_id` (see RequestSyncDevicesRequest). This request must be authorized
* using service account credentials from your Actions console project.
*
* Create a request for the method "devices.requestSync".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link RequestSync#execute()} method to invoke the remote
* operation. <p> {@link
* RequestSync#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest}
* @since 1.13
*/
protected RequestSync(com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest content) {
super(HomeGraphService.this, "POST", REST_PATH, content, com.google.api.services.homegraph.v1.model.RequestSyncDevicesResponse.class);
}
@Override
public RequestSync set$Xgafv(java.lang.String $Xgafv) {
return (RequestSync) super.set$Xgafv($Xgafv);
}
@Override
public RequestSync setAccessToken(java.lang.String accessToken) {
return (RequestSync) super.setAccessToken(accessToken);
}
@Override
public RequestSync setAlt(java.lang.String alt) {
return (RequestSync) super.setAlt(alt);
}
@Override
public RequestSync setCallback(java.lang.String callback) {
return (RequestSync) super.setCallback(callback);
}
@Override
public RequestSync setFields(java.lang.String fields) {
return (RequestSync) super.setFields(fields);
}
@Override
public RequestSync setKey(java.lang.String key) {
return (RequestSync) super.setKey(key);
}
@Override
public RequestSync setOauthToken(java.lang.String oauthToken) {
return (RequestSync) super.setOauthToken(oauthToken);
}
@Override
public RequestSync setPrettyPrint(java.lang.Boolean prettyPrint) {
return (RequestSync) super.setPrettyPrint(prettyPrint);
}
@Override
public RequestSync setQuotaUser(java.lang.String quotaUser) {
return (RequestSync) super.setQuotaUser(quotaUser);
}
@Override
public RequestSync setUploadType(java.lang.String uploadType) {
return (RequestSync) super.setUploadType(uploadType);
}
@Override
public RequestSync setUploadProtocol(java.lang.String uploadProtocol) {
return (RequestSync) super.setUploadProtocol(uploadProtocol);
}
@Override
public RequestSync set(String parameterName, Object value) {
return (RequestSync) super.set(parameterName, value);
}
}
/**
* Gets all the devices associated with the given third-party user. The third-party user's identity
* is passed in via the `agent_user_id` (see SyncRequest). This request must be authorized using
* service account credentials from your Actions console project.
*
* Create a request for the method "devices.sync".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link Sync#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.homegraph.v1.model.SyncRequest}
* @return the request
*/
public Sync sync(com.google.api.services.homegraph.v1.model.SyncRequest content) throws java.io.IOException {
Sync result = new Sync(content);
initialize(result);
return result;
}
public class Sync extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.SyncResponse> {
private static final String REST_PATH = "v1/devices:sync";
/**
* Gets all the devices associated with the given third-party user. The third-party user's
* identity is passed in via the `agent_user_id` (see SyncRequest). This request must be
* authorized using service account credentials from your Actions console project.
*
* Create a request for the method "devices.sync".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link Sync#execute()} method to invoke the remote operation. <p>
* {@link Sync#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.homegraph.v1.model.SyncRequest}
* @since 1.13
*/
protected Sync(com.google.api.services.homegraph.v1.model.SyncRequest content) {
super(HomeGraphService.this, "POST", REST_PATH, content, com.google.api.services.homegraph.v1.model.SyncResponse.class);
}
@Override
public Sync set$Xgafv(java.lang.String $Xgafv) {
return (Sync) super.set$Xgafv($Xgafv);
}
@Override
public Sync setAccessToken(java.lang.String accessToken) {
return (Sync) super.setAccessToken(accessToken);
}
@Override
public Sync setAlt(java.lang.String alt) {
return (Sync) super.setAlt(alt);
}
@Override
public Sync setCallback(java.lang.String callback) {
return (Sync) super.setCallback(callback);
}
@Override
public Sync setFields(java.lang.String fields) {
return (Sync) super.setFields(fields);
}
@Override
public Sync setKey(java.lang.String key) {
return (Sync) super.setKey(key);
}
@Override
public Sync setOauthToken(java.lang.String oauthToken) {
return (Sync) super.setOauthToken(oauthToken);
}
@Override
public Sync setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Sync) super.setPrettyPrint(prettyPrint);
}
@Override
public Sync setQuotaUser(java.lang.String quotaUser) {
return (Sync) super.setQuotaUser(quotaUser);
}
@Override
public Sync setUploadType(java.lang.String uploadType) {
return (Sync) super.setUploadType(uploadType);
}
@Override
public Sync setUploadProtocol(java.lang.String uploadProtocol) {
return (Sync) super.setUploadProtocol(uploadProtocol);
}
@Override
public Sync set(String parameterName, Object value) {
return (Sync) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link HomeGraphService}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link HomeGraphService}. */
@Override
public HomeGraphService build() {
return new HomeGraphService(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link HomeGraphServiceRequestInitializer}.
*
* @since 1.12
*/
public Builder setHomeGraphServiceRequestInitializer(
HomeGraphServiceRequestInitializer homegraphserviceRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(homegraphserviceRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-homegraph/v1/1.30.1/com/google/api/services/homegraph/v1/HomeGraphService.java | Java | apache-2.0 | 33,723 |
package org.jfl2.fx.controller.menu;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.scene.Node;
import javafx.scene.control.RadioButton;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import lombok.extern.slf4j.Slf4j;
import org.jfl2.core.util.Jfl2NumberUtils;
import org.jfl2.fx.control.MenuPane;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
public class MenuWindowManager {
private Map<String, MenuWindow> id2MenuWindow = new HashMap<>();
/**
* 表示中のメニュー
*/
private MenuWindow nowMenu;
/**
* 選択中のアイテムIndex
*/
private int selected = -1;
/**
* Pane
*/
private MenuPane menuPane;
/**
* Constructor
*
* @param pane
*/
public MenuWindowManager(MenuPane pane) {
menuPane = pane;
}
/**
* 管理対象にMenuWindowを追加
*
* @param menu
* @return
*/
public MenuWindowManager add(MenuWindow menu) {
id2MenuWindow.put(menu.id, menu);
return this;
}
/**
* id からMenuWindowを取得
*
* @param id Specify string
* @return
*/
public MenuWindow get(String id) {
return id2MenuWindow.get(id);
}
/**
* メニューを開く
*
* @param id
* @return
*/
public MenuWindowManager show(String id) {
nowMenu = get(id);
if (nowMenu != null) {
menuPane.setTitleText(nowMenu.id);
menuPane.setDescriptionText(nowMenu.description);
menuPane.getListView().setVisible(false);
menuPane.getListView().setManaged(false);
/* listview は廃止
menuPane.setItems(FXCollections.observableList(nowMenu.items));
VirtualFlow flow = (VirtualFlow) menuPane.getListView().getChildrenUnmodifiable().get(0);
double height = 0;
for (int n = 0; n < nowMenu.items.size(); n++) {
IndexedCell cell = flow.getCell(n);
if (cell != null) {
height += cell.getHeight();
}
}
height = Jfl2Const.getMaxValue(height, Jfl2Const.MENU_MAX_HEIGHT);
// menuPane.getListView().setStyle("-fx-pref-height: " + height + ";");
/**/
List<RadioButton> rList = nowMenu.items.stream().map(menuItem -> {
RadioButton btn = new RadioButton(menuItem.toString());
btn.setFocusTraversable(false);
btn.setToggleGroup(menuPane.getToggleGroup());
btn.onMouseEnteredProperty().set((ev) -> select(menuItem));
menuPane.getRadioBox().getChildren().add(btn);
menuPane.getButtons().add(btn);
return btn;
}).collect(Collectors.toList());
selectFirst();
menuPane.setVisible(true);
getFocus();
}
return this;
}
/**
* 1つ上を選択
*/
public MenuWindowManager up() {
select(selected - 1, true);
return this;
}
/**
* 1つ下を選択
*/
public MenuWindowManager down() {
select(selected + 1, true);
return this;
}
/**
* 現在選択されているものを実行する
*
* @return
*/
public MenuWindowManager enter() {
return enter(selected);
}
/**
* 指定したIndexのMenuを実行する
*
* @return
*/
public MenuWindowManager enter(int index) {
return enter(nowMenu.items.get(index));
}
/**
* 指定したMenuItemを実行する
*
* @param item MenuItem is executed.
* @return
*/
public MenuWindowManager enter(MenuItem item) {
hide();
item.getConsumer().accept(null);
return this;
}
/**
* 指定したボタンを選択する
*
* @param index 0開始
* @param loop 上下間ループするならtrue
* @return
*/
public MenuWindowManager select(int index, boolean loop) {
if (menuPane.getButtons() != null) {
selected = Jfl2NumberUtils.loopValue(index, menuPane.getButtons().size(), loop);
menuPane.getButtons().get(selected).setSelected(true);
}
return this;
}
/**
* 指定したボタンを選択する
*
* @param menuItem MenuItem
* @return
*/
public MenuWindowManager select(MenuItem menuItem){
int index=0;
for( MenuItem item : nowMenu.items ){
if(Objects.equals(item, menuItem)){
select(index, false);
}
index++;
}
return this;
}
/**
* 最初のボタンを選択する
*/
public MenuWindowManager selectFirst() {
select(0, false);
return this;
}
/**
* ListViewにフォーカスを移す
*/
public void getFocus() {
Platform.runLater(() -> {
Optional<RadioButton> selected = menuPane.getButtons().stream().filter(RadioButton::isSelected).findFirst();
selected.ifPresent(RadioButton::requestFocus);
});
}
/**
* メニューを閉じる
*
* @return
*/
public MenuWindowManager hide() {
menuPane.setVisible(false);
menuPane.setDescriptionText("");
// menuPane.clearItems();
menuPane.getMenuBox().getChildren().removeAll();
menuPane.getButtons().stream().forEach(node->node.onMouseEnteredProperty().unbind());
menuPane.getButtons().clear();
menuPane.getRadioBox().getChildren().clear();
nowMenu = null;
return this;
}
/**
* その他キーの処理
*
* @param event
* @return
*/
public MenuWindowManager quickSelect(Event event) {
if (KeyEvent.class.isInstance(event)) {
KeyEvent keyEvent = (KeyEvent) event;
nowMenu.items.stream().filter(
(item) -> item.getKey().isHandle(keyEvent)
).findFirst().ifPresent(item -> enter(item));
}
return this;
}
/**
* ホバー時のイベント
* @param mouseEvent
* @return
*/
public MenuWindowManager hover(MouseEvent mouseEvent) {
int index = 0;
for( Node node : menuPane.getRadioBox().getChildren() ){
if( node.contains(mouseEvent.getSceneX(), mouseEvent.getSceneY()) ){
select(index, false);
}
if( node.contains(mouseEvent.getScreenX(), mouseEvent.getScreenY()) ){
select(index, false);
}
index++;
}
return this;
}
}
| lei0229/jfl2 | src/main/java/org/jfl2/fx/controller/menu/MenuWindowManager.java | Java | apache-2.0 | 6,781 |
package sunning.democollection.learn._0331.component;
import dagger.Component;
import sunning.democollection.learn._0331.UserActivity;
import sunning.democollection.learn._0331.module.ShoppingCartModule;
/**
* Created by sunning on 16/3/31.
*/
@Component(dependencies = ActivityComponent.class, modules = ShoppingCartModule.class)
public interface ShoppingCartComponent {
void inject(UserActivity userActivity);
}
| syg5201314/demoCollection | app/src/main/java/sunning/democollection/learn/_0331/component/ShoppingCartComponent.java | Java | apache-2.0 | 422 |
/**
* 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.deephacks.tools4j.config.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import org.deephacks.tools4j.support.io.FileUtils;
import org.deephacks.tools4j.support.test.JUnitUtils;
public class XmlStorageHelper {
public static void clearAndInit(Class<?> projectLocalClass) {
File dir = JUnitUtils.getMavenProjectChildFile(projectLocalClass, "target");
System.setProperty("config.spi.schema.xml.dir", dir.getAbsolutePath());
clearXmlStorageFile(dir, "<schema-xml></schema-xml>", "schema.xml");
System.setProperty("config.spi.bean.xml.dir", dir.getAbsolutePath());
clearXmlStorageFile(dir, "<bean-xml></bean-xml>", "bean.xml");
}
private static void clearXmlStorageFile(File dir, String contents, String fileName) {
FileWriter writer = null;
try {
// make sure dir exist
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir, fileName);
if (!file.exists()) {
file.createNewFile();
}
writer = new FileWriter(new File(dir, fileName));
writer.write(contents);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
FileUtils.close(writer);
}
}
}
| kristianolsson/tools4j | config/config-tck/src/main/java/org/deephacks/tools4j/config/test/XmlStorageHelper.java | Java | apache-2.0 | 2,047 |
package gui.sub_controllers;
import gui.GraphDrawer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import org.jetbrains.annotations.NotNull;
import structures.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeSet;
/**
* View-Controller for the genome table.
*
* @author Marco Jakob -> from http://code.makery.ch/blog/javafx-8-tableview-sorting-filtering/
* Changed to view and change annotations by Jip Rietveld
*/
public class AnnotationTableController {
@FXML
private TextField filterField;
@FXML
private TableView<Annotation> annotationTable;
@FXML
private TableColumn<Annotation, Integer> startColumn;
@FXML
private TableColumn<Annotation, Integer> endColumn;
@FXML
private TableColumn<Annotation, String> infoColumn;
@FXML
private TableColumn<Annotation, Boolean> highlightColumn;
private SortedList<Annotation> sortedData;
private HashMap<Integer, TreeSet<Annotation>> annotations;
private HashMap<Integer, TreeSet<Annotation>> updatedAnnotations;
private boolean allSelected;
/**
* Just add some sample data in the constructor.
*/
public AnnotationTableController() {
}
/**
* Initializes the controller class.
* Needs to be called manually to get the data.
* Initializes the table columns and sets up sorting and filtering.
*
* @param annotationsArg the annotations to load into the table.
*/
@FXML
@SuppressWarnings("MethodLength") //It is only 2 too long and the comments ensure clarity.
public void initialize(HashMap<Integer, TreeSet<Annotation>> annotationsArg) {
this.annotations = annotationsArg;
this.updatedAnnotations = this.annotations;
allSelected = false;
ObservableList<Annotation> masterData =
FXCollections.observableArrayList(new ArrayList<>(bucketsToTreeSet()));
// 0. Initialize the columns.
initializeColumns();
// 0.1 setRight editable columns
setEditable();
// 1. Wrap the ObservableList in a FilteredList (initially display all data).
FilteredList<Annotation> filteredData = new FilteredList<>(masterData, p -> true);
// 2. Set the filter Predicate whenever the filter changes.
filterField.textProperty().addListener((observable, oldValue, newValue)
-> filteredData.setPredicate(annotation -> {
// If filter text is empty, display all annotations.
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
//Check the info, but also co-ordinates.
return annotation.getInfo().toLowerCase().contains(lowerCaseFilter)
|| Integer.toString(annotation.getStart()).contains(lowerCaseFilter)
|| Integer.toString(annotation.getEnd()).contains(lowerCaseFilter);
}));
// 3. Wrap the FilteredList in a SortedList.
sortedData = new SortedList<>(filteredData);
// 4. Bind the SortedList comparator to the TableView comparator.
sortedData.comparatorProperty().bind(annotationTable.comparatorProperty());
// 5. Add sorted (and filtered) data to the table.
annotationTable.setItems(sortedData);
}
/**
* Sets the hashMap annotations to a HashSet.
*
* @return a hash set of the buckets of annotations
*/
@NotNull
private TreeSet<Annotation> bucketsToTreeSet() {
return bucketsToTreeSet(this.annotations);
}
/**
* Converts the hashMap to a hashSet.
*
* @param hashMap The hashMap to be converted.
* @return a hashSet of the hashMap.
*/
private TreeSet<Annotation> bucketsToTreeSet(HashMap<Integer, TreeSet<Annotation>> hashMap) {
if (hashMap == null) {
return null;
}
TreeSet<Annotation> drawThese = new TreeSet<>();
for (int i = 0; i <= hashMap.size(); i++) {
TreeSet<Annotation> tempAnnotations = hashMap.get(i);
if (tempAnnotations != null) {
drawThese.addAll(tempAnnotations);
}
}
return drawThese;
}
/**
* Method that sets the columns and table to the correct editable state.
*/
private void setEditable() {
annotationTable.setEditable(true);
startColumn.setEditable(false);
endColumn.setEditable(false);
infoColumn.setEditable(false);
highlightColumn.setEditable(true);
}
/**
* Method that initializes the columns with the right factories.
*/
private void initializeColumns() {
startColumn.setCellValueFactory(new PropertyValueFactory<>("start"));
endColumn.setCellValueFactory(new PropertyValueFactory<>("end"));
infoColumn.setCellValueFactory(new PropertyValueFactory<>("info"));
highlightColumn.setCellValueFactory(
param -> param.getValue().getSelected());
highlightColumn.setCellFactory(CheckBoxTableCell.forTableColumn(highlightColumn));
annotationTable.setRowFactory(tv -> {
TableRow<Annotation> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
Annotation annotation = row.getItem();
goToAnnotation(annotation);
close();
}
});
return row;
});
}
/**
* Method that goes to the annotation and highlights it.
*
* @param annotation the Annotation to go to.
*/
private void goToAnnotation(Annotation annotation) {
try {
int startNodeID = GraphDrawer.getInstance().hongerInAfrika(annotation.getStart());
int endNodeID = GraphDrawer.getInstance().hongerInAfrika(annotation.getEnd());
int soortVanRadius = (int) ((endNodeID - startNodeID) * 1.2);
if (soortVanRadius > 4000) {
ZoomController.getInstance().traverseGraphClicked(startNodeID, 4000);
} else {
ZoomController.getInstance().traverseGraphClicked(((endNodeID + startNodeID) / 2),
Math.max(soortVanRadius, (int) Math.sqrt(49)));
}
GraphDrawer.getInstance().highlightAnnotation(annotation);
} catch (StackOverflowError e) {
AnnotationPopUpController popUp = new AnnotationPopUpController();
popUp.loadNoAnnotationFound("Sorry, can't find this annotation.");
System.err.println("Sorry, too many nodes without ref to hold in memory.");
}
}
/**
* Handles pressing the save button.
*/
@FXML
public void saveButtonClicked() {
updatedAnnotations = annotations;
Annotation annotation = annotationTable.getSelectionModel().getSelectedItem();
if (annotation != null) {
goToAnnotation(annotation);
}
close();
}
/**
* Handles pressing the cancel button.
*/
public void cancelButtonClicked() {
close();
}
/**
* A general function that closes the stage.
*/
private void close() {
Stage stage = (Stage) annotationTable.getScene().getWindow();
stage.close();
}
/**
* Can select/deselect the entire sortedData at the same time.
*/
@FXML
public void selectAllFiltered() {
for (Annotation annotation : sortedData) {
if (allSelected) {
annotation.setSelected(false);
} else {
annotation.setSelected(true);
}
}
annotationTable.setItems(sortedData);
allSelected = !allSelected;
}
public HashMap<Integer, TreeSet<Annotation>> getAnnotations() {
return updatedAnnotations;
}
}
| ProgrammingLife2017/DynamiteAndButterflies | src/main/java/gui/sub_controllers/AnnotationTableController.java | Java | apache-2.0 | 8,434 |
package liquibase.change.core;
import liquibase.change.AbstractSQLChange;
import liquibase.change.DatabaseChange;
import liquibase.change.ChangeMetaData;
/**
* Allows execution of arbitrary SQL. This change can be used when existing changes are either don't exist,
* are not flexible enough, or buggy.
*/
@DatabaseChange(name="sql",
description = "The 'sql' tag allows you to specify whatever sql you want. It is useful for complex changes that aren't supported through Liquibase's automated refactoring tags and to work around bugs and limitations of Liquibase. The SQL contained in the sql tag can be multi-line.\n" +
"\n" +
"The createProcedure refactoring is the best way to create stored procedures.\n" +
"\n" +
"The 'sql' tag can also support multiline statements in the same file. Statements can either be split using a ; at the end of the last line of the SQL or a go on its own on the line between the statements can be used.Multiline SQL statements are also supported and only a ; or go statement will finish a statement, a new line is not enough. Files containing a single statement do not need to use a ; or go.\n" +
"\n" +
"The sql change can also contain comments of either of the following formats:\n" +
"\n" +
"A multiline comment that starts with /* and ends with */.\n" +
"A single line comment starting with <space>--<space> and finishing at the end of the line\n" +
"Note: By default it will attempt to split statements on a ';' or 'go' at the end of lines. Because of this, if you have a comment or some other non-statement ending ';' or 'go', don't have it at the end of a line or you will get invalid SQL.",
priority = ChangeMetaData.PRIORITY_DEFAULT)
public class RawSQLChange extends AbstractSQLChange {
private String comment;
public RawSQLChange() {
}
public RawSQLChange(String sql) {
setSql(sql);
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getConfirmationMessage() {
return "Custom SQL executed";
}
}
| ArloL/liquibase | liquibase-core/src/main/java/liquibase/change/core/RawSQLChange.java | Java | apache-2.0 | 2,252 |
package com.deleidos.dp.export;
import com.deleidos.dp.beans.Schema;
import com.deleidos.dp.exceptions.H2DataAccessException;
import com.deleidos.dp.exceptions.SchemaNotFoundException;
public interface Exporter {
public abstract String generateExport(Schema schema);
public abstract String generateExport(Schema schema, Schema previousVersion);
}
| deleidos/de-schema-wizard | data-profiler/src/main/java/com/deleidos/dp/export/Exporter.java | Java | apache-2.0 | 356 |
package org.jtrim2.swing.component;
import java.util.Collections;
import org.jtrim2.image.transform.ZoomToFitOption;
import org.junit.Test;
public class TransformationAdapterTest {
/**
* Not much to test but that the methods does not throw exceptions.
*/
@Test
public void testMethods() {
TransformationAdapterImpl listener = new TransformationAdapterImpl();
listener.enterZoomToFitMode(Collections.<ZoomToFitOption>emptySet());
listener.flipChanged();
listener.leaveZoomToFitMode();
listener.offsetChanged();
listener.rotateChanged();
listener.zoomChanged();
}
public class TransformationAdapterImpl extends TransformationAdapter {
}
}
| kelemen/JTrim | subprojects/jtrim-swing-component/src/test/java/org/jtrim2/swing/component/TransformationAdapterTest.java | Java | apache-2.0 | 731 |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appyvet.rangebarsample.colorpicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import com.appyvet.rangebarsample.Component;
import com.appyvet.rangebarsample.R;
/**
* A dialog which takes in as input an array of colors and creates a palette allowing the user to
* select a specific color swatch, which invokes a listener.
*/
public class ColorPickerDialog extends DialogFragment implements ColorPickerSwatch.OnSwatchColorSelectedListener {
/**
* Interface for a callback when a color square is selected.
*/
public interface OnColorSelectedListener {
/**
* Called when a specific color square has been selected.
*/
public void onColorSelected(int color, Component component);
}
public static final int SIZE_LARGE = 1;
public static final int SIZE_SMALL = 2;
protected AlertDialog mAlertDialog;
protected static final String KEY_TITLE_ID = "title_id";
protected static final String KEY_COLORS = "colors";
protected static final String KEY_SELECTED_COLOR = "selected_color";
protected static final String KEY_COLUMNS = "columns";
protected static final String KEY_SIZE = "size";
protected int mTitleResId = R.string.color_picker_default_title;
protected int[] mColors = null;
protected int mSelectedColor;
protected int mColumns;
protected int mSize;
private Component mComponent;
private ColorPickerPalette mPalette;
private ProgressBar mProgress;
protected OnColorSelectedListener mListener;
public ColorPickerDialog() {
// Empty constructor required for dialog fragments.
}
public static ColorPickerDialog newInstance(int titleResId, int[] colors, int selectedColor,
int columns, int size, Component component) {
ColorPickerDialog ret = new ColorPickerDialog();
ret.initialize(titleResId, colors, selectedColor, columns, size, component);
return ret;
}
public void initialize(int titleResId, int[] colors, int selectedColor, int columns, int size, Component component) {
setArguments(titleResId, columns, size);
setColors(colors, selectedColor);
mComponent = component;
}
public void setArguments(int titleResId, int columns, int size) {
Bundle bundle = new Bundle();
bundle.putInt(KEY_TITLE_ID, titleResId);
bundle.putInt(KEY_COLUMNS, columns);
bundle.putInt(KEY_SIZE, size);
setArguments(bundle);
}
public void setOnColorSelectedListener(OnColorSelectedListener listener) {
mListener = listener;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitleResId = getArguments().getInt(KEY_TITLE_ID);
mColumns = getArguments().getInt(KEY_COLUMNS);
mSize = getArguments().getInt(KEY_SIZE);
}
if (savedInstanceState != null) {
mColors = savedInstanceState.getIntArray(KEY_COLORS);
mSelectedColor = (Integer) savedInstanceState.getSerializable(KEY_SELECTED_COLOR);
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Activity activity = getActivity();
View view = LayoutInflater.from(getActivity()).inflate(R.layout.color_picker_dialog, null);
mProgress = (ProgressBar) view.findViewById(android.R.id.progress);
mPalette = (ColorPickerPalette) view.findViewById(R.id.color_picker);
mPalette.init(mSize, mColumns, this);
if (mColors != null) {
showPaletteView();
}
mAlertDialog = new AlertDialog.Builder(activity)
.setTitle(mTitleResId)
.setView(view)
.create();
return mAlertDialog;
}
@Override
public void onSwatchColorSelected(int color) {
if (mListener != null) {
mListener.onColorSelected(color, mComponent);
}
if (getTargetFragment() instanceof ColorPickerSwatch.OnSwatchColorSelectedListener) {
final OnColorSelectedListener listener =
(OnColorSelectedListener) getTargetFragment();
listener.onColorSelected(color, mComponent);
}
if (color != mSelectedColor) {
mSelectedColor = color;
// Redraw palette to show checkmark on newly selected color before dismissing.
mPalette.drawPalette(mColors, mSelectedColor);
}
dismiss();
}
public void showPaletteView() {
if (mProgress != null && mPalette != null) {
mProgress.setVisibility(View.GONE);
refreshPalette();
mPalette.setVisibility(View.VISIBLE);
}
}
public void showProgressBarView() {
if (mProgress != null && mPalette != null) {
mProgress.setVisibility(View.VISIBLE);
mPalette.setVisibility(View.GONE);
}
}
public void setColors(int[] colors, int selectedColor) {
if (mColors != colors || mSelectedColor != selectedColor) {
mColors = colors;
mSelectedColor = selectedColor;
refreshPalette();
}
}
public void setColors(int[] colors) {
if (mColors != colors) {
mColors = colors;
refreshPalette();
}
}
public void setSelectedColor(int color) {
if (mSelectedColor != color) {
mSelectedColor = color;
refreshPalette();
}
}
private void refreshPalette() {
if (mPalette != null && mColors != null) {
mPalette.drawPalette(mColors, mSelectedColor);
}
}
public int[] getColors() {
return mColors;
}
public int getSelectedColor() {
return mSelectedColor;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray(KEY_COLORS, mColors);
outState.putSerializable(KEY_SELECTED_COLOR, mSelectedColor);
}
}
| oli107/material-range-bar | RangeBarSample/src/main/java/com/appyvet/rangebarsample/colorpicker/ColorPickerDialog.java | Java | apache-2.0 | 6,997 |
package com.lling.qiqu.commons;
import java.io.Serializable;
/**
* @ClassName: ResponseInfo
* @Description: http接口返回数据封装类
* @author lling
* @date 2015-5-30
*/
public class ResponseInfo implements Serializable{
private static final long serialVersionUID = 1L;
private String code;
private String desc;
private Object data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
| liuling07/QiQuYing | app/src/main/java/com/lling/qiqu/commons/ResponseInfo.java | Java | apache-2.0 | 673 |
/*
* EVE Swagger Interface
* An OpenAPI for EVE Online
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package net.troja.eve.esi.model;
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;
import java.util.ArrayList;
import java.util.List;
import net.troja.eve.esi.model.PlanetLink;
import net.troja.eve.esi.model.PlanetPin;
import net.troja.eve.esi.model.PlanetRoute;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for CharacterPlanetResponse
*/
public class CharacterPlanetResponseTest {
private final CharacterPlanetResponse model = new CharacterPlanetResponse();
/**
* Model tests for CharacterPlanetResponse
*/
@Test
public void testCharacterPlanetResponse() {
// TODO: test CharacterPlanetResponse
}
/**
* Test the property 'routes'
*/
@Test
public void routesTest() {
// TODO: test routes
}
/**
* Test the property 'links'
*/
@Test
public void linksTest() {
// TODO: test links
}
/**
* Test the property 'pins'
*/
@Test
public void pinsTest() {
// TODO: test pins
}
}
| burberius/eve-esi | src/test/java/net/troja/eve/esi/model/CharacterPlanetResponseTest.java | Java | apache-2.0 | 1,583 |
/*
* Copyright 2006-2010 Virtual Laboratory for e-Science (www.vl-e.nl)
* Copyright 2012-2013 Netherlands eScience Center.
*
* 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 the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For the full license, see: LICENSE.txt (located in the root folder of this distribution).
* ---
*/
// source:
package nl.esciencecenter.vlet.vfs.lfc;
public class SEInfo
{
public String hostname=null;
public int optionalPort=-1;
public SEInfo(String infoStr)
{
// fail not or else fail later
if ((infoStr==null) || infoStr.equals(""))
throw new NullPointerException("Storage Element info string can not be null or empty");
String strs[]=infoStr.split(":");
if (strs.length>0)
hostname=strs[0];
if (strs.length>1)
optionalPort=Integer.parseInt(strs[1]);
}
public boolean hasExplicitPort()
{
return (optionalPort>0);
}
public int getPort()
{
return optionalPort;
}
public String getHostname()
{
return hostname;
}
}
| NLeSC/vbrowser | source/nl.esciencecenter.vlet.vfs.lfc/src/nl/esciencecenter/vlet/vfs/lfc/SEInfo.java | Java | apache-2.0 | 1,641 |
/*
* 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.lightsail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes the source of a CloudFormation stack record (i.e., the export snapshot record).
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CloudFormationStackRecordSourceInfo"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CloudFormationStackRecordSourceInfo implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* </p>
*/
private String resourceType;
/**
* <p>
* The name of the record.
* </p>
*/
private String name;
/**
* <p>
* The Amazon Resource Name (ARN) of the export snapshot record.
* </p>
*/
private String arn;
/**
* <p>
* The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* </p>
*
* @param resourceType
* The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* @see CloudFormationStackRecordSourceType
*/
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
/**
* <p>
* The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* </p>
*
* @return The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* @see CloudFormationStackRecordSourceType
*/
public String getResourceType() {
return this.resourceType;
}
/**
* <p>
* The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* </p>
*
* @param resourceType
* The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* @return Returns a reference to this object so that method calls can be chained together.
* @see CloudFormationStackRecordSourceType
*/
public CloudFormationStackRecordSourceInfo withResourceType(String resourceType) {
setResourceType(resourceType);
return this;
}
/**
* <p>
* The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* </p>
*
* @param resourceType
* The Lightsail resource type (e.g., <code>ExportSnapshotRecord</code>).
* @return Returns a reference to this object so that method calls can be chained together.
* @see CloudFormationStackRecordSourceType
*/
public CloudFormationStackRecordSourceInfo withResourceType(CloudFormationStackRecordSourceType resourceType) {
this.resourceType = resourceType.toString();
return this;
}
/**
* <p>
* The name of the record.
* </p>
*
* @param name
* The name of the record.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the record.
* </p>
*
* @return The name of the record.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the record.
* </p>
*
* @param name
* The name of the record.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CloudFormationStackRecordSourceInfo withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the export snapshot record.
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the export snapshot record.
*/
public void setArn(String arn) {
this.arn = arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the export snapshot record.
* </p>
*
* @return The Amazon Resource Name (ARN) of the export snapshot record.
*/
public String getArn() {
return this.arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the export snapshot record.
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the export snapshot record.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CloudFormationStackRecordSourceInfo withArn(String arn) {
setArn(arn);
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 (getResourceType() != null)
sb.append("ResourceType: ").append(getResourceType()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getArn() != null)
sb.append("Arn: ").append(getArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CloudFormationStackRecordSourceInfo == false)
return false;
CloudFormationStackRecordSourceInfo other = (CloudFormationStackRecordSourceInfo) obj;
if (other.getResourceType() == null ^ this.getResourceType() == null)
return false;
if (other.getResourceType() != null && other.getResourceType().equals(this.getResourceType()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getArn() == null ^ this.getArn() == null)
return false;
if (other.getArn() != null && other.getArn().equals(this.getArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getResourceType() == null) ? 0 : getResourceType().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode());
return hashCode;
}
@Override
public CloudFormationStackRecordSourceInfo clone() {
try {
return (CloudFormationStackRecordSourceInfo) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.lightsail.model.transform.CloudFormationStackRecordSourceInfoMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/CloudFormationStackRecordSourceInfo.java | Java | apache-2.0 | 8,005 |
/*
* 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.rocketmq.common;
import org.apache.rocketmq.common.annotation.ImportantField;
import org.apache.rocketmq.common.constant.PermName;
import org.apache.rocketmq.remoting.common.RemotingUtil;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class BrokerConfig {
private String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
@ImportantField
private String namesrvAddr = System.getProperty(MixAll.NAMESRV_ADDR_PROPERTY, System.getenv(MixAll.NAMESRV_ADDR_ENV));
@ImportantField
private String brokerIP1 = RemotingUtil.getLocalAddress();
private String brokerIP2 = RemotingUtil.getLocalAddress();
@ImportantField
private String brokerName = localHostName();
@ImportantField
private String brokerClusterName = "DefaultCluster";
@ImportantField
private long brokerId = MixAll.MASTER_ID;
/**
* Broker 权限(读写等)
*/
private int brokerPermission = PermName.PERM_READ | PermName.PERM_WRITE;
private int defaultTopicQueueNums = 8;
@ImportantField
private boolean autoCreateTopicEnable = true;
private boolean clusterTopicEnable = true;
private boolean brokerTopicEnable = true;
@ImportantField
private boolean autoCreateSubscriptionGroup = true;
private String messageStorePlugIn = "";
private int sendMessageThreadPoolNums = 1; //16 + Runtime.getRuntime().availableProcessors() * 4;
private int pullMessageThreadPoolNums = 16 + Runtime.getRuntime().availableProcessors() * 2;
private int adminBrokerThreadPoolNums = 16;
private int clientManageThreadPoolNums = 32;
private int consumerManageThreadPoolNums = 32;
private int flushConsumerOffsetInterval = 1000 * 5;
private int flushConsumerOffsetHistoryInterval = 1000 * 60;
@ImportantField
private boolean rejectTransactionMessage = false;
@ImportantField
private boolean fetchNamesrvAddrByAddressServer = false;
private int sendThreadPoolQueueCapacity = 10000;
private int pullThreadPoolQueueCapacity = 100000;
private int clientManagerThreadPoolQueueCapacity = 1000000;
private int consumerManagerThreadPoolQueueCapacity = 1000000;
private int filterServerNums = 0;
private boolean longPollingEnable = true;
private long shortPollingTimeMills = 1000;
private boolean notifyConsumerIdsChangedEnable = true;
private boolean highSpeedMode = false;
private boolean commercialEnable = true;
private int commercialTimerCount = 1;
private int commercialTransCount = 1;
private int commercialBigCount = 1;
private int commercialBaseCount = 1;
private boolean transferMsgByHeap = true;
private int maxDelayTime = 40;
// TODO 疑问:这个是干啥的
private String regionId = MixAll.DEFAULT_TRACE_REGION_ID;
private int registerBrokerTimeoutMills = 6000;
private boolean slaveReadEnable = false;
private boolean disableConsumeIfConsumerReadSlowly = false;
private long consumerFallbehindThreshold = 1024L * 1024 * 1024 * 16;
private long waitTimeMillsInSendQueue = 200;
/**
* 开始接收请求时间
* TODO 疑问:什么时候设置的
*/
private long startAcceptSendRequestTimeStamp = 0L;
private boolean traceOn = true;
public static String localHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "DEFAULT_BROKER";
}
public boolean isTraceOn() {
return traceOn;
}
public void setTraceOn(final boolean traceOn) {
this.traceOn = traceOn;
}
public long getStartAcceptSendRequestTimeStamp() {
return startAcceptSendRequestTimeStamp;
}
public void setStartAcceptSendRequestTimeStamp(final long startAcceptSendRequestTimeStamp) {
this.startAcceptSendRequestTimeStamp = startAcceptSendRequestTimeStamp;
}
public long getWaitTimeMillsInSendQueue() {
return waitTimeMillsInSendQueue;
}
public void setWaitTimeMillsInSendQueue(final long waitTimeMillsInSendQueue) {
this.waitTimeMillsInSendQueue = waitTimeMillsInSendQueue;
}
public long getConsumerFallbehindThreshold() {
return consumerFallbehindThreshold;
}
public void setConsumerFallbehindThreshold(final long consumerFallbehindThreshold) {
this.consumerFallbehindThreshold = consumerFallbehindThreshold;
}
public boolean isDisableConsumeIfConsumerReadSlowly() {
return disableConsumeIfConsumerReadSlowly;
}
public void setDisableConsumeIfConsumerReadSlowly(final boolean disableConsumeIfConsumerReadSlowly) {
this.disableConsumeIfConsumerReadSlowly = disableConsumeIfConsumerReadSlowly;
}
public boolean isSlaveReadEnable() {
return slaveReadEnable;
}
public void setSlaveReadEnable(final boolean slaveReadEnable) {
this.slaveReadEnable = slaveReadEnable;
}
public int getRegisterBrokerTimeoutMills() {
return registerBrokerTimeoutMills;
}
public void setRegisterBrokerTimeoutMills(final int registerBrokerTimeoutMills) {
this.registerBrokerTimeoutMills = registerBrokerTimeoutMills;
}
public String getRegionId() {
return regionId;
}
public void setRegionId(final String regionId) {
this.regionId = regionId;
}
public boolean isTransferMsgByHeap() {
return transferMsgByHeap;
}
public void setTransferMsgByHeap(final boolean transferMsgByHeap) {
this.transferMsgByHeap = transferMsgByHeap;
}
public String getMessageStorePlugIn() {
return messageStorePlugIn;
}
public void setMessageStorePlugIn(String messageStorePlugIn) {
this.messageStorePlugIn = messageStorePlugIn;
}
public boolean isHighSpeedMode() {
return highSpeedMode;
}
public void setHighSpeedMode(final boolean highSpeedMode) {
this.highSpeedMode = highSpeedMode;
}
public String getRocketmqHome() {
return rocketmqHome;
}
public void setRocketmqHome(String rocketmqHome) {
this.rocketmqHome = rocketmqHome;
}
public String getBrokerName() {
return brokerName;
}
public void setBrokerName(String brokerName) {
this.brokerName = brokerName;
}
public int getBrokerPermission() {
return brokerPermission;
}
public void setBrokerPermission(int brokerPermission) {
this.brokerPermission = brokerPermission;
}
public int getDefaultTopicQueueNums() {
return defaultTopicQueueNums;
}
public void setDefaultTopicQueueNums(int defaultTopicQueueNums) {
this.defaultTopicQueueNums = defaultTopicQueueNums;
}
public boolean isAutoCreateTopicEnable() {
return autoCreateTopicEnable;
}
public void setAutoCreateTopicEnable(boolean autoCreateTopic) {
this.autoCreateTopicEnable = autoCreateTopic;
}
public String getBrokerClusterName() {
return brokerClusterName;
}
public void setBrokerClusterName(String brokerClusterName) {
this.brokerClusterName = brokerClusterName;
}
public String getBrokerIP1() {
return brokerIP1;
}
public void setBrokerIP1(String brokerIP1) {
this.brokerIP1 = brokerIP1;
}
public String getBrokerIP2() {
return brokerIP2;
}
public void setBrokerIP2(String brokerIP2) {
this.brokerIP2 = brokerIP2;
}
public int getSendMessageThreadPoolNums() {
return sendMessageThreadPoolNums;
}
public void setSendMessageThreadPoolNums(int sendMessageThreadPoolNums) {
this.sendMessageThreadPoolNums = sendMessageThreadPoolNums;
}
public int getPullMessageThreadPoolNums() {
return pullMessageThreadPoolNums;
}
public void setPullMessageThreadPoolNums(int pullMessageThreadPoolNums) {
this.pullMessageThreadPoolNums = pullMessageThreadPoolNums;
}
public int getAdminBrokerThreadPoolNums() {
return adminBrokerThreadPoolNums;
}
public void setAdminBrokerThreadPoolNums(int adminBrokerThreadPoolNums) {
this.adminBrokerThreadPoolNums = adminBrokerThreadPoolNums;
}
public int getFlushConsumerOffsetInterval() {
return flushConsumerOffsetInterval;
}
public void setFlushConsumerOffsetInterval(int flushConsumerOffsetInterval) {
this.flushConsumerOffsetInterval = flushConsumerOffsetInterval;
}
public int getFlushConsumerOffsetHistoryInterval() {
return flushConsumerOffsetHistoryInterval;
}
public void setFlushConsumerOffsetHistoryInterval(int flushConsumerOffsetHistoryInterval) {
this.flushConsumerOffsetHistoryInterval = flushConsumerOffsetHistoryInterval;
}
public boolean isClusterTopicEnable() {
return clusterTopicEnable;
}
public void setClusterTopicEnable(boolean clusterTopicEnable) {
this.clusterTopicEnable = clusterTopicEnable;
}
public String getNamesrvAddr() {
return namesrvAddr;
}
public void setNamesrvAddr(String namesrvAddr) {
this.namesrvAddr = namesrvAddr;
}
public long getBrokerId() {
return brokerId;
}
public void setBrokerId(long brokerId) {
this.brokerId = brokerId;
}
public boolean isAutoCreateSubscriptionGroup() {
return autoCreateSubscriptionGroup;
}
public void setAutoCreateSubscriptionGroup(boolean autoCreateSubscriptionGroup) {
this.autoCreateSubscriptionGroup = autoCreateSubscriptionGroup;
}
public boolean isRejectTransactionMessage() {
return rejectTransactionMessage;
}
public void setRejectTransactionMessage(boolean rejectTransactionMessage) {
this.rejectTransactionMessage = rejectTransactionMessage;
}
public boolean isFetchNamesrvAddrByAddressServer() {
return fetchNamesrvAddrByAddressServer;
}
public void setFetchNamesrvAddrByAddressServer(boolean fetchNamesrvAddrByAddressServer) {
this.fetchNamesrvAddrByAddressServer = fetchNamesrvAddrByAddressServer;
}
public int getSendThreadPoolQueueCapacity() {
return sendThreadPoolQueueCapacity;
}
public void setSendThreadPoolQueueCapacity(int sendThreadPoolQueueCapacity) {
this.sendThreadPoolQueueCapacity = sendThreadPoolQueueCapacity;
}
public int getPullThreadPoolQueueCapacity() {
return pullThreadPoolQueueCapacity;
}
public void setPullThreadPoolQueueCapacity(int pullThreadPoolQueueCapacity) {
this.pullThreadPoolQueueCapacity = pullThreadPoolQueueCapacity;
}
public boolean isBrokerTopicEnable() {
return brokerTopicEnable;
}
public void setBrokerTopicEnable(boolean brokerTopicEnable) {
this.brokerTopicEnable = brokerTopicEnable;
}
public int getFilterServerNums() {
return filterServerNums;
}
public void setFilterServerNums(int filterServerNums) {
this.filterServerNums = filterServerNums;
}
public boolean isLongPollingEnable() {
return longPollingEnable;
}
public void setLongPollingEnable(boolean longPollingEnable) {
this.longPollingEnable = longPollingEnable;
}
public boolean isNotifyConsumerIdsChangedEnable() {
return notifyConsumerIdsChangedEnable;
}
public void setNotifyConsumerIdsChangedEnable(boolean notifyConsumerIdsChangedEnable) {
this.notifyConsumerIdsChangedEnable = notifyConsumerIdsChangedEnable;
}
public long getShortPollingTimeMills() {
return shortPollingTimeMills;
}
public void setShortPollingTimeMills(long shortPollingTimeMills) {
this.shortPollingTimeMills = shortPollingTimeMills;
}
public int getClientManageThreadPoolNums() {
return clientManageThreadPoolNums;
}
public void setClientManageThreadPoolNums(int clientManageThreadPoolNums) {
this.clientManageThreadPoolNums = clientManageThreadPoolNums;
}
public boolean isCommercialEnable() {
return commercialEnable;
}
public void setCommercialEnable(final boolean commercialEnable) {
this.commercialEnable = commercialEnable;
}
public int getCommercialTimerCount() {
return commercialTimerCount;
}
public void setCommercialTimerCount(final int commercialTimerCount) {
this.commercialTimerCount = commercialTimerCount;
}
public int getCommercialTransCount() {
return commercialTransCount;
}
public void setCommercialTransCount(final int commercialTransCount) {
this.commercialTransCount = commercialTransCount;
}
public int getCommercialBigCount() {
return commercialBigCount;
}
public void setCommercialBigCount(final int commercialBigCount) {
this.commercialBigCount = commercialBigCount;
}
public int getMaxDelayTime() {
return maxDelayTime;
}
public void setMaxDelayTime(final int maxDelayTime) {
this.maxDelayTime = maxDelayTime;
}
public int getClientManagerThreadPoolQueueCapacity() {
return clientManagerThreadPoolQueueCapacity;
}
public void setClientManagerThreadPoolQueueCapacity(int clientManagerThreadPoolQueueCapacity) {
this.clientManagerThreadPoolQueueCapacity = clientManagerThreadPoolQueueCapacity;
}
public int getConsumerManagerThreadPoolQueueCapacity() {
return consumerManagerThreadPoolQueueCapacity;
}
public void setConsumerManagerThreadPoolQueueCapacity(int consumerManagerThreadPoolQueueCapacity) {
this.consumerManagerThreadPoolQueueCapacity = consumerManagerThreadPoolQueueCapacity;
}
public int getConsumerManageThreadPoolNums() {
return consumerManageThreadPoolNums;
}
public void setConsumerManageThreadPoolNums(int consumerManageThreadPoolNums) {
this.consumerManageThreadPoolNums = consumerManageThreadPoolNums;
}
public int getCommercialBaseCount() {
return commercialBaseCount;
}
public void setCommercialBaseCount(int commercialBaseCount) {
this.commercialBaseCount = commercialBaseCount;
}
}
| Coneboy-k/incubator-rocketmq | common/src/main/java/org/apache/rocketmq/common/BrokerConfig.java | Java | apache-2.0 | 15,205 |
/*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.product.index;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.data.Offset.offset;
import java.time.LocalDate;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.product.PortfolioItemSummary;
import com.opengamma.strata.product.PortfolioItemType;
import com.opengamma.strata.product.ProductType;
import com.opengamma.strata.product.TradeInfo;
import com.opengamma.strata.product.TradedPrice;
/**
* Test {@link IborFutureTrade}.
*/
public class IborFutureTradeTest {
private static final ReferenceData REF_DATA = ReferenceData.standard();
private static final LocalDate TRADE_DATE = date(2015, 3, 18);
private static final TradeInfo TRADE_INFO = TradeInfo.of(TRADE_DATE);
private static final IborFuture PRODUCT = IborFutureTest.sut();
private static final IborFuture PRODUCT2 = IborFutureTest.sut2();
private static final double QUANTITY = 35;
private static final double QUANTITY2 = 36;
private static final double PRICE = 0.99;
private static final double PRICE2 = 0.98;
//-------------------------------------------------------------------------
@Test
public void test_builder() {
IborFutureTrade test = sut();
assertThat(test.getInfo()).isEqualTo(TRADE_INFO);
assertThat(test.getProduct()).isEqualTo(PRODUCT);
assertThat(test.getPrice()).isEqualTo(PRICE);
assertThat(test.getQuantity()).isEqualTo(QUANTITY);
assertThat(test.withInfo(TRADE_INFO).getInfo()).isEqualTo(TRADE_INFO);
assertThat(test.withQuantity(0.9129).getQuantity()).isCloseTo(0.9129d, offset(1e-10));
assertThat(test.withPrice(0.9129).getPrice()).isCloseTo(0.9129d, offset(1e-10));
}
@Test
public void test_builder_badPrice() {
assertThatIllegalArgumentException()
.isThrownBy(() -> sut().toBuilder().price(2.1).build());
}
//-------------------------------------------------------------------------
@Test
public void test_summarize() {
IborFutureTrade trade = sut();
PortfolioItemSummary expected = PortfolioItemSummary.builder()
.id(TRADE_INFO.getId().orElse(null))
.portfolioItemType(PortfolioItemType.TRADE)
.productType(ProductType.IBOR_FUTURE)
.currencies(Currency.USD)
.description("IborFuture x 35")
.build();
assertThat(trade.summarize()).isEqualTo(expected);
}
//-------------------------------------------------------------------------
@Test
public void test_resolve() {
IborFutureTrade test = sut();
ResolvedIborFutureTrade resolved = test.resolve(REF_DATA);
assertThat(resolved.getInfo()).isEqualTo(TRADE_INFO);
assertThat(resolved.getProduct()).isEqualTo(PRODUCT.resolve(REF_DATA));
assertThat(resolved.getQuantity()).isEqualTo(QUANTITY);
assertThat(resolved.getTradedPrice()).isEqualTo(Optional.of(TradedPrice.of(TRADE_DATE, PRICE)));
}
//-------------------------------------------------------------------------
@Test
public void test_withQuantity() {
IborFutureTrade base = sut();
double quantity = 65243;
IborFutureTrade computed = base.withQuantity(quantity);
IborFutureTrade expected = IborFutureTrade.builder()
.info(TRADE_INFO)
.product(PRODUCT)
.quantity(quantity)
.price(PRICE)
.build();
assertThat(computed).isEqualTo(expected);
}
@Test
public void test_withPrice() {
IborFutureTrade base = sut();
double price = 0.95;
IborFutureTrade computed = base.withPrice(price);
IborFutureTrade expected = IborFutureTrade.builder()
.info(TRADE_INFO)
.product(PRODUCT)
.quantity(QUANTITY)
.price(price)
.build();
assertThat(computed).isEqualTo(expected);
}
//-------------------------------------------------------------------------
@Test
public void coverage() {
coverImmutableBean(sut());
coverBeanEquals(sut(), sut2());
}
@Test
public void test_serialization() {
assertSerialization(sut());
}
//-------------------------------------------------------------------------
static IborFutureTrade sut() {
return IborFutureTrade.builder()
.info(TRADE_INFO)
.product(PRODUCT)
.quantity(QUANTITY)
.price(PRICE)
.build();
}
static IborFutureTrade sut2() {
return IborFutureTrade.builder()
.product(PRODUCT2)
.quantity(QUANTITY2)
.price(PRICE2)
.build();
}
}
| OpenGamma/Strata | modules/product/src/test/java/com/opengamma/strata/product/index/IborFutureTradeTest.java | Java | apache-2.0 | 5,092 |
/*
* Copyright (c) 2016. Sunghyouk Bae <sunghyouk.bae@gmail.com>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.redisson.spring.cache;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.inject.Inject;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author sunghyouk.bae@gmail.com
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RedissonCacheConfiguration.class})
public class RedissonCacheTest {
@Inject UserRepository userRepo;
@Test
public void testConfiguration() {
assertThat(userRepo).isNotNull();
}
@Test
public void testNull() {
userRepo.save("user1", null);
assertThat(userRepo.getNull("user1")).isNull();
userRepo.remove("user1");
assertThat(userRepo.getNull("user1")).isNull();
}
@Test
public void testRemove() {
userRepo.save("user1", UserRepository.UserObject.of("name1", "value1"));
assertThat(userRepo.get("user1"))
.isNotNull()
.isInstanceOf(UserRepository.UserObject.class);
userRepo.remove("user1");
assertThat(userRepo.getNull("user1")).isNull();
}
@Test
public void testPutGet() {
userRepo.save("user1", UserRepository.UserObject.of("name1", "value1"));
UserRepository.UserObject u = userRepo.get("user1");
assertThat(u).isNotNull();
assertThat(u.getName()).isEqualTo("name1");
assertThat(u.getValue()).isEqualTo("value1");
}
@Test(expected = IllegalStateException.class)
public void testGet() {
userRepo.get("notExists");
}
}
| debop/debop4k | debop4k-redis/src/test/java/debop4k/redisson/spring/cache/RedissonCacheTest.java | Java | apache-2.0 | 2,169 |
/*
* 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.geode.redis.internal;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import org.apache.geode.distributed.internal.DistributedSystemService;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.classloader.ClassPathLoader;
public class RedisDistributedSystemService implements DistributedSystemService {
@Override
public void init(InternalDistributedSystem internalDistributedSystem) {
}
@Override
public Class getInterface() {
return getClass();
}
@Override
public Collection<String> getSerializationAcceptlist() throws IOException {
URL sanctionedSerializables = ClassPathLoader.getLatest().getResource(getClass(),
"sanctioned-geode-apis-compatible-with-redis-serializables.txt");
return InternalDataSerializer.loadClassNames(sanctionedSerializables);
}
}
| masaki-yamakawa/geode | geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/RedisDistributedSystemService.java | Java | apache-2.0 | 1,750 |
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.lang.meta;
import leap.lang.Named;
import leap.lang.Titled;
public interface MNamed extends MObject,Named,Titled {
} | leapframework/framework | base/lang/src/main/java/leap/lang/meta/MNamed.java | Java | apache-2.0 | 748 |
package com.vladmihalcea.book.hpjp.hibernate.type.array;
import org.hibernate.dialect.PostgreSQL95Dialect;
import java.sql.Types;
/**
* @author Vlad Mihalcea
*/
public class PostgreSQL95ArrayDialect extends PostgreSQL95Dialect {
public PostgreSQL95ArrayDialect() {
super();
this.registerColumnType(Types.ARRAY, "array");
}
}
| vladmihalcea/high-performance-java-persistence | core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/type/array/PostgreSQL95ArrayDialect.java | Java | apache-2.0 | 355 |
package grammar.model.nouns;
import grammar.model.Multiplicity;
import grammar.model.PseudoEnum;
import grammar.model.SubjectGender;
import grammar.util.Utilities;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Noun implements PseudoEnum<Noun> {
private static final Map<String, Noun> INSTANCE_MAP = new HashMap<String, Noun>();
private static final Set<Noun> INSTANCES = new HashSet<Noun>();
private static int sequenceGenerator = 0;
private final int sequence;
private final Map<NounClass, Map<Multiplicity, NounForm>> formMap = new HashMap<NounClass, Map<Multiplicity, NounForm>>();
private final Set<NounForm> formSet;
private final Set<NounTag> classifications;
public Noun(Set<NounForm> forms, Set<NounTag> classifications) {
for (NounForm form : forms) {
for (NounClass nc : form.getNounClasses()) {
Map<Multiplicity, NounForm> ms = Utilities.initialiseIfReqd(nc, formMap);
ms.put(form.getMultiplicity(), form);
}
form.setNoun(this);
}
sequence = sequenceGenerator++;
this.formSet = forms;
this.classifications = classifications;
INSTANCE_MAP.put(toString(), this);
INSTANCES.add(this);
}
public Set<NounForm> getForms() {
return formSet;
}
public boolean isRegular() {
for (NounForm form : formSet) {
if (!form.isRegular())
return false;
}
return true;
}
public int ordinal() {
return sequence;
}
public int compareTo(Noun o) {
return ordinal() - o.ordinal();
}
public static Noun[] values() {
return INSTANCES.toArray(new Noun[]{});
}
public static Noun valueOf(String key) {
Noun m = INSTANCE_MAP.get(key);
if (m == null)
throw new IllegalArgumentException("No such Noun: '"+key+"'.");
return m;
}
public String getText(SubjectGender subjectGender, Multiplicity multiplicity) {
NounClass nc = mapSubjectGenderToNounClass(subjectGender);
Map<Multiplicity, NounForm> multiplicities = formMap.get(nc);
if (multiplicities == null)
multiplicities = formMap.values().iterator().next();
NounForm form = multiplicities.get(multiplicity);
if (form != null)
return form.getText();
if (multiplicity.equals(Multiplicity.PLURAL)) {
form = multiplicities.get(Multiplicity.SINGULAR);
return form + (form.getText().endsWith("s") ? "es" : "s"); // TODO this should come from some xml somewhere...
}
else // singular requested; only a plural form exists
throw new IllegalArgumentException("No singular form exists for noun "+getText(subjectGender, Multiplicity.PLURAL)+".");
}
public String toString() {
try {
return getText(SubjectGender.MASCULINE, Multiplicity.SINGULAR);
}
catch (IllegalArgumentException iae) {
return getText(SubjectGender.MASCULINE, Multiplicity.PLURAL);
}
}
public NounClass getNounClass(SubjectGender subjectGender) {
NounClass nc = mapSubjectGenderToNounClass(subjectGender);
if (formMap.keySet().contains(nc))
return nc;
return formMap.keySet().iterator().next();
}
private static NounClass mapSubjectGenderToNounClass(SubjectGender subjectGender) {
NounClass nc;
if (subjectGender.equals(SubjectGender.MASCULINE)) // TODO mapping is specific to french...
nc = NounClass.valueOf("MASCULINE");
else if (subjectGender.equals(SubjectGender.FEMININE))
nc = NounClass.valueOf("FEMININE");
else
nc = null;
return nc;
}
public Set<NounTag> getClassifications() {
return classifications;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + sequence;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Noun))
return false;
final Noun other = (Noun) obj;
if (sequence != other.sequence)
return false;
return true;
}
} | dliroberts/lang | RomanceConjugator/src/main/java/grammar/model/nouns/Noun.java | Java | apache-2.0 | 3,873 |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.route53domains.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53domains-2014-05-15/EnableDomainAutoRenew"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EnableDomainAutoRenewResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof EnableDomainAutoRenewResult == false)
return false;
EnableDomainAutoRenewResult other = (EnableDomainAutoRenewResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public EnableDomainAutoRenewResult clone() {
try {
return (EnableDomainAutoRenewResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| dagnir/aws-sdk-java | aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53domains/model/EnableDomainAutoRenewResult.java | Java | apache-2.0 | 2,301 |
/*
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2007 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.powermock.api.mockito.repackaged.asm.tree;
import org.powermock.api.mockito.repackaged.asm.AnnotationVisitor;
import org.powermock.api.mockito.repackaged.asm.Attribute;
import org.powermock.api.mockito.repackaged.asm.ClassVisitor;
import org.powermock.api.mockito.repackaged.asm.Label;
import org.powermock.api.mockito.repackaged.asm.MethodVisitor;
import org.powermock.api.mockito.repackaged.asm.Opcodes;
import org.powermock.api.mockito.repackaged.asm.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A node that represents a method.
*
* @author Eric Bruneton
*/
public class MethodNode extends MemberNode implements MethodVisitor {
/**
* The method's access flags (see {@link Opcodes}). This field also
* indicates if the method is synthetic and/or deprecated.
*/
public int access;
/**
* The method's name.
*/
public String name;
/**
* The method's descriptor (see {@link Type}).
*/
public String desc;
/**
* The method's signature. May be <tt>null</tt>.
*/
public String signature;
/**
* The internal names of the method's exception classes (see
* {@link Type#getInternalName() getInternalName}). This list is a list of
* {@link String} objects.
*/
public List exceptions;
/**
* The default value of this annotation interface method. This field must be
* a {@link Byte}, {@link Boolean}, {@link Character}, {@link Short},
* {@link Integer}, {@link Long}, {@link Float}, {@link Double},
* {@link String} or {@link Type}, or an two elements String array (for
* enumeration values), a {@link AnnotationNode}, or a {@link List} of
* values of one of the preceding types. May be <tt>null</tt>.
*/
public Object annotationDefault;
/**
* The runtime visible parameter annotations of this method. These lists are
* lists of {@link AnnotationNode} objects. May be <tt>null</tt>.
*
* @associates org.powermock.api.mockito.repackaged.asm.tree.AnnotationNode
* @label invisible parameters
*/
public List[] visibleParameterAnnotations;
/**
* The runtime invisible parameter annotations of this method. These lists
* are lists of {@link AnnotationNode} objects. May be <tt>null</tt>.
*
* @associates org.powermock.api.mockito.repackaged.asm.tree.AnnotationNode
* @label visible parameters
*/
public List[] invisibleParameterAnnotations;
/**
* The instructions of this method. This list is a list of
* {@link AbstractInsnNode} objects.
*
* @associates org.powermock.api.mockito.repackaged.asm.tree.AbstractInsnNode
* @label instructions
*/
public InsnList instructions;
/**
* The try catch blocks of this method. This list is a list of
* {@link TryCatchBlockNode} objects.
*
* @associates org.powermock.api.mockito.repackaged.asm.tree.TryCatchBlockNode
*/
public List tryCatchBlocks;
/**
* The maximum stack size of this method.
*/
public int maxStack;
/**
* The maximum number of local variables of this method.
*/
public int maxLocals;
/**
* The local variables of this method. This list is a list of
* {@link LocalVariableNode} objects. May be <tt>null</tt>
*
* @associates org.powermock.api.mockito.repackaged.asm.tree.LocalVariableNode
*/
public List localVariables;
/**
* Constructs an unitialized .
*/
public MethodNode() {
this.instructions = new InsnList();
}
/**
* Constructs a new .
*
* @param access the method's access flags (see {@link Opcodes}). This
* parameter also indicates if the method is synthetic and/or
* deprecated.
* @param name the method's name.
* @param desc the method's descriptor (see {@link Type}).
* @param signature the method's signature. May be <tt>null</tt>.
* @param exceptions the internal names of the method's exception classes
* (see {@link Type#getInternalName() getInternalName}). May be
* <tt>null</tt>.
*/
public MethodNode(
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions)
{
this();
this.access = access;
this.name = name;
this.desc = desc;
this.signature = signature;
this.exceptions = new ArrayList(exceptions == null
? 0
: exceptions.length);
boolean isAbstract = (access & Opcodes.ACC_ABSTRACT) != 0;
if (!isAbstract) {
this.localVariables = new ArrayList(5);
}
this.tryCatchBlocks = new ArrayList();
if (exceptions != null) {
this.exceptions.addAll(Arrays.asList(exceptions));
}
}
// ------------------------------------------------------------------------
// Implementation of the MethodVisitor interface
// ------------------------------------------------------------------------
public AnnotationVisitor visitAnnotationDefault() {
return new AnnotationNode(new ArrayList(0) {
public boolean add(final Object o) {
annotationDefault = o;
return super.add(o);
}
});
}
public AnnotationVisitor visitParameterAnnotation(
final int parameter,
final String desc,
final boolean visible)
{
AnnotationNode an = new AnnotationNode(desc);
if (visible) {
if (visibleParameterAnnotations == null) {
int params = Type.getArgumentTypes(this.desc).length;
visibleParameterAnnotations = new List[params];
}
if (visibleParameterAnnotations[parameter] == null) {
visibleParameterAnnotations[parameter] = new ArrayList(1);
}
visibleParameterAnnotations[parameter].add(an);
} else {
if (invisibleParameterAnnotations == null) {
int params = Type.getArgumentTypes(this.desc).length;
invisibleParameterAnnotations = new List[params];
}
if (invisibleParameterAnnotations[parameter] == null) {
invisibleParameterAnnotations[parameter] = new ArrayList(1);
}
invisibleParameterAnnotations[parameter].add(an);
}
return an;
}
public void visitCode() {
}
public void visitFrame(
final int type,
final int nLocal,
final Object[] local,
final int nStack,
final Object[] stack)
{
instructions.add(new FrameNode(type, nLocal, local == null
? null
: getLabelNodes(local), nStack, stack == null
? null
: getLabelNodes(stack)));
}
public void visitInsn(final int opcode) {
instructions.add(new InsnNode(opcode));
}
public void visitIntInsn(final int opcode, final int operand) {
instructions.add(new IntInsnNode(opcode, operand));
}
public void visitVarInsn(final int opcode, final int var) {
instructions.add(new VarInsnNode(opcode, var));
}
public void visitTypeInsn(final int opcode, final String type) {
instructions.add(new TypeInsnNode(opcode, type));
}
public void visitFieldInsn(
final int opcode,
final String owner,
final String name,
final String desc)
{
instructions.add(new FieldInsnNode(opcode, owner, name, desc));
}
public void visitMethodInsn(
final int opcode,
final String owner,
final String name,
final String desc)
{
instructions.add(new MethodInsnNode(opcode, owner, name, desc));
}
public void visitJumpInsn(final int opcode, final Label label) {
instructions.add(new JumpInsnNode(opcode, getLabelNode(label)));
}
public void visitLabel(final Label label) {
instructions.add(getLabelNode(label));
}
public void visitLdcInsn(final Object cst) {
instructions.add(new LdcInsnNode(cst));
}
public void visitIincInsn(final int var, final int increment) {
instructions.add(new IincInsnNode(var, increment));
}
public void visitTableSwitchInsn(
final int min,
final int max,
final Label dflt,
final Label[] labels)
{
instructions.add(new TableSwitchInsnNode(min,
max,
getLabelNode(dflt),
getLabelNodes(labels)));
}
public void visitLookupSwitchInsn(
final Label dflt,
final int[] keys,
final Label[] labels)
{
instructions.add(new LookupSwitchInsnNode(getLabelNode(dflt),
keys,
getLabelNodes(labels)));
}
public void visitMultiANewArrayInsn(final String desc, final int dims) {
instructions.add(new MultiANewArrayInsnNode(desc, dims));
}
public void visitTryCatchBlock(
final Label start,
final Label end,
final Label handler,
final String type)
{
tryCatchBlocks.add(new TryCatchBlockNode(getLabelNode(start),
getLabelNode(end),
getLabelNode(handler),
type));
}
public void visitLocalVariable(
final String name,
final String desc,
final String signature,
final Label start,
final Label end,
final int index)
{
localVariables.add(new LocalVariableNode(name,
desc,
signature,
getLabelNode(start),
getLabelNode(end),
index));
}
public void visitLineNumber(final int line, final Label start) {
instructions.add(new LineNumberNode(line, getLabelNode(start)));
}
public void visitMaxs(final int maxStack, final int maxLocals) {
this.maxStack = maxStack;
this.maxLocals = maxLocals;
}
/**
* Returns the LabelNode corresponding to the given Label. Creates a new
* LabelNode if necessary. The default implementation of this method uses
* the {@link Label#info} field to store associations between labels and
* label nodes.
*
* @param l a Label.
* @return the LabelNode corresponding to l.
*/
protected LabelNode getLabelNode(final Label l) {
if (!(l.info instanceof LabelNode)) {
l.info = new LabelNode(l);
}
return (LabelNode) l.info;
}
private LabelNode[] getLabelNodes(final Label[] l) {
LabelNode[] nodes = new LabelNode[l.length];
for (int i = 0; i < l.length; ++i) {
nodes[i] = getLabelNode(l[i]);
}
return nodes;
}
private Object[] getLabelNodes(final Object[] objs) {
Object[] nodes = new Object[objs.length];
for (int i = 0; i < objs.length; ++i) {
Object o = objs[i];
if (o instanceof Label) {
o = getLabelNode((Label) o);
}
nodes[i] = o;
}
return nodes;
}
// ------------------------------------------------------------------------
// Accept method
// ------------------------------------------------------------------------
/**
* Makes the given class visitor visit this method.
*
* @param cv a class visitor.
*/
public void accept(final ClassVisitor cv) {
String[] exceptions = new String[this.exceptions.size()];
this.exceptions.toArray(exceptions);
MethodVisitor mv = cv.visitMethod(access,
name,
desc,
signature,
exceptions);
if (mv != null) {
accept(mv);
}
}
/**
* Makes the given method visitor visit this method.
*
* @param mv a method visitor.
*/
public void accept(final MethodVisitor mv) {
// visits the method attributes
int i, j, n;
if (annotationDefault != null) {
AnnotationVisitor av = mv.visitAnnotationDefault();
AnnotationNode.accept(av, null, annotationDefault);
if (av != null) {
av.visitEnd();
}
}
n = visibleAnnotations == null ? 0 : visibleAnnotations.size();
for (i = 0; i < n; ++i) {
AnnotationNode an = (AnnotationNode) visibleAnnotations.get(i);
an.accept(mv.visitAnnotation(an.desc, true));
}
n = invisibleAnnotations == null ? 0 : invisibleAnnotations.size();
for (i = 0; i < n; ++i) {
AnnotationNode an = (AnnotationNode) invisibleAnnotations.get(i);
an.accept(mv.visitAnnotation(an.desc, false));
}
n = visibleParameterAnnotations == null
? 0
: visibleParameterAnnotations.length;
for (i = 0; i < n; ++i) {
List l = visibleParameterAnnotations[i];
if (l == null) {
continue;
}
for (j = 0; j < l.size(); ++j) {
AnnotationNode an = (AnnotationNode) l.get(j);
an.accept(mv.visitParameterAnnotation(i, an.desc, true));
}
}
n = invisibleParameterAnnotations == null
? 0
: invisibleParameterAnnotations.length;
for (i = 0; i < n; ++i) {
List l = invisibleParameterAnnotations[i];
if (l == null) {
continue;
}
for (j = 0; j < l.size(); ++j) {
AnnotationNode an = (AnnotationNode) l.get(j);
an.accept(mv.visitParameterAnnotation(i, an.desc, false));
}
}
n = attrs == null ? 0 : attrs.size();
for (i = 0; i < n; ++i) {
mv.visitAttribute((Attribute) attrs.get(i));
}
// visits the method's code
if (instructions.size() > 0) {
mv.visitCode();
// visits try catch blocks
for (i = 0; i < tryCatchBlocks.size(); ++i) {
((TryCatchBlockNode) tryCatchBlocks.get(i)).accept(mv);
}
// visits instructions
instructions.accept(mv);
// visits local variables
n = localVariables == null ? 0 : localVariables.size();
for (i = 0; i < n; ++i) {
((LocalVariableNode) localVariables.get(i)).accept(mv);
}
// visits maxs
mv.visitMaxs(maxStack, maxLocals);
}
mv.visitEnd();
}
}
| gstamac/powermock | powermock-api/powermock-api-mockito2/src/main/java/org/powermock/api/mockito/repackaged/asm/tree/MethodNode.java | Java | apache-2.0 | 16,512 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator;
import com.facebook.airlift.log.Logger;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.BlockEncodingSerde;
import com.facebook.presto.execution.buffer.PagesSerdeFactory;
import com.facebook.presto.metadata.Split;
import com.facebook.presto.metadata.Split.SplitIdentifier;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.page.PagesSerde;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.collect.AbstractIterator;
import io.airlift.slice.InputStreamSliceInput;
import io.airlift.slice.OutputStreamSliceOutput;
import io.airlift.slice.SliceOutput;
import javax.inject.Inject;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static com.facebook.presto.spi.page.PagesSerdeUtil.readPages;
import static com.facebook.presto.spi.page.PagesSerdeUtil.writePages;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static java.nio.file.Files.newInputStream;
import static java.nio.file.Files.newOutputStream;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.util.Objects.requireNonNull;
import static java.util.UUID.randomUUID;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class FileFragmentResultCacheManager
implements FragmentResultCacheManager
{
private static final Logger log = Logger.get(FileFragmentResultCacheManager.class);
private final Path baseDirectory;
private final long maxInFlightBytes;
private final PagesSerde pagesSerde;
private final FragmentCacheStats fragmentCacheStats;
private final ExecutorService flushExecutor;
private final ExecutorService removalExecutor;
private final Cache<CacheKey, Path> cache;
// TODO: Decouple CacheKey by encoding PlanNode and SplitIdentifier separately so we don't have to keep too many objects in memory
@Inject
public FileFragmentResultCacheManager(
FileFragmentResultCacheConfig cacheConfig,
BlockEncodingSerde blockEncodingSerde,
FragmentCacheStats fragmentCacheStats,
ExecutorService flushExecutor,
ExecutorService removalExecutor)
{
requireNonNull(cacheConfig, "cacheConfig is null");
requireNonNull(blockEncodingSerde, "blockEncodingSerde is null");
this.baseDirectory = Paths.get(cacheConfig.getBaseDirectory());
this.maxInFlightBytes = cacheConfig.getMaxInFlightSize().toBytes();
this.pagesSerde = new PagesSerdeFactory(blockEncodingSerde, cacheConfig.isBlockEncodingCompressionEnabled()).createPagesSerde();
this.fragmentCacheStats = requireNonNull(fragmentCacheStats, "fragmentCacheStats is null");
this.flushExecutor = requireNonNull(flushExecutor, "flushExecutor is null");
this.removalExecutor = requireNonNull(removalExecutor, "removalExecutor is null");
this.cache = CacheBuilder.newBuilder()
.maximumSize(cacheConfig.getMaxCachedEntries())
.expireAfterAccess(cacheConfig.getCacheTtl().toMillis(), MILLISECONDS)
.removalListener(new CacheRemovalListener())
.recordStats()
.build();
File target = new File(baseDirectory.toUri());
if (!target.exists()) {
try {
Files.createDirectories(target.toPath());
}
catch (IOException e) {
throw new PrestoException(GENERIC_INTERNAL_ERROR, "cannot create cache directory " + target, e);
}
}
else {
File[] files = target.listFiles();
if (files == null) {
return;
}
this.removalExecutor.submit(() -> Arrays.stream(files).forEach(file -> {
try {
Files.delete(file.toPath());
}
catch (IOException e) {
// ignore
}
}));
}
}
@Override
public Future<?> put(String serializedPlan, Split split, List<Page> result)
{
CacheKey key = new CacheKey(serializedPlan, split.getSplitIdentifier());
long resultSize = getPagesSize(result);
if (fragmentCacheStats.getInFlightBytes() + resultSize > maxInFlightBytes || cache.getIfPresent(key) != null) {
return immediateFuture(null);
}
fragmentCacheStats.addInFlightBytes(resultSize);
Path path = baseDirectory.resolve(randomUUID().toString().replaceAll("-", "_"));
return flushExecutor.submit(() -> cachePages(key, path, result));
}
private static long getPagesSize(List<Page> pages)
{
return pages.stream()
.mapToLong(Page::getSizeInBytes)
.sum();
}
private void cachePages(CacheKey key, Path path, List<Page> pages)
{
// TODO: To support both memory and disk limit, we should check cache size before putting to cache and use written bytes as weight for cache
try {
Files.createFile(path);
try (SliceOutput output = new OutputStreamSliceOutput(newOutputStream(path, APPEND))) {
writePages(pagesSerde, output, pages.iterator());
cache.put(key, path);
}
catch (UncheckedIOException | IOException e) {
log.warn(e, "%s encountered an error while writing to path %s", Thread.currentThread().getName(), path);
tryDeleteFile(path);
}
}
catch (UncheckedIOException | IOException e) {
log.warn(e, "%s encountered an error while writing to path %s", Thread.currentThread().getName(), path);
tryDeleteFile(path);
}
finally {
fragmentCacheStats.addInFlightBytes(-getPagesSize(pages));
}
}
private static void tryDeleteFile(Path path)
{
try {
File file = new File(path.toUri());
if (file.exists()) {
Files.delete(file.toPath());
}
}
catch (IOException e) {
// ignore
}
}
@Override
public Optional<Iterator<Page>> get(String serializedPlan, Split split)
{
CacheKey key = new CacheKey(serializedPlan, split.getSplitIdentifier());
Path path = cache.getIfPresent(key);
if (path == null) {
fragmentCacheStats.incrementCacheMiss();
return Optional.empty();
}
try {
InputStream inputStream = newInputStream(path);
Iterator<Page> result = readPages(pagesSerde, new InputStreamSliceInput(inputStream));
fragmentCacheStats.incrementCacheHit();
return Optional.of(closeWhenExhausted(result, inputStream));
}
catch (UncheckedIOException | IOException e) {
// there might be a chance the file has been deleted. We would return cache miss in this case.
fragmentCacheStats.incrementCacheMiss();
return Optional.empty();
}
}
private static <T> Iterator<T> closeWhenExhausted(Iterator<T> iterator, Closeable resource)
{
requireNonNull(iterator, "iterator is null");
requireNonNull(resource, "resource is null");
return new AbstractIterator<T>()
{
@Override
protected T computeNext()
{
if (iterator.hasNext()) {
return iterator.next();
}
try {
resource.close();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
return endOfData();
}
};
}
public static class CacheKey
{
private final String serializedPlan;
private final SplitIdentifier splitIdentifier;
public CacheKey(String serializedPlan, SplitIdentifier splitIdentifier)
{
this.serializedPlan = requireNonNull(serializedPlan, "serializedPlan is null");
this.splitIdentifier = requireNonNull(splitIdentifier, "splitIdentifier is null");
}
public String getSerializedPlan()
{
return serializedPlan;
}
public SplitIdentifier getSplitIdentifier()
{
return splitIdentifier;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CacheKey cacheKey = (CacheKey) o;
return Objects.equals(serializedPlan, cacheKey.serializedPlan) &&
Objects.equals(splitIdentifier, cacheKey.splitIdentifier);
}
@Override
public int hashCode()
{
return Objects.hash(serializedPlan, splitIdentifier);
}
}
private class CacheRemovalListener
implements RemovalListener<CacheKey, Path>
{
@Override
public void onRemoval(RemovalNotification<CacheKey, Path> notification)
{
removalExecutor.submit(() -> tryDeleteFile(notification.getValue()));
}
}
}
| EvilMcJerkface/presto | presto-main/src/main/java/com/facebook/presto/operator/FileFragmentResultCacheManager.java | Java | apache-2.0 | 10,483 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.distributed.near;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.cache.store.CacheStoreAdapter;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.spi.discovery.DiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
* Test that persistent store is not used when loading invalidated entry from backup node.
*/
public class GridPartitionedBackupLoadSelfTest extends GridCommonAbstractTest {
/** */
private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
/** */
private static final int GRID_CNT = 3;
/** */
private final TestStore store = new TestStore();
/** */
private final AtomicInteger cnt = new AtomicInteger();
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
cfg.setDiscoverySpi(discoverySpi());
cfg.setCacheConfiguration(cacheConfiguration());
return cfg;
}
/**
* @return Discovery SPI.
*/
private DiscoverySpi discoverySpi() {
TcpDiscoverySpi spi = new TcpDiscoverySpi();
spi.setIpFinder(IP_FINDER);
return spi;
}
/**
* @return Cache configuration.
*/
@SuppressWarnings("unchecked")
private CacheConfiguration cacheConfiguration() {
CacheConfiguration cfg = defaultCacheConfiguration();
cfg.setCacheMode(PARTITIONED);
cfg.setBackups(1);
cfg.setCacheStoreFactory(singletonFactory(store));
cfg.setReadThrough(true);
cfg.setWriteThrough(true);
cfg.setLoadPreviousValue(true);
cfg.setWriteSynchronizationMode(FULL_SYNC);
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
startGridsMultiThreaded(GRID_CNT);
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
stopAllGrids();
}
/**
* @throws Exception If failed.
*/
public void testBackupLoad() throws Exception {
grid(0).cache(null).put(1, 1);
assert store.get(1) == 1;
for (int i = 0; i < GRID_CNT; i++) {
IgniteCache<Integer, Integer> cache = jcache(i);
if (grid(i).affinity(null).isBackup(grid(i).localNode(), 1)) {
assert cache.localPeek(1, CachePeekMode.ONHEAP) == 1;
jcache(i).localClear(1);
assert cache.localPeek(1, CachePeekMode.ONHEAP) == null;
// Store is called in putx method, so we reset counter here.
cnt.set(0);
assert cache.get(1) == 1;
assert cnt.get() == 0;
}
}
}
/**
* Test store.
*/
private class TestStore extends CacheStoreAdapter<Integer, Integer> {
/** */
private Map<Integer, Integer> map = new ConcurrentHashMap<>();
/** {@inheritDoc} */
@Override public Integer load(Integer key) {
cnt.incrementAndGet();
return null;
}
/** {@inheritDoc} */
@Override public void write(javax.cache.Cache.Entry<? extends Integer, ? extends Integer> e) {
map.put(e.getKey(), e.getValue());
}
/** {@inheritDoc} */
@Override public void delete(Object key) {
// No-op
}
/**
* @param key Key.
* @return Value.
*/
public Integer get(Integer key) {
return map.get(key);
}
}
} | nivanov/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/near/GridPartitionedBackupLoadSelfTest.java | Java | apache-2.0 | 5,117 |
package org.opencommercesearch.client.impl;
import java.util.Date;
/**
* Represents a sku's availability.
*
* @author rmerizalde
*/
public class Availability {
public enum Status {
InStock,
OutOfStock,
PermanentlyOutOfStock,
Backorderable,
Preorderable
}
private Status status;
private Long stockLevel;
private Long backorderLevel;
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Long getStockLevel() {
return stockLevel;
}
public void setStockLevel(Long stockLevel) {
this.stockLevel = stockLevel;
}
public Long getBackorderLevel() {
return backorderLevel;
}
public void setBackorderLevel(Long backorderLevel) {
this.backorderLevel = backorderLevel;
}
}
| madickson/opencommercesearch | opencommercesearch-sdk-java/src/main/java/org/opencommercesearch/client/impl/Availability.java | Java | apache-2.0 | 947 |
package org.usfirst.frc.team4453.robot.commands;
import org.usfirst.frc.team4453.library.Vision;
import org.usfirst.frc.team4453.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
*
*/
public class DriveWithCamera extends Command {
public DriveWithCamera() {
// Use requires() here to declare subsystem dependencies
requires(Robot.chassis);
}
// Called just before this Command runs the first time
protected void initialize() {
System.out.println("DriveWithCamera");
Robot.ahrs.zeroYaw();
Robot.chassis.setPidVel(0);
Robot.chassis.enableChassisPID();
Robot.chassis.setAutoTurn(true);
}
// Called repeatedly when this Command is scheduled to run
// TODO: Figure out the 3d coordinant system, so we don't have to use the 2d coordinants, and so we can be camera independant.
protected void execute() {
double targetXPos = Vision.getTargetImgPosition("TheTarget").X;
double targetAngleOffset;
if(targetXPos == -99.0)
{
targetAngleOffset = 0;
}
else
{
double targetXOffset = Vision.getTargetImgPosition("TheTarget").X - (Vision.getFOVx()/2);
// Lots of trig, gets us the number of degrees we need to turn.
targetAngleOffset = Math.toDegrees(Math.atan(targetXOffset / ((Vision.getFOVx()/2) / Math.tan(Math.toRadians(Vision.getFOV()/2)))));
}
//Update the setpoint (does this work?);
double setpointAngle = Robot.ahrs.getYaw() + targetAngleOffset;
/*
if(setpointAngle > 180.0)
{
setpointAngle -= 360.0;
}
if(setpointAngle < -180.0)
{
setpointAngle += 360.0;
}
*/
SmartDashboard.putNumber("DriveWithCamera Output ", targetAngleOffset);
Robot.chassis.chassisSetSetpoint(setpointAngle);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return !Robot.chassis.getAutoTurn();
}
// Called once after isFinished returns true
protected void end() {
Robot.chassis.disableChassisPID();
Robot.chassis.setAutoTurn(false);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| RedHotChiliBots/FRC4453 | Robot/Programming/FRC2016Robot/src/org/usfirst/frc/team4453/robot/commands/DriveWithCamera.java | Java | apache-2.0 | 2,359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.