repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
SSEHUB/spassMeter | gearsBridgeJ/src/de/uni_hildesheim/sse/system/IThisProcessDataGatherer.java | 4927 | package de.uni_hildesheim.sse.system;
import de.uni_hildesheim.sse.codeEraser.annotations.Operation;
import de.uni_hildesheim.sse.codeEraser.annotations.Variability;
/**
* Defines an interface for requesting information on the current process, i.e.
* the JVM from the system.
*
* @author Holger Eichelberger
* @since 1.00
* @version 1.00
*/
@Variability(id = AnnotationConstants.VAR_CURRENT_PROCESS_DATA)
public interface IThisProcessDataGatherer {
/**
* Returns the identification the current process.
*
* @return the identification of the current process, may
* be <b>null</b> if invalid
*/
@Variability(id = AnnotationConstants.VAR_CURRENT_PROCESS_DATA )
public String getCurrentProcessID();
/**
* Returns the I/O statistics of the current process.
*
* @return the I/O statistics of the current process, may
* be <b>null</b> if invalid
*/
@Variability(id = { AnnotationConstants.VAR_CURRENT_PROCESS_DATA,
AnnotationConstants.VAR_IO_DATA }, op = Operation.AND)
public IoStatistics getCurrentProcessIo();
/**
* Returns weather native network I/O statistics are included, i.e.
* weather the system provides required capabilities to access the
* statistics.
*
* @param forAll query this information for all processes, or
* otherways for a single process
*
* @return <code>true</code> if the information is provided,
* <code>false</code> else
*
* @since 1.00
*/
@Variability(id = { AnnotationConstants.VAR_CURRENT_PROCESS_DATA,
AnnotationConstants.VAR_ALL_PROCESSES_DATA,
AnnotationConstants.VAR_IO_DATA }, op = Operation.AND)
public boolean isNetworkIoDataIncluded(boolean forAll);
/**
* Returns weather native file I/O statistics are included, i.e.
* weather the system provides required capabilities to access the
* statistics.
*
* @param forAll query this information for all processes, or
* otherways for a single process
*
* @return <code>true</code> if the information is provided,
* <code>false</code> else
*
* @since 1.00
*/
@Variability(id = { AnnotationConstants.VAR_CURRENT_PROCESS_DATA,
AnnotationConstants.VAR_ALL_PROCESSES_DATA,
AnnotationConstants.VAR_IO_DATA }, op = Operation.AND)
public boolean isFileIoDataIncluded(boolean forAll);
/**
* Returns the memory usage of the current process.
*
* @return the memory usage of the current process in bytes, zero or
* negative if invalid
*/
@Variability(id = { AnnotationConstants.VAR_CURRENT_PROCESS_DATA,
AnnotationConstants.VAR_MEMORY_DATA }, op = Operation.AND)
public long getCurrentProcessMemoryUse();
/**
* Returns the CPU user time ticks of the current process.
*
* @return the CPU user time ticks of the current process in nano seconds,
* zero or negative if invalid
*/
@Variability(id = { AnnotationConstants.VAR_CURRENT_PROCESS_DATA,
AnnotationConstants.VAR_TIME_DATA }, op = Operation.AND)
public long getCurrentProcessUserTimeTicks();
/**
* Returns the CPU kernel time ticks of the current process.
*
* @return the CPU kernel time ticks of the current process in nano
* seconds, zero or negative if invalid
*/
@Variability(id = { AnnotationConstants.VAR_CURRENT_PROCESS_DATA,
AnnotationConstants.VAR_TIME_DATA }, op = Operation.AND)
public long getCurrentProcessKernelTimeTicks();
/**
* Returns the system time ticks of the current process.
*
* @return the system time ticks of the current process in nano seconds,
* zero or negative if invalid
*/
@Variability(id = { AnnotationConstants.VAR_CURRENT_PROCESS_DATA,
AnnotationConstants.VAR_TIME_DATA }, op = Operation.AND)
public long getCurrentProcessSystemTimeTicks();
/**
* Returns the load produced by the current process.
*
* @return the load produced by the current process in percent, zero or
* negative if invalid
*/
@Variability(id = { AnnotationConstants.VAR_CURRENT_PROCESS_DATA,
AnnotationConstants.VAR_LOAD_DATA }, op = Operation.AND)
public double getCurrentProcessProcessorLoad();
/**
* Returns the I/O statistics for all currently running processes.
*
* @return the I/O statistics for all processes, may
* be <b>null</b> if invalid
*/
@Variability(id = { AnnotationConstants.VAR_ALL_PROCESSES_DATA,
AnnotationConstants.VAR_IO_DATA }, op = Operation.AND)
public IoStatistics getAllProcessesIo();
} | apache-2.0 |
trask/glowroot | build/error-prone-jdk6/src/main/java/com/google/errorprone/annotations/Immutable.java | 389 | package com.google.errorprone.annotations;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target(TYPE)
@Retention(RUNTIME)
@Inherited
public @interface Immutable {
String[] containerOf() default {};
}
| apache-2.0 |
inbloom/secure-data-service | sli/domain/src/test/java/org/slc/sli/validation/strategy/StringBlacklistStrategyTest.java | 3704 | /*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.slc.sli.validation.strategy;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* JUnits for StringBlacklistStrategy
* @author vmcglaughlin
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext-test.xml" })
public class StringBlacklistStrategyTest {
// trailing and leading spaces required to match word boundaries
private static final String PREFIX = "some chars ";
private static final String SUFFIX = " and other chars";
@Autowired
private AbstractBlacklistStrategy stringBlacklistStrategy;
@Autowired
private AbstractBlacklistStrategy relaxedStringBlacklistStrategy;
@Test
public void testRelaxedBlacklisting() {
List<String> badStringList = createBadRelaxedStringList();
runTestLoop(badStringList, relaxedStringBlacklistStrategy, false);
List<String> goodStringList = createGoodStringList();
runTestLoop(goodStringList, relaxedStringBlacklistStrategy, true);
}
@Test
public void testBlacklisting() {
List<String> badStringList = createBadStringList();
runTestLoop(badStringList, stringBlacklistStrategy, false);
List<String> goodStringList = createGoodStringList();
runTestLoop(goodStringList, stringBlacklistStrategy, true);
}
private void runTestLoop(List<String> inputList, AbstractBlacklistStrategy strategy, boolean shouldPass) {
for (String s : inputList) {
String input = PREFIX + s + SUFFIX;
boolean isValid = strategy.isValid("StringBlacklistStrategyTest", input);
if (shouldPass) {
assertTrue("Valid string did not pass validation: " + s, isValid);
} else {
assertFalse("Invalid string passed validation: " + s, isValid);
}
}
}
private List<String> createBadStringList() {
List<String> stringList = new ArrayList<String>();
stringList.add("script");
stringList.add("img");
stringList.add("src");
stringList.add("FSCommand =");
stringList.add("FSCommand=");
return stringList;
}
private List<String> createBadRelaxedStringList() {
List<String> stringList = new ArrayList<String>();
stringList.add("<script");
stringList.add("<iframe");
stringList.add("<frame");
return stringList;
}
private List<String> createGoodStringList() {
List<String> stringList = new ArrayList<String>();
stringList.add("innocuous");
stringList.add("list");
stringList.add("of");
stringList.add("strings");
stringList.add("FSCommand");
return stringList;
}
}
| apache-2.0 |
kantega/Flyt-cms | modules/core/src/main/java/no/kantega/publishing/common/data/TemplateConfiguration.java | 2533 | /*
* Copyright 2009 Kantega AS
*
* 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 no.kantega.publishing.common.data;
import no.kantega.publishing.api.model.Site;
import java.util.ArrayList;
import java.util.List;
/**
* Object containing the current Template configuration
*/
public class TemplateConfiguration {
List<Site> sites = new ArrayList<>();
List<AssociationCategory> associationCategories = new ArrayList<>();
List<DocumentType> documentTypes = new ArrayList<>();
List<ContentTemplate> contentTemplates = new ArrayList<>();
List<ContentTemplate> metadataTemplates = new ArrayList<>();
List<DisplayTemplate> displayTemplates = new ArrayList<>();
public List<Site> getSites() {
return sites;
}
public void setSites(List<Site> sites) {
this.sites = sites;
}
public List<AssociationCategory> getAssociationCategories() {
return associationCategories;
}
public void setAssociationCategories(List<AssociationCategory> associationCategories) {
this.associationCategories = associationCategories;
}
public List<DocumentType> getDocumentTypes() {
return documentTypes;
}
public void setDocumentTypes(List<DocumentType> documentTypes) {
this.documentTypes = documentTypes;
}
public List<ContentTemplate> getContentTemplates() {
return contentTemplates;
}
public void setContentTemplates(List<ContentTemplate> contentTemplates) {
this.contentTemplates = contentTemplates;
}
public List<DisplayTemplate> getDisplayTemplates() {
return displayTemplates;
}
public void setDisplayTemplates(List<DisplayTemplate> displayTemplates) {
this.displayTemplates = displayTemplates;
}
public List<ContentTemplate> getMetadataTemplates() {
return metadataTemplates;
}
public void setMetadataTemplates(List<ContentTemplate> metadataTemplates) {
this.metadataTemplates = metadataTemplates;
}
}
| apache-2.0 |
thongdv/OEPv2 | portlets/oep-core-dossiermgt-portlet/docroot/WEB-INF/service/org/oep/core/dossiermgt/model/PaymentRequestWrapper.java | 13540 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package org.oep.core.dossiermgt.model;
import com.liferay.portal.kernel.lar.StagedModelType;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.ModelWrapper;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* This class is a wrapper for {@link PaymentRequest}.
* </p>
*
* @author trungdk
* @see PaymentRequest
* @generated
*/
public class PaymentRequestWrapper implements PaymentRequest,
ModelWrapper<PaymentRequest> {
public PaymentRequestWrapper(PaymentRequest paymentRequest) {
_paymentRequest = paymentRequest;
}
@Override
public Class<?> getModelClass() {
return PaymentRequest.class;
}
@Override
public String getModelClassName() {
return PaymentRequest.class.getName();
}
@Override
public Map<String, Object> getModelAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("uuid", getUuid());
attributes.put("paymentRequestId", getPaymentRequestId());
attributes.put("userId", getUserId());
attributes.put("groupId", getGroupId());
attributes.put("companyId", getCompanyId());
attributes.put("createDate", getCreateDate());
attributes.put("modifiedDate", getModifiedDate());
attributes.put("organizationId", getOrganizationId());
attributes.put("dossierId", getDossierId());
attributes.put("amount", getAmount());
attributes.put("note", getNote());
attributes.put("issueDate", getIssueDate());
attributes.put("paymentFileId", getPaymentFileId());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
String uuid = (String)attributes.get("uuid");
if (uuid != null) {
setUuid(uuid);
}
Long paymentRequestId = (Long)attributes.get("paymentRequestId");
if (paymentRequestId != null) {
setPaymentRequestId(paymentRequestId);
}
Long userId = (Long)attributes.get("userId");
if (userId != null) {
setUserId(userId);
}
Long groupId = (Long)attributes.get("groupId");
if (groupId != null) {
setGroupId(groupId);
}
Long companyId = (Long)attributes.get("companyId");
if (companyId != null) {
setCompanyId(companyId);
}
Date createDate = (Date)attributes.get("createDate");
if (createDate != null) {
setCreateDate(createDate);
}
Date modifiedDate = (Date)attributes.get("modifiedDate");
if (modifiedDate != null) {
setModifiedDate(modifiedDate);
}
Long organizationId = (Long)attributes.get("organizationId");
if (organizationId != null) {
setOrganizationId(organizationId);
}
Long dossierId = (Long)attributes.get("dossierId");
if (dossierId != null) {
setDossierId(dossierId);
}
Long amount = (Long)attributes.get("amount");
if (amount != null) {
setAmount(amount);
}
String note = (String)attributes.get("note");
if (note != null) {
setNote(note);
}
Date issueDate = (Date)attributes.get("issueDate");
if (issueDate != null) {
setIssueDate(issueDate);
}
Long paymentFileId = (Long)attributes.get("paymentFileId");
if (paymentFileId != null) {
setPaymentFileId(paymentFileId);
}
}
/**
* Returns the primary key of this payment request.
*
* @return the primary key of this payment request
*/
@Override
public long getPrimaryKey() {
return _paymentRequest.getPrimaryKey();
}
/**
* Sets the primary key of this payment request.
*
* @param primaryKey the primary key of this payment request
*/
@Override
public void setPrimaryKey(long primaryKey) {
_paymentRequest.setPrimaryKey(primaryKey);
}
/**
* Returns the uuid of this payment request.
*
* @return the uuid of this payment request
*/
@Override
public java.lang.String getUuid() {
return _paymentRequest.getUuid();
}
/**
* Sets the uuid of this payment request.
*
* @param uuid the uuid of this payment request
*/
@Override
public void setUuid(java.lang.String uuid) {
_paymentRequest.setUuid(uuid);
}
/**
* Returns the payment request ID of this payment request.
*
* @return the payment request ID of this payment request
*/
@Override
public long getPaymentRequestId() {
return _paymentRequest.getPaymentRequestId();
}
/**
* Sets the payment request ID of this payment request.
*
* @param paymentRequestId the payment request ID of this payment request
*/
@Override
public void setPaymentRequestId(long paymentRequestId) {
_paymentRequest.setPaymentRequestId(paymentRequestId);
}
/**
* Returns the user ID of this payment request.
*
* @return the user ID of this payment request
*/
@Override
public long getUserId() {
return _paymentRequest.getUserId();
}
/**
* Sets the user ID of this payment request.
*
* @param userId the user ID of this payment request
*/
@Override
public void setUserId(long userId) {
_paymentRequest.setUserId(userId);
}
/**
* Returns the user uuid of this payment request.
*
* @return the user uuid of this payment request
* @throws SystemException if a system exception occurred
*/
@Override
public java.lang.String getUserUuid()
throws com.liferay.portal.kernel.exception.SystemException {
return _paymentRequest.getUserUuid();
}
/**
* Sets the user uuid of this payment request.
*
* @param userUuid the user uuid of this payment request
*/
@Override
public void setUserUuid(java.lang.String userUuid) {
_paymentRequest.setUserUuid(userUuid);
}
/**
* Returns the group ID of this payment request.
*
* @return the group ID of this payment request
*/
@Override
public long getGroupId() {
return _paymentRequest.getGroupId();
}
/**
* Sets the group ID of this payment request.
*
* @param groupId the group ID of this payment request
*/
@Override
public void setGroupId(long groupId) {
_paymentRequest.setGroupId(groupId);
}
/**
* Returns the company ID of this payment request.
*
* @return the company ID of this payment request
*/
@Override
public long getCompanyId() {
return _paymentRequest.getCompanyId();
}
/**
* Sets the company ID of this payment request.
*
* @param companyId the company ID of this payment request
*/
@Override
public void setCompanyId(long companyId) {
_paymentRequest.setCompanyId(companyId);
}
/**
* Returns the create date of this payment request.
*
* @return the create date of this payment request
*/
@Override
public java.util.Date getCreateDate() {
return _paymentRequest.getCreateDate();
}
/**
* Sets the create date of this payment request.
*
* @param createDate the create date of this payment request
*/
@Override
public void setCreateDate(java.util.Date createDate) {
_paymentRequest.setCreateDate(createDate);
}
/**
* Returns the modified date of this payment request.
*
* @return the modified date of this payment request
*/
@Override
public java.util.Date getModifiedDate() {
return _paymentRequest.getModifiedDate();
}
/**
* Sets the modified date of this payment request.
*
* @param modifiedDate the modified date of this payment request
*/
@Override
public void setModifiedDate(java.util.Date modifiedDate) {
_paymentRequest.setModifiedDate(modifiedDate);
}
/**
* Returns the organization ID of this payment request.
*
* @return the organization ID of this payment request
*/
@Override
public long getOrganizationId() {
return _paymentRequest.getOrganizationId();
}
/**
* Sets the organization ID of this payment request.
*
* @param organizationId the organization ID of this payment request
*/
@Override
public void setOrganizationId(long organizationId) {
_paymentRequest.setOrganizationId(organizationId);
}
/**
* Returns the dossier ID of this payment request.
*
* @return the dossier ID of this payment request
*/
@Override
public long getDossierId() {
return _paymentRequest.getDossierId();
}
/**
* Sets the dossier ID of this payment request.
*
* @param dossierId the dossier ID of this payment request
*/
@Override
public void setDossierId(long dossierId) {
_paymentRequest.setDossierId(dossierId);
}
/**
* Returns the amount of this payment request.
*
* @return the amount of this payment request
*/
@Override
public long getAmount() {
return _paymentRequest.getAmount();
}
/**
* Sets the amount of this payment request.
*
* @param amount the amount of this payment request
*/
@Override
public void setAmount(long amount) {
_paymentRequest.setAmount(amount);
}
/**
* Returns the note of this payment request.
*
* @return the note of this payment request
*/
@Override
public java.lang.String getNote() {
return _paymentRequest.getNote();
}
/**
* Sets the note of this payment request.
*
* @param note the note of this payment request
*/
@Override
public void setNote(java.lang.String note) {
_paymentRequest.setNote(note);
}
/**
* Returns the issue date of this payment request.
*
* @return the issue date of this payment request
*/
@Override
public java.util.Date getIssueDate() {
return _paymentRequest.getIssueDate();
}
/**
* Sets the issue date of this payment request.
*
* @param issueDate the issue date of this payment request
*/
@Override
public void setIssueDate(java.util.Date issueDate) {
_paymentRequest.setIssueDate(issueDate);
}
/**
* Returns the payment file ID of this payment request.
*
* @return the payment file ID of this payment request
*/
@Override
public long getPaymentFileId() {
return _paymentRequest.getPaymentFileId();
}
/**
* Sets the payment file ID of this payment request.
*
* @param paymentFileId the payment file ID of this payment request
*/
@Override
public void setPaymentFileId(long paymentFileId) {
_paymentRequest.setPaymentFileId(paymentFileId);
}
@Override
public boolean isNew() {
return _paymentRequest.isNew();
}
@Override
public void setNew(boolean n) {
_paymentRequest.setNew(n);
}
@Override
public boolean isCachedModel() {
return _paymentRequest.isCachedModel();
}
@Override
public void setCachedModel(boolean cachedModel) {
_paymentRequest.setCachedModel(cachedModel);
}
@Override
public boolean isEscapedModel() {
return _paymentRequest.isEscapedModel();
}
@Override
public java.io.Serializable getPrimaryKeyObj() {
return _paymentRequest.getPrimaryKeyObj();
}
@Override
public void setPrimaryKeyObj(java.io.Serializable primaryKeyObj) {
_paymentRequest.setPrimaryKeyObj(primaryKeyObj);
}
@Override
public com.liferay.portlet.expando.model.ExpandoBridge getExpandoBridge() {
return _paymentRequest.getExpandoBridge();
}
@Override
public void setExpandoBridgeAttributes(
com.liferay.portal.model.BaseModel<?> baseModel) {
_paymentRequest.setExpandoBridgeAttributes(baseModel);
}
@Override
public void setExpandoBridgeAttributes(
com.liferay.portlet.expando.model.ExpandoBridge expandoBridge) {
_paymentRequest.setExpandoBridgeAttributes(expandoBridge);
}
@Override
public void setExpandoBridgeAttributes(
com.liferay.portal.service.ServiceContext serviceContext) {
_paymentRequest.setExpandoBridgeAttributes(serviceContext);
}
@Override
public java.lang.Object clone() {
return new PaymentRequestWrapper((PaymentRequest)_paymentRequest.clone());
}
@Override
public int compareTo(PaymentRequest paymentRequest) {
return _paymentRequest.compareTo(paymentRequest);
}
@Override
public int hashCode() {
return _paymentRequest.hashCode();
}
@Override
public com.liferay.portal.model.CacheModel<PaymentRequest> toCacheModel() {
return _paymentRequest.toCacheModel();
}
@Override
public PaymentRequest toEscapedModel() {
return new PaymentRequestWrapper(_paymentRequest.toEscapedModel());
}
@Override
public PaymentRequest toUnescapedModel() {
return new PaymentRequestWrapper(_paymentRequest.toUnescapedModel());
}
@Override
public java.lang.String toString() {
return _paymentRequest.toString();
}
@Override
public java.lang.String toXmlString() {
return _paymentRequest.toXmlString();
}
@Override
public void persist()
throws com.liferay.portal.kernel.exception.SystemException {
_paymentRequest.persist();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof PaymentRequestWrapper)) {
return false;
}
PaymentRequestWrapper paymentRequestWrapper = (PaymentRequestWrapper)obj;
if (Validator.equals(_paymentRequest,
paymentRequestWrapper._paymentRequest)) {
return true;
}
return false;
}
@Override
public StagedModelType getStagedModelType() {
return _paymentRequest.getStagedModelType();
}
/**
* @deprecated As of 6.1.0, replaced by {@link #getWrappedModel}
*/
public PaymentRequest getWrappedPaymentRequest() {
return _paymentRequest;
}
@Override
public PaymentRequest getWrappedModel() {
return _paymentRequest;
}
@Override
public void resetOriginalValues() {
_paymentRequest.resetOriginalValues();
}
private PaymentRequest _paymentRequest;
} | apache-2.0 |
xLeitix/jcloudscale | ext/DataStoreLib/src/main/java/at/ac/tuwien/infosys/jcloudscale/datastore/mapping/Preconditions.java | 1339 | /*
Copyright 2013 Rene Nowak
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package at.ac.tuwien.infosys.jcloudscale.datastore.mapping;
public final class Preconditions {
//Hide Constructor
private Preconditions(){}
/**
* Verify that the given object is not null otherwise and exception is thrown
*
* @param object the given object
*/
public static void notNull(Object object) {
if(object == null) {
throw new NullPointerException("Object " + object + " is null.");
}
}
/**
* Verify that the given objects are not null otherwise an exception is thrown
*
* @param objects the given objects
*/
public static void notNull(Object... objects) {
for(Object object : objects) {
notNull(object);
}
}
}
| apache-2.0 |
boneman1231/org.apache.felix | trunk/ipojo/core/src/main/java/org/apache/felix/ipojo/handlers/providedservice/ProvidedService.java | 39685 | /*
* 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.ipojo.handlers.providedservice;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.ConfigurationException;
import org.apache.felix.ipojo.IPOJOServiceFactory;
import org.apache.felix.ipojo.InstanceManager;
import org.apache.felix.ipojo.util.Callback;
import org.apache.felix.ipojo.util.Property;
import org.apache.felix.ipojo.util.SecurityHelper;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationAdmin;
/**
* Provided Service represent a provided service by the component.
*
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class ProvidedService implements ServiceFactory {
/**
* Service State : REGISTRED.
*/
public static final int REGISTERED = 1;
/**
* Service State : UNREGISTRED.
*/
public static final int UNREGISTERED = 0;
/**
* Factory Policy : SINGLETON_FACTORY.
*/
public static final int SINGLETON_STRATEGY = 0;
/**
* Factory policy : SERVICE_FACTORY.
*/
public static final int SERVICE_STRATEGY = 1;
/**
* Factory policy : STATIC_FACTORY.
*/
public static final int STATIC_STRATEGY = 2;
/**
* Factory policy : INSTANCE.
* Creates one service object per instance consuming the service.
*/
public static final int INSTANCE_STRATEGY = 3;
/**
* At this time, it is only the java interface full name.
*/
private String[] m_serviceSpecifications = new String[0];
/**
* The service registration. is null when the service is not registered.
* m_serviceRegistration : ServiceRegistration
*/
private ServiceRegistration m_serviceRegistration;
/**
* Link to the owner handler. m_handler : Provided Service Handler
*/
private ProvidedServiceHandler m_handler;
/**
* Properties Array.
*/
private Property[] m_properties;
/**
* Service Object creation policy.
*/
private CreationStrategy m_strategy;
/**
* Were the properties updated during the processing.
*/
private volatile boolean m_wasUpdated;
/**
* Service Controller.
*/
private Map /*<Specification, ServiceController>*/ m_controllers = new HashMap/*<Specification, ServiceController>*/();
/**
* Post-Registration callback.
*/
private Callback m_postRegistration;
/**
* Post-Unregistration callback.
*/
private Callback m_postUnregistration;
/**
* The published properties.
*/
private Dictionary m_publishedProperties = new Properties();
/**
* Creates a provided service object.
*
* @param handler the the provided service handler.
* @param specification the specifications provided by this provided service
* @param factoryPolicy the service providing policy
* @param creationStrategyClass the customized service object creation strategy.
* @param conf the instance configuration.
*/
public ProvidedService(ProvidedServiceHandler handler, String[] specification, int factoryPolicy, Class creationStrategyClass, Dictionary conf) {
m_handler = handler;
m_serviceSpecifications = specification;
// Add instance name, factory name and factory version is set.
try {
addProperty(new Property("instance.name", null, null, handler.getInstanceManager().getInstanceName(), String.class.getName(), handler.getInstanceManager(), handler));
addProperty(new Property("factory.name", null, null, handler.getInstanceManager().getFactory().getFactoryName(), String.class.getName(), handler.getInstanceManager(), handler));
if (handler.getInstanceManager().getFactory().getVersion() != null) {
addProperty(new Property("factory.version", null, null, handler.getInstanceManager().getFactory().getVersion(), String.class.getName(), handler.getInstanceManager(), handler));
}
// Add the service.* if defined
if (conf.get(Constants.SERVICE_PID) != null) {
addProperty(new Property(Constants.SERVICE_PID, null, null, (String) conf.get(Constants.SERVICE_PID), String.class.getName(), handler.getInstanceManager(), handler));
}
if (conf.get(Constants.SERVICE_RANKING) != null) {
addProperty(new Property(Constants.SERVICE_RANKING, null, null, (String) conf.get(Constants.SERVICE_RANKING), "int", handler.getInstanceManager(), handler));
}
if (conf.get(Constants.SERVICE_VENDOR) != null) {
addProperty(new Property(Constants.SERVICE_VENDOR, null, null, (String) conf.get(Constants.SERVICE_VENDOR), String.class.getName(), handler.getInstanceManager(), handler));
}
if (conf.get(Constants.SERVICE_DESCRIPTION) != null) {
addProperty(new Property(Constants.SERVICE_DESCRIPTION, null, null, (String) conf.get(Constants.SERVICE_DESCRIPTION), String.class.getName(), handler.getInstanceManager(), handler));
}
} catch (ConfigurationException e) {
m_handler.error("An exception occurs when adding instance.name and factory.name property : " + e.getMessage());
}
if (creationStrategyClass != null) {
try {
m_strategy = (CreationStrategy) creationStrategyClass.newInstance();
} catch (IllegalAccessException e) {
m_handler.error("["
+ m_handler.getInstanceManager().getInstanceName()
+ "] The customized service object creation policy "
+ "(" + creationStrategyClass.getName() + ") is not accessible: "
+ e.getMessage(), e);
getInstanceManager().stop();
return;
} catch (InstantiationException e) {
m_handler.error("["
+ m_handler.getInstanceManager().getInstanceName()
+ "] The customized service object creation policy "
+ "(" + creationStrategyClass.getName() + ") cannot be instantiated: "
+ e.getMessage(), e);
getInstanceManager().stop();
return;
}
} else {
switch (factoryPolicy) {
case SINGLETON_STRATEGY:
m_strategy = new SingletonStrategy();
break;
case SERVICE_STRATEGY:
case STATIC_STRATEGY:
// In this case, we need to try to create a new pojo object,
// the factory method will handle the creation.
m_strategy = new FactoryStrategy();
break;
case INSTANCE_STRATEGY:
m_strategy = new PerInstanceStrategy();
break;
// Other policies:
// Thread : one service object per asking thread
// Consumer : one service object per consumer
default:
List specs = Arrays.asList(m_serviceSpecifications);
m_handler.error("["
+ m_handler.getInstanceManager().getInstanceName()
+ "] Unknown creation policy for " + specs + " : "
+ factoryPolicy);
getInstanceManager().stop();
break;
}
}
}
/**
* Add properties to the provided service.
* @param props : the properties to attached to the service registration
*/
protected void setProperties(Property[] props) {
for (int i = 0; i < props.length; i++) {
addProperty(props[i]);
}
}
/**
* Add the given property to the property list.
*
* @param prop : the element to add
*/
private synchronized void addProperty(Property prop) {
for (int i = 0; (m_properties != null) && (i < m_properties.length); i++) {
if (m_properties[i] == prop) {
return;
}
}
if (m_properties == null) {
m_properties = new Property[] { prop };
} else {
Property[] newProp = new Property[m_properties.length + 1];
System.arraycopy(m_properties, 0, newProp, 0, m_properties.length);
newProp[m_properties.length] = prop;
m_properties = newProp;
}
}
/**
* Remove a property.
*
* @param name : the property to remove
* @return <code>true</code> if the property was removed,
* <code>false</code> otherwise.
*/
private synchronized boolean removeProperty(String name) {
int idx = -1;
for (int i = 0; i < m_properties.length; i++) {
if (m_properties[i].getName().equals(name)) {
idx = i;
break;
}
}
if (idx >= 0) {
if ((m_properties.length - 1) == 0) {
m_properties = null;
} else {
Property[] newPropertiesList = new Property[m_properties.length - 1];
System.arraycopy(m_properties, 0, newPropertiesList, 0, idx);
if (idx < newPropertiesList.length) {
System.arraycopy(m_properties, idx + 1, newPropertiesList, idx, newPropertiesList.length - idx);
}
m_properties = newPropertiesList;
}
return true;
} else {
return false;
}
}
/**
* Get the service reference of the service registration.
* @return the service reference of the provided service (null if the
* service is not published).
*/
public ServiceReference getServiceReference() {
if (m_serviceRegistration == null) {
return null;
} else {
return m_serviceRegistration.getReference();
}
}
/**
* Returns a service object for the dependency.
* @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration)
* @param bundle : the bundle
* @param registration : the service registration of the registered service
* @return a new service object or a already created service object (in the case of singleton) or <code>null</code>
* if the instance is no more valid.
*/
public Object getService(Bundle bundle, ServiceRegistration registration) {
if (getInstanceManager().getState() == InstanceManager.VALID) {
return m_strategy.getService(bundle, registration);
} else {
return null;
}
}
/**
* The unget method.
*
* @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle,
* org.osgi.framework.ServiceRegistration, java.lang.Object)
* @param bundle : bundle
* @param registration : service registration
* @param service : service object
*/
public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {
m_strategy.ungetService(bundle, registration, service);
}
/**
* Registers the service. The service object must be able to serve this
* service.
* This method also notifies the creation strategy of the publication.
*/
protected void registerService() {
ServiceRegistration reg = null;
Properties serviceProperties = null;
synchronized (this) {
if (m_serviceRegistration != null) {
return;
} else {
if (m_handler.getInstanceManager().getState() == ComponentInstance.VALID
&& m_serviceRegistration == null
&& isAtLeastAServiceControllerValid()) {
// Build the service properties list
BundleContext bc = m_handler.getInstanceManager().getContext();
// Security check
if (SecurityHelper.hasPermissionToRegisterServices(
m_serviceSpecifications, bc)) {
serviceProperties = getServiceProperties();
m_strategy.onPublication(getInstanceManager(),
getServiceSpecificationsToRegister(),
serviceProperties);
m_serviceRegistration = bc.registerService(
getServiceSpecificationsToRegister(), this,
(Dictionary) serviceProperties);
reg = m_serviceRegistration; // Stack confinement
} else {
throw new SecurityException("The bundle "
+ bc.getBundle().getBundleId()
+ " does not have the"
+ " permission to register the services "
+ Arrays.asList(m_serviceSpecifications));
}
}
}
}
// An update may happen during the registration, re-check and apply.
// This must be call outside the synchronized block.
if (reg != null && m_wasUpdated) {
Properties updated = getServiceProperties();
reg.setProperties((Dictionary) updated);
m_publishedProperties = updated;
m_wasUpdated = false;
}
synchronized (this) {
// Call the post-registration callback in the same thread holding
// the monitor lock.
// This allows to be sure that the callback is called once per
// registration.
// But the callback must take care to not create a deadlock
if (m_postRegistration != null) {
try {
m_postRegistration
.call(new Object[] { m_serviceRegistration
.getReference() });
} catch (Exception e) {
m_handler.error(
"Cannot invoke the post-registration callback "
+ m_postRegistration.getMethod(), e);
}
}
}
}
/**
* Unregisters the service.
*/
protected synchronized void unregisterService() {
// Create a copy of the service reference in the case we need
// to inject it to the post-unregistration callback.
ServiceReference ref = null;
if (m_serviceRegistration != null) {
ref = m_serviceRegistration.getReference();
m_serviceRegistration.unregister();
m_serviceRegistration = null;
}
m_strategy.onUnpublication();
// Call the post-unregistration callback in the same thread holding the monitor lock.
// This allows to be sure that the callback is called once per unregistration.
// But the callback must take care to not create a deadlock
if (m_postUnregistration != null && ref != null) {
try {
m_postUnregistration.call(new Object[] { ref });
} catch (Exception e) {
m_handler.error("Cannot invoke the post-unregistration callback " + m_postUnregistration.getMethod(), e);
}
}
}
/**
* Get the current provided service state.
* @return The state of the provided service.
*/
public int getState() {
if (m_serviceRegistration == null) {
return UNREGISTERED;
} else {
return REGISTERED;
}
}
protected InstanceManager getInstanceManager() {
return m_handler.getInstanceManager();
}
/**
* Return the list of properties attached to this service. This list
* contains only property where a value are assigned.
*
* @return the properties attached to the provided service.
*/
private Properties getServiceProperties() {
// Build the service properties list
Properties serviceProperties = new Properties();
for (int i = 0; i < m_properties.length; i++) {
Object value = m_properties[i].getValue();
if (value != null && value != Property.NO_VALUE) {
serviceProperties.put(m_properties[i].getName(), value);
}
}
return serviceProperties;
}
/**
* Get the list of properties attached to the service registration.
* @return the properties attached to the provided service.
*/
public Property[] getProperties() {
return m_properties;
}
/**
* Update the service properties. The new list of properties is sent to
* the service registry.
*/
public synchronized void update() {
// Update the service registration
if (m_serviceRegistration != null) {
Properties updated = getServiceProperties();
Dictionary oldProps = (Dictionary) ((Properties) m_publishedProperties).clone();
Dictionary newProps = (Dictionary) (updated.clone());
// Remove keys that must not be compared
newProps.remove("instance.name");
oldProps.remove("instance.name");
newProps.remove(Constants.SERVICE_ID);
oldProps.remove(Constants.SERVICE_ID);
newProps.remove(Constants.SERVICE_PID);
oldProps.remove(Constants.SERVICE_PID);
newProps.remove("factory.name");
oldProps.remove("factory.name");
newProps.remove(ConfigurationAdmin.SERVICE_FACTORYPID);
oldProps.remove(ConfigurationAdmin.SERVICE_FACTORYPID);
// Trigger the update only if the properties have changed.
// First check, are the size equals
if (oldProps.size() != newProps.size()) {
m_handler.info("Updating Registration : " + oldProps.size() + " / " + newProps.size());
m_publishedProperties = updated;
m_serviceRegistration.setProperties((Dictionary) updated);
} else {
// Check changes
Enumeration keys = oldProps.keys();
while (keys.hasMoreElements()) {
String k = (String) keys.nextElement();
Object val = oldProps.get(k);
if (! val.equals(updated.get(k))) {
m_handler.info("Updating Registration : " + k);
m_publishedProperties = updated;
m_serviceRegistration.setProperties((Dictionary) updated);
return;
}
}
}
} else {
// Need to be updated later.
m_wasUpdated = true;
}
}
/**
* Add properties to the list.
* @param props : properties to add
*/
protected void addProperties(Dictionary props) {
Enumeration keys = props.keys();
boolean updated = false;
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
Object value = props.get(key);
boolean alreadyExisting = false;
for (int i = 0; i < m_properties.length; i++) {
if (key.equals(m_properties[i].getName())) {
alreadyExisting = true;
// Check whether the value changed.
if (m_properties[i].getValue() == null
|| ! value.equals(m_properties[i].getValue())) {
m_properties[i].setValue(value);
updated = true;
}
}
}
if (! alreadyExisting) {
try {
Property prop = new Property(key, null, null, value.toString(), value.getClass().getName(), getInstanceManager(), m_handler);
addProperty(prop);
updated = true;
} catch (ConfigurationException e) {
m_handler.error("The propagated property " + key + " cannot be created correctly : " + e.getMessage());
}
}
}
if (updated) {
m_handler.info("Update triggered by adding properties " + props);
update();
}
}
/**
* Remove properties from the list.
* @param props : properties to remove
*/
protected void deleteProperties(Dictionary props) {
Enumeration keys = props.keys();
boolean mustUpdate = false;
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
mustUpdate = mustUpdate || removeProperty(key);
}
if (mustUpdate) {
m_handler.info("Update triggered when removing properties : " + props);
update();
}
}
/**
* Get the published service specifications.
* @return the list of provided service specifications (i.e. java
* interface).
*/
public String[] getServiceSpecifications() {
return m_serviceSpecifications;
}
/**
* Get the service registration.
* @return the service registration of this service.
*/
public ServiceRegistration getServiceRegistration() {
return m_serviceRegistration;
}
/**
* Sets the service controller on this provided service.
* @param field the field attached to this controller
* @param value the value the initial value
* @param specification the target specification, if <code>null</code>
* affect all specifications.
*/
public void setController(String field, boolean value, String specification) {
if (specification == null) {
m_controllers.put("ALL", new ServiceController(field, value));
} else {
m_controllers.put(specification, new ServiceController(field, value));
}
}
public ServiceController getController(String field) {
Collection controllers = m_controllers.values();
Iterator iterator = controllers.iterator();
while (iterator.hasNext()) {
ServiceController controller = (ServiceController) iterator.next();
if (field.equals(controller.m_field)) {
return controller;
}
}
return null;
}
public ServiceController getControllerBySpecification(String spec) {
return (ServiceController) m_controllers.get(spec);
}
/**
* Checks if at least one service controller is valid.
* @return <code>true</code> if one service controller at least
* is valid.
*/
private boolean isAtLeastAServiceControllerValid() {
Collection controllers = m_controllers.values();
// No controller
if (controllers.isEmpty()) {
return true;
}
Iterator iterator = controllers.iterator();
while (iterator.hasNext()) {
ServiceController controller = (ServiceController) iterator.next();
if (controller.getValue()) {
return true;
}
}
return false;
}
private String[] getServiceSpecificationsToRegister() {
if (m_controllers.isEmpty()) {
return m_serviceSpecifications;
}
ArrayList l = new ArrayList();
if (m_controllers.containsKey("ALL")) {
ServiceController ctrl = (ServiceController) m_controllers.get("ALL");
if (ctrl.m_value) {
l.addAll(Arrays.asList(m_serviceSpecifications));
}
}
Iterator iterator = m_controllers.keySet().iterator();
while (iterator.hasNext()) {
String spec = (String) iterator.next();
ServiceController ctrl = (ServiceController) m_controllers.get(spec);
if (ctrl.m_value) {
if (! "ALL".equals(spec)) { // Already added.
if (! l.contains(spec)) {
l.add(spec);
}
}
} else {
l.remove(spec);
}
}
return (String[]) l.toArray(new String[l.size()]);
}
public void setPostRegistrationCallback(Callback cb) {
m_postRegistration = cb;
}
public void setPostUnregistrationCallback(Callback cb) {
m_postUnregistration = cb;
}
/**
* Service Controller.
*/
class ServiceController {
/**
* The controller value.
*/
private boolean m_value;
/**
* The field attached to this controller.
*/
private final String m_field;
/**
* Creates a ServiceController.
* @param field the field
* @param value the initial value
*/
public ServiceController(String field, boolean value) {
m_field = field;
m_value = value;
}
public String getField() {
return m_field;
}
/**
* Gets the value.
* @return the value
*/
public boolean getValue() {
synchronized (ProvidedService.this) {
return m_value;
}
}
/**
* Sets the value.
* @param value the value
*/
public void setValue(Boolean value) {
synchronized (ProvidedService.this) {
if (value.booleanValue() != m_value) {
// If there is a change to the ServiceController value then
// we will
// need to modify the registrations.
m_value = value.booleanValue();
unregisterService();
if (getServiceSpecificationsToRegister().length != 0) {
registerService();
}
}
}
}
}
/**
* Singleton creation strategy.
* This strategy just creates one service object and
* returns always the same.
*/
private class SingletonStrategy extends CreationStrategy {
/**
* The service is going to be registered.
* @param instance the instance manager
* @param interfaces the published interfaces
* @param props the properties
* @see org.apache.felix.ipojo.handlers.providedservice.CreationStrategy#onPublication(InstanceManager, java.lang.String[], java.util.Properties)
*/
public void onPublication(InstanceManager instance, String[] interfaces,
Properties props) { }
/**
* The service was unpublished.
* @see org.apache.felix.ipojo.handlers.providedservice.CreationStrategy#onUnpublication()
*/
public void onUnpublication() { }
/**
* A service object is required.
* @param arg0 the bundle requiring the service object.
* @param arg1 the service registration.
* @return the first pojo object.
* @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration)
*/
public Object getService(Bundle arg0, ServiceRegistration arg1) {
return m_handler.getInstanceManager().getPojoObject();
}
/**
* A service object is released.
* @param arg0 the bundle
* @param arg1 the service registration
* @param arg2 the get service object.
* @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration, java.lang.Object)
*/
public void ungetService(Bundle arg0, ServiceRegistration arg1,
Object arg2) {
}
}
/**
* Service object creation policy following the OSGi Service Factory
* policy {@link ServiceFactory}.
*/
private class FactoryStrategy extends CreationStrategy {
/**
* The service is going to be registered.
* @param instance the instance manager
* @param interfaces the published interfaces
* @param props the properties
* @see org.apache.felix.ipojo.handlers.providedservice.CreationStrategy#onPublication(InstanceManager, java.lang.String[], java.util.Properties)
*/
public void onPublication(InstanceManager instance, String[] interfaces,
Properties props) { }
/**
* The service is unpublished.
* @see org.apache.felix.ipojo.handlers.providedservice.CreationStrategy#onUnpublication()
*/
public void onUnpublication() { }
/**
* OSGi Service Factory getService method.
* Returns a new service object per asking bundle.
* This object is then cached by the framework.
* @param arg0 the bundle requiring the service
* @param arg1 the service registration
* @return the service object for the asking bundle
* @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration)
*/
public Object getService(Bundle arg0, ServiceRegistration arg1) {
return m_handler.getInstanceManager().createPojoObject();
}
/**
* OSGi Service Factory unget method.
* Deletes the created object for the asking bundle.
* @param arg0 the asking bundle
* @param arg1 the service registration
* @param arg2 the created service object returned for this bundle
* @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration, java.lang.Object)
*/
public void ungetService(Bundle arg0, ServiceRegistration arg1,
Object arg2) {
m_handler.getInstanceManager().deletePojoObject(arg2);
}
}
/**
* Service object creation policy creating a service object per asking iPOJO component
* instance. This creation policy follows the iPOJO Service Factory interaction pattern
* and does no support 'direct' invocation.
*/
private class PerInstanceStrategy extends CreationStrategy implements IPOJOServiceFactory, InvocationHandler {
/**
* Map [ComponentInstance->ServiceObject] storing created service objects.
*/
private Map/*<ComponentInstance, ServiceObject>*/ m_instances = new HashMap();
/**
* A method is invoked on the proxy object.
* If the method is the {@link IPOJOServiceFactory#getService(ComponentInstance)}
* method, this method creates a service object if not already created for the asking
* component instance.
* If the method is {@link IPOJOServiceFactory#ungetService(ComponentInstance, Object)}
* the service object is unget (i.e. removed from the map and deleted).
* In all other cases, a {@link UnsupportedOperationException} is thrown as this policy
* requires to use the {@link IPOJOServiceFactory} interaction pattern.
* @param arg0 the proxy object
* @param arg1 the called method
* @param arg2 the arguments
* @return the service object attached to the asking instance for 'get',
* <code>null</code> for 'unget',
* a {@link UnsupportedOperationException} for all other methods.
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
*/
public Object invoke(Object arg0, Method arg1, Object[] arg2) {
if (isGetServiceMethod(arg1)) {
return getService((ComponentInstance) arg2[0]);
}
if (isUngetServiceMethod(arg1)) {
ungetService((ComponentInstance) arg2[0], arg2[1]);
return null;
}
// Regular methods from java.lang.Object : equals and hashCode
if (arg1.getName().equals("equals") && arg2 != null && arg2.length == 1) {
return this.equals(arg2[0]);
}
if (arg1.getName().equals("hashCode")) {
return this.hashCode();
}
throw new UnsupportedOperationException("This service requires an advanced creation policy. "
+ "Before calling the service, call the getService(ComponentInstance) method to get "
+ "the service object. - Method called: " + arg1.getName());
}
/**
* A service object is required.
* This policy returns a service object per asking instance.
* @param instance the instance requiring the service object
* @return the service object for this instance
* @see org.apache.felix.ipojo.IPOJOServiceFactory#getService(org.apache.felix.ipojo.ComponentInstance)
*/
public Object getService(ComponentInstance instance) {
Object obj = m_instances.get(instance);
if (obj == null) {
obj = m_handler.getInstanceManager().createPojoObject();
m_instances.put(instance, obj);
}
return obj;
}
/**
* A service object is unget.
* The service object is removed from the map and deleted.
* @param instance the instance releasing the service
* @param svcObject the service object
* @see org.apache.felix.ipojo.IPOJOServiceFactory#ungetService(org.apache.felix.ipojo.ComponentInstance, java.lang.Object)
*/
public void ungetService(ComponentInstance instance, Object svcObject) {
Object pojo = m_instances.remove(instance);
m_handler.getInstanceManager().deletePojoObject(pojo);
}
/**
* The service is going to be registered.
* @param instance the instance manager
* @param interfaces the published interfaces
* @param props the properties
* @see org.apache.felix.ipojo.handlers.providedservice.CreationStrategy#onPublication(InstanceManager, java.lang.String[], java.util.Properties)
*/
public void onPublication(InstanceManager instance, String[] interfaces,
Properties props) { }
/**
* The service is going to be unregistered.
* The instance map is cleared. Created object are disposed.
* @see org.apache.felix.ipojo.handlers.providedservice.CreationStrategy#onUnpublication()
*/
public void onUnpublication() {
Collection col = m_instances.values();
Iterator it = col.iterator();
while (it.hasNext()) {
m_handler.getInstanceManager().deletePojoObject(it.next());
}
m_instances.clear();
}
/**
* OSGi Service Factory getService method.
* @param arg0 the asking bundle
* @param arg1 the service registration
* @return a proxy implementing the {@link IPOJOServiceFactory}
* @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration)
*/
public Object getService(Bundle arg0, ServiceRegistration arg1) {
Object proxy = Proxy.newProxyInstance(getInstanceManager().getClazz().getClassLoader(),
getSpecificationsWithIPOJOServiceFactory(m_serviceSpecifications, m_handler.getInstanceManager().getContext()), this);
return proxy;
}
/**
* OSGi Service factory unget method.
* Does nothing.
* @param arg0 the asking bundle
* @param arg1 the service registration
* @param arg2 the service object created for this bundle.
* @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration, java.lang.Object)
*/
public void ungetService(Bundle arg0, ServiceRegistration arg1,
Object arg2) { }
/**
* Utility method returning the class array of provided service
* specification and the {@link IPOJOServiceFactory} interface.
* @param specs the published service interface
* @param bc the bundle context, used to load classes
* @return the class array containing provided service specification and
* the {@link IPOJOServiceFactory} class.
*/
private Class[] getSpecificationsWithIPOJOServiceFactory(String[] specs, BundleContext bc) {
Class[] classes = new Class[specs.length + 1];
int i = 0;
for (i = 0; i < specs.length; i++) {
try {
classes[i] = bc.getBundle().loadClass(specs[i]);
} catch (ClassNotFoundException e) {
// Should not happen.
}
}
classes[i] = IPOJOServiceFactory.class;
return classes;
}
}
}
| apache-2.0 |
amoraes/mobify | mobify-server/src/main/java/com/amoraesdev/mobify/repositories/UserRepository.java | 394 | package com.amoraesdev.mobify.repositories;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
import com.amoraesdev.mobify.entities.User;
public interface UserRepository extends CassandraRepository<User> {
@Query("select * from user where username = ?0")
public User findByUsername(String username);
}
| apache-2.0 |
tyybjcc/Design-Patterns-in-java | DesignPatterns/src/com/designpattern/structural/adapter/Target.java | 104 | package com.designpattern.structural.adapter;
public interface Target {
public void request();
}
| apache-2.0 |
StefanHeimberg/maven3-unit_integration_systemtest-setup | parent/example-web/src/main/java/com/github/stefanheimberg/example/web/rest/company/CompanyResource.java | 1728 | /*
* Copyright 2015 Stefan Heimberg <kontakt@stefanheimberg.ch>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.stefanheimberg.example.web.rest.company;
import com.github.stefanheimberg.example.web.model.Company;
import com.github.stefanheimberg.example.web.persistence.CompanyRepository;
import java.util.Collection;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* @author Stefan Heimberg <kontakt@stefanheimberg.ch>
*/
@Path("companies")
@RequestScoped
public class CompanyResource {
@Inject
private CompanyRepository companyRepository;
@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Company findById(@PathParam("id") final Long id) {
final Company company = companyRepository.findById(id);
if(null == company) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return company;
}
}
| apache-2.0 |
Lihuanghe/CMPPGate | src/main/java/com/zx/sms/codec/smpp/msg/BindTransceiver.java | 1478 | package com.zx.sms.codec.smpp.msg;
/*
* #%L
* ch-smpp
* %%
* Copyright (C) 2009 - 2015 Cloudhopper by Twitter
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.zx.sms.codec.smpp.SmppConstants;
/**
*
* @author joelauer (twitter: @jjlauer or <a href="http://twitter.com/jjlauer" target=window>http://twitter.com/jjlauer</a>)
*/
public class BindTransceiver extends BaseBind<BindTransceiverResp> {
/**
*
*/
private static final long serialVersionUID = 7788689674672351061L;
public BindTransceiver() {
super(SmppConstants.CMD_ID_BIND_TRANSCEIVER, "bind_transceiver");
}
@Override
public BindTransceiverResp createResponse() {
BindTransceiverResp resp = new BindTransceiverResp();
resp.setSequenceNumber(this.getSequenceNumber());
return resp;
}
@Override
public Class<BindTransceiverResp> getResponseClass() {
return BindTransceiverResp.class;
}
} | apache-2.0 |
w2ogroup/incubator-streams | streams-components/streams-converters/src/main/java/org/apache/streams/converter/ActivityConverterProcessor.java | 10207 | /*
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.streams.converter;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.streams.core.StreamsDatum;
import org.apache.streams.core.StreamsProcessor;
import org.apache.streams.core.util.DatumUtils;
import org.apache.streams.data.ActivityConverter;
import org.apache.streams.data.DocumentClassifier;
import org.apache.streams.data.util.ActivityUtil;
import org.apache.streams.exceptions.ActivityConversionException;
import org.apache.streams.pojo.json.Activity;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* ActivityConverterProcessor is a utility processor for converting any datum document
* to an Activity.
*
* By default it will handle string json and objectnode representation of existing Activities.
*
* Implementations can add DocumentClassifiers and ActivityConverterResolvers to the processor
* to ensure additional ActivityConverters will be resolved and applied.
*
* A DocumentClassifier's reponsibility is to recognize document formats and label them, using
* a jackson-compatible POJO class.
*
* An ActivityConverterResolver's reponsibility is to identify ActivityConverter implementations
* capable of converting a raw document associated with that POJO class into an activity.
*
*/
public class ActivityConverterProcessor implements StreamsProcessor {
private final static Logger LOGGER = LoggerFactory.getLogger(ActivityConverterProcessor.class);
private List<DocumentClassifier> classifiers;
private List<ActivityConverter> converters;
private ActivityConverterProcessorConfiguration configuration;
public ActivityConverterProcessor() {
this.classifiers = Lists.newArrayList();
this.converters = Lists.newArrayList();
}
public ActivityConverterProcessor(ActivityConverterProcessorConfiguration configuration) {
this();
this.configuration = configuration;
}
@Override
public List<StreamsDatum> process(StreamsDatum entry) {
List<StreamsDatum> result = Lists.newLinkedList();
Object document = entry.getDocument();
try {
// first determine which classes this document might actually be
List<Class> detectedClasses = detectClasses(document);
if( detectedClasses.size() == 0 ) {
LOGGER.warn("Unable to classify");
return null;
} else {
LOGGER.debug("Classified document as " + detectedClasses);
}
// for each of these classes:
// use TypeUtil to switch the document to that type
Map<Class, Object> typedDocs = convertToDetectedClasses(detectedClasses, document);
if( typedDocs.size() == 0 ) {
LOGGER.warn("Unable to convert to any detected Class");
return result;
}
else {
LOGGER.debug("Document has " + typedDocs.size() + " representations: " + typedDocs.toString());
}
// for each specified / discovered converter
for( ActivityConverter converter : converters ) {
Object typedDoc = typedDocs.get(converter.requiredClass());
List<Activity> activities = applyConverter(converter, typedDoc);
for (Activity activity : activities) {
StreamsDatum datum = DatumUtils.cloneDatum(entry);
datum.setId(activity.getId());
datum.setDocument(activity);
result.add(datum);
}
}
} catch( Exception e ) {
LOGGER.warn("General exception in process! " + e.getMessage());
} finally {
return result;
}
}
protected List<Activity> applyConverter(ActivityConverter converter, Object typedDoc) {
List<Activity> activities = Lists.newArrayList();
// if the document can be typed as the required class
if( typedDoc != null ) {
// let the converter create activities if it can
try {
activities = convertToActivity(converter, typedDoc);
} catch( Exception e ) {
LOGGER.debug("convertToActivity caught exception " + e.getMessage());
}
}
return activities;
}
protected List<Activity> convertToActivity(ActivityConverter converter, Object document) {
List<Activity> activities = Lists.newArrayList();
try {
activities = converter.toActivityList(document);
} catch (ActivityConversionException e1) {
LOGGER.debug(converter.getClass().getCanonicalName() + " unable to convert " + converter.requiredClass().getClass().getCanonicalName() + " to Activity");
}
for (Activity activity : activities) {
if (activity != null) {
// only accept valid activities
// this primitive validity check should be replaced with
// one that applies javax.validation to JSR303 annotations
// on the Activity json schema once a suitable implementation
// is found.
if (!ActivityUtil.isValid(activity)) {
activities.remove(activity);
LOGGER.debug(converter.getClass().getCanonicalName() + " produced invalid Activity converting " + converter.requiredClass().getClass().getCanonicalName());
}
} else {
LOGGER.debug(converter.getClass().getCanonicalName() + " returned null converting " + converter.requiredClass().getClass().getCanonicalName() + " to Activity");
}
}
return activities;
}
protected List<Class> detectClasses(Object document) {
Set<Class> detectedClasses = Sets.newConcurrentHashSet();
for( DocumentClassifier classifier : classifiers ) {
List<Class> detected = classifier.detectClasses(document);
if( detected != null && detected.size() > 0)
detectedClasses.addAll(detected);
}
return Lists.newArrayList(detectedClasses);
}
private Map<Class, Object> convertToDetectedClasses(List<Class> datumClasses, Object document) {
Map<Class, Object> convertedDocuments = Maps.newHashMap();
for( Class detectedClass : datumClasses ) {
Object typedDoc;
if (detectedClass.isInstance(document))
typedDoc = document;
else
typedDoc = TypeConverterUtil.convert(document, detectedClass);
if( typedDoc != null )
convertedDocuments.put(detectedClass, typedDoc);
}
return convertedDocuments;
}
@Override
public void prepare(Object configurationObject) {
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("org.apache.streams"))
.setScanners(new SubTypesScanner()));
if ( configuration != null &&
configuration.getClassifiers() != null &&
configuration.getClassifiers().size() > 0) {
for( DocumentClassifier classifier : configuration.getClassifiers()) {
try {
this.classifiers.add(classifier);
} catch (Exception e) {
LOGGER.warn("Exception adding " + classifier);
}
}
} else {
Set<Class<? extends DocumentClassifier>> classifierClasses = reflections.getSubTypesOf(DocumentClassifier.class);
for (Class classifierClass : classifierClasses) {
try {
this.classifiers.add((DocumentClassifier) classifierClass.newInstance());
} catch (Exception e) {
LOGGER.warn("Exception instantiating " + classifierClass);
}
}
}
Preconditions.checkArgument(this.classifiers.size() > 0);
if (configuration != null &&
configuration.getConverters() != null &&
configuration.getConverters().size() > 0) {
for( ActivityConverter converter : configuration.getConverters()) {
try {
this.converters.add(converter);
} catch (Exception e) {
LOGGER.warn("Exception adding " + converter);
}
}
} else {
Set<Class<? extends ActivityConverter>> converterClasses = reflections.getSubTypesOf(ActivityConverter.class);
for (Class converterClass : converterClasses) {
try {
this.converters.add((ActivityConverter) converterClass.newInstance());
} catch (Exception e) {
LOGGER.warn("Exception instantiating " + converterClass);
}
}
}
Preconditions.checkArgument(this.converters.size() > 0);
}
@Override
public void cleanUp() {
}
};
| apache-2.0 |
cisoft8341/starapp | starapp-webapp/src/main/java/org/starapp/andriod/entity/Task.java | 2335 | package org.starapp.andriod.entity;
import javax.persistence.GenerationType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Column;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.DecimalMin;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Lists;
import com.google.common.collect.ImmutableList;
import java.util.Date;
import java.util.List;
import java.io.Serializable;
/**
* @author wangqiang@cisoft.com.cn
*
*/
@Entity
@Table(name = "app_task")
public class Task implements Serializable{
/**
* ID
*/
private long id;
/**
* TITLE
*/
private String title;
/**
* DESCRIPTION
*/
private String description;
/**
* CREATE_DATE
*/
private Date createDate;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ID")
@DecimalMin(value="0")
public long getId(){
return this.id;
}
public void setId(long id){
this.id = id;
}
@NotBlank
public String getTitle(){
return this.title;
}
public void setTitle(String title){
this.title = title;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
@Temporal(TemporalType.TIMESTAMP)
public Date getCreateDate(){
return this.createDate;
}
public void setCreateDate(Date createDate){
this.createDate = createDate;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| apache-2.0 |
weld/core | tests-arquillian/src/test/java/org/jboss/weld/tests/decorators/interceptor/Intercepted.java | 1228 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.decorators.interceptor;
import jakarta.interceptor.InterceptorBinding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@InterceptorBinding
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Intercepted {
}
| apache-2.0 |
AnonymousProductions/MineFantasy2 | src/main/java/minefantasy/mf2/item/list/ComponentListMF.java | 16365 | package minefantasy.mf2.item.list;
import java.util.ArrayList;
import java.util.Iterator;
import minefantasy.mf2.api.MineFantasyAPI;
import minefantasy.mf2.api.heating.Heatable;
import minefantasy.mf2.api.knowledge.InformationBase;
import minefantasy.mf2.api.material.CustomMaterial;
import minefantasy.mf2.api.mining.RandomDigs;
import minefantasy.mf2.api.mining.RandomOre;
import minefantasy.mf2.block.list.BlockListMF;
import minefantasy.mf2.item.AdvancedFuelHandlerMF;
import minefantasy.mf2.item.FuelHandlerMF;
import minefantasy.mf2.item.ItemComponentMF;
import minefantasy.mf2.item.ItemFilledMould;
import minefantasy.mf2.item.ItemHide;
import minefantasy.mf2.item.ItemMFBowl;
import minefantasy.mf2.item.ItemRawOreMF;
import minefantasy.mf2.item.custom.*;
import minefantasy.mf2.item.food.FoodListMF;
import minefantasy.mf2.item.gadget.ItemBombComponent;
import minefantasy.mf2.item.gadget.ItemCrossbowPart;
import minefantasy.mf2.item.heatable.ItemHeated;
import minefantasy.mf2.material.BaseMaterialMF;
import minefantasy.mf2.material.WoodMaterial;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.registry.GameRegistry;
/**
* @author Anonymous Productions
*/
public class ComponentListMF
{
public static final String[] ingotMats = new String[]
{
"copper",
"tin",
"bronze",
"pigiron",
"steel",
"encrusted",
"blacksteelweak",
"blacksteel",
"silver",
"redsteelweak",
"redsteel",
"bluesteelweak",
"bluesteel",
"adamantium",
"mithril",
"ignotumite",
"mithium",
"ender",
"tungsten",
"obsidian",
};
public static Item clay_pot = new ItemMFBowl("clay_pot");
public static Item clay_pot_uncooked = new ItemComponentMF("clay_pot_uncooked", 0);
public static Item ingot_mould = new ItemComponentMF("ingot_mould");
public static Item ingot_mould_uncooked = new ItemComponentMF("ingot_mould_uncooked", 0);
public static Item pie_tray_uncooked = new ItemComponentMF("pie_tray_uncooked", 0);
public static ItemComponentMF[] ingots = new ItemComponentMF[ingotMats.length];
public static Item plank = new ItemComponentMF("plank").setCustom("yes");
public static Item vine = new ItemComponentMF("vine", -1);
public static Item sharp_rock = new ItemComponentMF("sharp_rock", -1);
public static Item flux = new ItemComponentMF("flux", 0);
public static Item flux_strong = new ItemComponentMF("flux_strong", 0);
public static Item coalDust = new ItemComponentMF("coalDust", 0).setContainerItem(clay_pot);
public static Item nitre = new ItemComponentMF("nitre", 0);
public static Item sulfur = new ItemComponentMF("sulfur", 0);
public static Item iron_prep = new ItemComponentMF("iron_prep", 0);
public static Item blackpowder = new ItemBombComponent("blackpowder", 0, "powder", 0).setContainerItem(clay_pot);
public static Item blackpowder_advanced = new ItemBombComponent("blackpowder_advanced", 1, "powder", 1).setContainerItem(clay_pot);
public static Item fletching = new ItemComponentMF("fletching", 0);
public static Item shrapnel = new ItemBombComponent("shrapnel", 0, "filling", 1).setContainerItem(ComponentListMF.clay_pot);
public static Item magma_cream_refined = new ItemBombComponent("magma_cream_refined", 1, "filling", 2).setContainerItem(clay_pot);
public static Item bomb_fuse = new ItemBombComponent("bomb_fuse", 0, "fuse", 0);
public static Item bomb_fuse_long = new ItemBombComponent("bomb_fuse_long", 0, "fuse", 1);
public static Item bomb_casing_uncooked = new ItemComponentMF("bomb_casing_uncooked", 0);
public static Item bomb_casing = new ItemBombComponent("bomb_casing", 0, "bombcase", 0);
public static Item mine_casing_uncooked = new ItemComponentMF("mine_casing_uncooked", 0);
public static Item mine_casing = new ItemBombComponent("mine_casing", 0, "minecase", 0);
public static Item bomb_casing_iron = new ItemBombComponent("bomb_casing_iron", 0, "bombcase", 1);
public static Item mine_casing_iron = new ItemBombComponent("mine_casing_iron", 0, "minecase", 1);
public static Item bomb_casing_obsidian = new ItemBombComponent("bomb_casing_obsidian", 1, "bombcase", 2);
public static Item mine_casing_obsidian = new ItemBombComponent("mine_casing_obsidian", 1, "minecase", 2);
public static Item bomb_casing_crystal = new ItemBombComponent("bomb_casing_crystal", 1, "bombcase", 3);
public static Item mine_casing_crystal = new ItemBombComponent("mine_casing_crystal", 1, "minecase", 3);
public static Item bomb_casing_arrow = new ItemBombComponent("bomb_casing_arrow", 1, "arrow", 0);
public static Item bomb_casing_bolt = new ItemBombComponent("bomb_casing_bolt", 1, "bolt", 0);
public static Item coke = new ItemComponentMF("coke", 1);
public static Item diamond_shards = new ItemComponentMF("diamond_shards", 0);
public static Item clay_brick = new ItemComponentMF("clay_brick", 0);
public static Item kaolinite = new ItemComponentMF("kaolinite", 0);
public static Item kaolinite_dust = new ItemComponentMF("kaolinite_dust", 0).setContainerItem(clay_pot);
public static Item fireclay = new ItemComponentMF("fireclay", 0);
public static Item fireclay_brick = new ItemComponentMF("fireclay_brick", 0);
public static Item strong_brick = new ItemComponentMF("strong_brick", 0);
public static Item hideSmall = new ItemComponentMF("hideSmall", 0);
public static Item hideMedium = new ItemComponentMF("hideMedium", 0);
public static Item hideLarge = new ItemComponentMF("hideLarge", 0);
public static Item rawhideSmall = new ItemHide("rawhideSmall", hideSmall, 1.0F);
public static Item rawhideMedium = new ItemHide("rawhideMedium", hideMedium, 1.5F);
public static Item rawhideLarge = new ItemHide("rawhideLarge", hideLarge, 3.0F);
public static Item dragon_heart = new ItemComponentMF("dragon_heart", 1);
public static Item leather_strip = new ItemComponentMF("leather_strip", 0);
public static Item nail = new ItemComponentMF("nail", 0);
public static Item rivet = new ItemComponentMF("rivet", 0);
public static Item thread = new ItemComponentMF("thread", 0);
public static Item obsidian_rock = new ItemComponentMF("obsidian_rock", 0);
public static Item oreCopper = new ItemRawOreMF("oreCopper", -1);
public static Item oreTin = new ItemRawOreMF("oreTin", -1);
public static Item oreIron = new ItemRawOreMF("oreIron", 0);
public static Item oreSilver = new ItemRawOreMF("oreSilver", 0);
public static Item oreGold = new ItemRawOreMF("oreGold", 0);
public static Item oreTungsten = new ItemRawOreMF("oreTungsten", 1);
public static Item hotItem = new ItemHeated();
public static Item plant_oil = new ItemComponentMF("plant_oil", 0).setContainerItem(FoodListMF.jug_empty);
public static Item talisman_lesser= new ItemComponentMF("talisman_lesser", 1);
public static Item talisman_greater= new ItemComponentMF("talisman_greater", 3);
public static Item bolt = new ItemComponentMF("bolt", 0);
public static Item iron_frame = new ItemComponentMF("iron_frame", 0);
public static Item iron_strut = new ItemComponentMF("iron_strut", 0);
public static Item bronze_gears = new ItemComponentMF("bronze_gears", 0);
public static Item tungsten_gears = new ItemComponentMF("tungsten_gears", 1);
public static Item steel_tube = new ItemComponentMF("steel_tube", 0);
public static Item cogwork_shaft = new ItemComponentMF("cogwork_shaft", 1);
public static Item ingotCompositeAlloy = new ItemComponentMF("ingotCompositeAlloy", 1);
public static Item coal_prep = new ItemComponentMF("coal_prep", 0);
public static Item ingot_mould_filled = new ItemFilledMould();
public static Item crossbow_stock_wood = new ItemCrossbowPart("cross_stock_wood", "stock").addSpeed(1.0F).addRecoil(0.5F);
public static Item crossbow_stock_iron = new ItemCrossbowPart("cross_stock_iron", "stock").addSpeed(1.0F).addRecoil(-0.5F).addDurability(150);
public static Item crossbow_handle_wood = new ItemCrossbowPart("cross_handle_wood", "stock").addSpeed(0.5F).addRecoil(1.5F).addSpread(1.0F);
public static Item cross_arms_basic = new ItemCrossbowPart("cross_arms_basic", "mechanism").addPower(1.00F).addSpeed(0.50F).addRecoil(1.00F).addSpread(1.00F);
public static Item cross_arms_light = new ItemCrossbowPart("cross_arms_light", "mechanism").addPower(0.85F).addSpeed(0.25F).addRecoil(0.50F).addSpread(0.50F);
public static Item cross_arms_heavy = new ItemCrossbowPart("cross_arms_heavy", "mechanism").addPower(1.15F).addSpeed(1.00F).addRecoil(1.50F).addSpread(2.00F);
public static Item cross_arms_advanced = new ItemCrossbowPart("cross_arms_advanced", "mechanism").addPower(1.15F).addSpeed(1.00F).addRecoil(2.50F).addSpread(0.25F).addDurability(150);
public static Item cross_bayonet = new ItemCrossbowPart("cross_bayonet", "muzzle").addBash(4.0F).addRecoil(-0.5F).addSpeed(0.5F);
public static Item cross_ammo = new ItemCrossbowPart("cross_ammo", "mod").addCapacity(5).addSpread(2.00F);
public static Item cross_scope = new ItemCrossbowPart("cross_scope", "mod").setScope(0.75F);
//public static ItemHaft hilt_custom = new ItemHaft("hilt");
//public static ItemHaft longhilt_custom = new ItemHaft("longhilt");
//public static ItemHaft haft_custom = new ItemHaft("haft");
//public static ItemHaft longhaft_custom = new ItemHaft("longhaft");
//public static ItemHaft spearhaft_custom = new ItemHaft("spearhaft");
//public static ItemCustomComponent plankCustom = new ItemCustomComponent("plank", 1F);
//public static ItemCustomComponent plateHeavy = new ItemCustomComponent("plateheavy", 3F);
public static ItemCustomComponent chainmesh = new ItemCustomComponent("chainmesh", 1F);
public static ItemCustomComponent scalemesh = new ItemCustomComponent("scalemesh", 1F);
public static ItemCustomComponent splintmesh = new ItemCustomComponent("splintmesh", 1F);
public static ItemCustomComponent plate = new ItemCustomComponent("plate", 2F);
//public static ItemCustomComponent scrapMetal = new ItemCustomComponent("scrap", 1F);
public static ItemCustomComponent metalHunk = new ItemCustomComponent("hunk", 0.25F);
public static ItemCustomComponent arrowhead = new ItemCustomComponent("arrowhead", 1/4F);
public static ItemCustomComponent bodkinhead = new ItemCustomComponent("bodkinhead", 1/4F);
public static ItemCustomComponent broadhead = new ItemCustomComponent("broadhead", 1/4F);
public static Item flux_pot = new ItemComponentMF("flux_pot", 0).setContainerItem(clay_pot);
public static Item coal_flux = new ItemComponentMF("coal_flux", 0);
//public static Item lime_rock = new ItemComponentMF("lime_rock", 0);
//public static Item borax_rock = new ItemComponentMF("borax_rock", 0);
//public static Item sulfur_rock = new ItemComponentMF("sulfur_rock", 0);
//public static Item nitre_rock = new ItemComponentMF("nitre_rock", 0);
public static void load()
{
WoodMaterial.init();
Items.potionitem.setContainerItem(Items.glass_bottle);
GameRegistry.registerFuelHandler(new FuelHandlerMF());
MineFantasyAPI.registerFuelHandler(new AdvancedFuelHandlerMF());
Items.iron_ingot.setTextureName("minefantasy2:component/ingotWroughtIron");
Blocks.iron_block.setBlockTextureName("minefantasy2:metal/iron_block");
Blocks.iron_bars.setBlockTextureName("minefantasy2:metal/iron_bars");
for(int a = 0; a < ingotMats.length; a ++)
{
BaseMaterialMF mat = BaseMaterialMF.getMaterial(ingotMats[a]);
String name = mat.name;
int rarity = mat.rarity;
ingots[a] = new ItemComponentMF("ingot"+name, rarity);
OreDictionary.registerOre("ingot"+name, ingots[a]);
if(name.equalsIgnoreCase("PigIron"))
{
OreDictionary.registerOre("ingotRefinedIron", ingots[a]);
}
}
/*for(int a = 0; a < woodMats.length; a ++)
{
CustomMaterial mat = CustomMaterial.getMaterial(woodMats[a]);
String name = mat.name;
planks[a] = new ItemComponentMF("plank"+name, 0).setCustom("This is irrelevant text,but i'm lazy now");
OreDictionary.registerOre("MFplank2"+name, planks[a]);
}*/
addRandomDrops();
initFuels();
OreDictionary.registerOre("ingotCompositeAlloy", ingotCompositeAlloy);
OreDictionary.registerOre("ingotIron", Items.iron_ingot);
OreDictionary.registerOre("ingotGold", Items.gold_ingot);
OreDictionary.registerOre("carbon", new ItemStack(Items.coal, 1, OreDictionary.WILDCARD_VALUE));
OreDictionary.registerOre("carbon", coke);
OreDictionary.registerOre("carbon", coal_flux);
}
private static void initFuels()
{
MineFantasyAPI.addForgeFuel(new ItemStack(Items.coal, 1, 0), 900, 150);// 150* , 45s
MineFantasyAPI.addForgeFuel(new ItemStack(Items.coal, 1, 1), 1200, 170);// 170* , 1m
MineFantasyAPI.addForgeFuel(Items.blaze_powder, 200, 300, true);// 300* , 10s
MineFantasyAPI.addForgeFuel(Items.blaze_rod, 300, 300, true);// 300* , 15s
MineFantasyAPI.addForgeFuel(Items.fire_charge, 1200, 350,true);// 350* , 1m
MineFantasyAPI.addForgeFuel(Items.lava_bucket, 2400, 500, true);// 500* , 2m
MineFantasyAPI.addForgeFuel(Items.magma_cream, 2400, 400);// 400* , 2m
MineFantasyAPI.addForgeFuel(ComponentListMF.coalDust, 200, 150);// 150* , 10s
MineFantasyAPI.addForgeFuel(ComponentListMF.coke, 1200, 250);// 250* , 1m
MineFantasyAPI.addForgeFuel(ComponentListMF.magma_cream_refined, 2400, 200);// 500* , 2m
}
private static void addRandomDrops()
{
RandomOre.addOre(new ItemStack(kaolinite), 1.5F, Blocks.stone, -1, 32,128, false);
RandomOre.addOre(new ItemStack(flux), 2F, Blocks.stone, -1, 0, 128, false);
RandomOre.addOre(new ItemStack(flux_strong), 1F, Blocks.stone, 2, 0, 128, false);
RandomOre.addOre(new ItemStack(flux), 20F, BlockListMF.limestone, 0, -1, 0, 256, true);
RandomOre.addOre(new ItemStack(flux_strong), 10F, BlockListMF.limestone, 0, 2, 0, 256, true);
RandomOre.addOre(new ItemStack(Items.coal), 2F, Blocks.stone, -1, 0, 128, false);
RandomOre.addOre(new ItemStack(sulfur), 2F, Blocks.stone, -1, 0, 16, false);
RandomOre.addOre(new ItemStack(nitre), 3F, Blocks.stone, -1, 0, 64, false);
RandomOre.addOre(new ItemStack(Items.redstone), 5F, Blocks.stone, 2, 0, 16, false);
RandomOre.addOre(new ItemStack(Items.flint), 1F, Blocks.stone, -1, 0, 64, false);
RandomOre.addOre(new ItemStack(diamond_shards), 0.2F,Blocks.stone, 2, 0, 16, false);
RandomOre.addOre(new ItemStack(Items.quartz), 0.5F,Blocks.stone, 3, 0, 16, false);
RandomOre.addOre(new ItemStack(sulfur), 10F,Blocks.netherrack, -1, 0, 512, false);
RandomOre.addOre(new ItemStack(Items.glowstone_dust), 5F,Blocks.netherrack, -1, 0, 512, false);
RandomOre.addOre(new ItemStack(Items.quartz), 5F, Blocks.netherrack, -1, 0, 512, false);
RandomOre.addOre(new ItemStack(Items.blaze_powder), 5F, Blocks.netherrack, -1, 0, 512, false);
RandomOre.addOre(new ItemStack(Items.nether_wart), 1F, Blocks.netherrack, -1, 0, 512, false);
RandomOre.addOre(new ItemStack(Items.nether_star), 0.01F, Blocks.netherrack, -1, 0, 512,false);
RandomDigs.addOre(new ItemStack(Blocks.skull, 1, 1), 0.1F, Blocks.soul_sand,3, 0, 256, false);
RandomDigs.addOre(new ItemStack(Items.bone), 5F, Blocks.dirt, -1, 0, 256, false);
RandomDigs.addOre(new ItemStack(Items.rotten_flesh), 2F, Blocks.dirt, -1, 0, 256, false);
RandomDigs.addOre(new ItemStack(Items.coal, 1, 1), 1F, Blocks.dirt, -1, 32, 64, false);
RandomDigs.addOre(new ItemStack(Items.melon_seeds), 5F, Blocks.grass, -1, 0, 256, false);
RandomDigs.addOre(new ItemStack(Items.pumpkin_seeds), 8F, Blocks.grass, -1, 0, 256, false);
RandomOre.addOre(new ItemStack(oreCopper), 4F, Blocks.stone, 0, 48, 96, false);
RandomOre.addOre(new ItemStack(oreTin), 2F,Blocks.stone, 0, 48, 96, false);
RandomOre.addOre(new ItemStack(oreIron), 5F, Blocks.stone, 0, 0, 64, false);
RandomOre.addOre(new ItemStack(oreSilver), 1.5F, Blocks.stone, 0, 0, 32, false);
RandomOre.addOre(new ItemStack(oreGold), 1F, Blocks.stone, 0, 0, 32, false);
RandomOre.addOre(new ItemStack(oreTungsten), 1F, Blocks.stone, 3, 0, 16, false, "tungsten");
}
}
| apache-2.0 |
HaoyuHuang/ZapporChallenge | src/com/photoshare/zappor/challenge/main/Main.java | 3209 | package com.photoshare.zappor.challenge.main;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.photoshare.zappor.challenge.pricefacet.PriceBean;
import com.photoshare.zappor.challenge.pricefacet.PriceFacetRequest;
import com.photoshare.zappor.challenge.pricefacet.PriceFacetResponse;
import com.photoshare.zappor.challenge.pricefacet.PriceHelper;
import com.photoshare.zappor.challenge.pricefacet.PriceFacetRequest.PriceFacetRequestBuilder;
import com.photoshare.zappor.challenge.product.ProductBean;
import com.photoshare.zappor.challenge.product.ProductHelper;
import com.photoshare.zappor.challenge.product.SearchProductByPriceRequest;
import com.photoshare.zappor.challenge.product.SearchProductByPriceResponse;
public class Main {
public static void main(String[] args) {
PriceFacetRequest request = new PriceFacetRequestBuilder()
.excludeResults(true).facetSortByName(true).filter(true)
.filterOnSale(true).includeOnSale(true).onSale(true).term("")
.build();
PriceFacetResponse response = new PriceFacetResponse("");
PriceHelper priceHelper = new PriceHelper();
List<PriceBean> beans = priceHelper.getPriceFacets(request, response);
Scanner scan = new Scanner(System.in);
int number = 0;
double dollar = 0;
while(scan.hasNextLine()) {
System.out.println("Please input the desired number of products:");
number = scan.nextInt();
System.out.println("Please input the desired dollar amount:");
dollar = scan.nextDouble();
Algorithm algorithm = new Algorithm();
List<SelectedPrice> selectedPrices = new ArrayList<SelectedPrice>();
computeClosestProductList(beans, algorithm, selectedPrices, number,
dollar);
}
scan.close();
}
/**
* Calculate the closest value and print the chosen products.
*
* @param beans
* @param algorithm
* @param selectedPrices
* @param number
* @param dollar
*/
private static void computeClosestProductList(List<PriceBean> beans,
Algorithm algorithm, List<SelectedPrice> selectedPrices,
int number, double dollar) {
double closestValue = algorithm.findClosestValue(number, dollar, beans,
selectedPrices);
List<ProductBean> satisfyProducts = new ArrayList<ProductBean>();
for (SelectedPrice selectedPrice : selectedPrices) {
SearchProductByPriceRequest productByPriceRequest = new SearchProductByPriceRequest.SearchProductByPriceRequestBuilder()
.Price(selectedPrice.getPrice()).IncludeOnSale(true)
.OnSale(true).Limit(selectedPrice.getCount()).build();
SearchProductByPriceResponse productByPriceResponse = new SearchProductByPriceResponse(
"");
ProductHelper productHelper = new ProductHelper();
List<ProductBean> products = productHelper.getProductByPrice(
productByPriceRequest, productByPriceResponse);
satisfyProducts.addAll(products);
}
Logger.getAnonymousLogger().log(Level.INFO,
"closestValue:" + closestValue);
for (ProductBean product : satisfyProducts) {
Logger.getAnonymousLogger().log(Level.INFO, product.toString());
}
}
}
| apache-2.0 |
jsakamoto/selenium | java/server/src/org/openqa/selenium/grid/router/httpd/RouterServer.java | 4707 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.grid.router.httpd;
import com.google.auto.service.AutoService;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import org.openqa.selenium.cli.CliCommand;
import org.openqa.selenium.grid.config.AnnotatedConfig;
import org.openqa.selenium.grid.config.CompoundConfig;
import org.openqa.selenium.grid.config.ConcatenatingConfig;
import org.openqa.selenium.grid.config.Config;
import org.openqa.selenium.grid.config.EnvConfig;
import org.openqa.selenium.grid.distributor.Distributor;
import org.openqa.selenium.grid.distributor.DistributorOptions;
import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;
import org.openqa.selenium.grid.log.LoggingOptions;
import org.openqa.selenium.grid.node.local.NodeFlags;
import org.openqa.selenium.grid.router.Router;
import org.openqa.selenium.grid.server.BaseServer;
import org.openqa.selenium.grid.server.BaseServerFlags;
import org.openqa.selenium.grid.server.BaseServerOptions;
import org.openqa.selenium.grid.server.HelpFlags;
import org.openqa.selenium.grid.server.Server;
import org.openqa.selenium.grid.server.W3CCommandHandler;
import org.openqa.selenium.grid.sessionmap.SessionMap;
import org.openqa.selenium.grid.sessionmap.SessionMapOptions;
import org.openqa.selenium.grid.sessionmap.remote.RemoteSessionMap;
import org.openqa.selenium.grid.web.Routes;
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.selenium.remote.tracing.DistributedTracer;
import org.openqa.selenium.remote.tracing.GlobalDistributedTracer;
import java.net.URL;
@AutoService(CliCommand.class)
public class RouterServer implements CliCommand {
@Override
public String getName() {
return "router";
}
@Override
public String getDescription() {
return "Creates a router to front the selenium grid.";
}
@Override
public Executable configure(String... args) {
HelpFlags help = new HelpFlags();
BaseServerFlags serverFlags = new BaseServerFlags(4444);
NodeFlags nodeFlags = new NodeFlags();
JCommander commander = JCommander.newBuilder()
.programName(getName())
.addObject(help)
.addObject(serverFlags)
.addObject(nodeFlags)
.build();
return () -> {
try {
commander.parse(args);
} catch (ParameterException e) {
System.err.println(e.getMessage());
commander.usage();
return;
}
if (help.displayHelp(commander, System.out)) {
return;
}
Config config = new CompoundConfig(
new AnnotatedConfig(help),
new AnnotatedConfig(serverFlags),
new AnnotatedConfig(nodeFlags),
new EnvConfig(),
new ConcatenatingConfig("router", '.', System.getProperties()));
LoggingOptions loggingOptions = new LoggingOptions(config);
loggingOptions.configureLogging();
DistributedTracer tracer = loggingOptions.getTracer();
GlobalDistributedTracer.setInstance(tracer);
SessionMapOptions sessionsOptions = new SessionMapOptions(config);
URL sessionMapUrl = sessionsOptions.getSessionMapUri().toURL();
SessionMap sessions = new RemoteSessionMap(
HttpClient.Factory.createDefault().createClient(sessionMapUrl));
BaseServerOptions serverOptions = new BaseServerOptions(config);
DistributorOptions distributorOptions = new DistributorOptions(config);
URL distributorUrl = distributorOptions.getDistributorUri().toURL();
Distributor distributor = new RemoteDistributor(
tracer,
HttpClient.Factory.createDefault(),
distributorUrl);
Router router = new Router(tracer, sessions, distributor);
Server<?> server = new BaseServer<>(serverOptions);
server.addRoute(Routes.matching(router).using(router).decorateWith(W3CCommandHandler.class));
server.start();
};
}
}
| apache-2.0 |
nebulae2us/stardust | src/test/java/org/nebulae2us/stardust/sql/domain/MockedDataReader.java | 2480 | /*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nebulae2us.stardust.sql.domain;
import java.sql.Date;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.nebulae2us.electron.util.Immutables.*;
/**
* @author Trung Phan
*
*/
public class MockedDataReader extends DataReader {
private final List<String> columnNames;
private final List<Object[]> data;
private int currentPos = -1;
private final Map<String, Integer> columnNameIndexes;
public MockedDataReader(List<String> columnNames, List<Object[]> data) {
this.columnNames = $(columnNames).elementToUpperCase();
this.data = data;
columnNameIndexes = new HashMap<String, Integer>();
for (int i = columnNames.size() - 1; i >= 0; i--) {
columnNameIndexes.put(columnNames.get(i).toLowerCase(), i);
}
}
@SuppressWarnings("unchecked")
public MockedDataReader(List<String> columnNames) {
this(columnNames, Collections.EMPTY_LIST);
}
@Override
public int findColumn(String columnName) {
int idx = this.columnNames.indexOf(columnName.toUpperCase());
return idx < 0 ? -1 : idx + 1;
}
@SuppressWarnings("unchecked")
@Override
public <T> T read(Class<T> expectedClass, int columnIndex) {
Object result = this.data.get(currentPos)[columnIndex - 1];
if (expectedClass.isInstance(result)) {
return (T)result;
}
// TODO expand more scenarios
if (expectedClass == Date.class) {
return (T)new Date(((java.util.Date)result).getTime());
}
return (T)result;
}
@Override
public boolean next() {
return ++this.currentPos < this.data.size();
}
@Override
public <T> T read(Class<T> expectedClass, String columnName) {
int index = columnNameIndexes.get(columnName);
return read(expectedClass, index + 1);
}
@Override
public void close() {
}
@Override
public int getRowNumber() {
return this.currentPos;
}
}
| apache-2.0 |
DiUS/pact-jvm | provider/junit/src/test/java/au/com/dius/pact/provider/junit/StateTeardownTest.java | 1997 | package au.com.dius.pact.provider.junit;
import static com.github.restdriver.clientdriver.RestClientDriver.giveEmptyResponse;
import static com.github.restdriver.clientdriver.RestClientDriver.onRequestTo;
import static org.junit.Assert.assertEquals;
import au.com.dius.pact.provider.junitsupport.Provider;
import au.com.dius.pact.provider.junitsupport.State;
import au.com.dius.pact.provider.junitsupport.StateChangeAction;
import au.com.dius.pact.provider.junitsupport.loader.PactFolder;
import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junitsupport.target.Target;
import au.com.dius.pact.provider.junitsupport.target.TestTarget;
import com.github.restdriver.clientdriver.ClientDriverRule;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
@RunWith(PactRunner.class)
@Provider("providerTeardownTest")
@PactFolder("pacts")
public class StateTeardownTest {
private static Collection<Object> stateNameParamValues = new ArrayList<>();
@ClassRule
public static final ClientDriverRule embeddedProvider = new ClientDriverRule(8333);
@TestTarget
public final Target target = new HttpTarget(8333);
@State(value = {"state 1", "state 2"}, action = StateChangeAction.SETUP)
public void toDefaultState() {
embeddedProvider.addExpectation(
onRequestTo("/data"), giveEmptyResponse()
);
}
@State(value = "state 1", action = StateChangeAction.TEARDOWN)
public void teardownDefaultState(Map<String, Object> params) {
stateNameParamValues.addAll(params.values());
}
@After
public void after() {
embeddedProvider.reset();
}
@AfterClass
public static void assertTeardownWasCalledForState1() {
assertEquals(Collections.singletonList("state 1"), stateNameParamValues);
}
}
| apache-2.0 |
AkihiroSuda/earthquake | analyzer/java/base/src/main/java/net/osrg/earthquake/ExperimentPattern.java | 1807 | // Copyright (C) 2015 Nippon Telegraph and Telephone 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 net.osrg.earthquake;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.nio.charset.Charset;
public class ExperimentPattern {
static final Logger LOG = LogManager.getLogger(ExperimentPattern.class);
Hasher hasher;
public ExperimentPattern() {
this.hasher = Hashing.sha256().newHasher();
}
// TODO: pluggable
private int normalizeCount(String rowKey, String colKey, int count) {
return count > 0 ? 1 : 0;
// return count;
}
public void putCount(String klazzName, String methodName, int line, String nodeID, boolean succ, int count) {
String rowKey = String.format("%s:%s:%d", klazzName, methodName, line);
String colKey = nodeID;
int normalizedCount = this.normalizeCount(rowKey, colKey, count);
String s = String.format("%s\t%s\t%d\n", rowKey, colKey, normalizedCount);
this.hasher.putString(s, Charset.defaultCharset());
}
public HashCode computeHash() {
return this.hasher.hash();
}
}
| apache-2.0 |
renfeihn/jeeframe | src/main/java/com/renfeihn/jeeframe/modules/oa/service/TestAuditService.java | 3466 | package com.renfeihn.jeeframe.modules.oa.service;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Maps;
import com.renfeihn.jeeframe.common.persistence.Page;
import com.renfeihn.jeeframe.common.service.CrudService;
import com.renfeihn.jeeframe.common.utils.StringUtils;
import com.renfeihn.jeeframe.modules.act.service.ActTaskService;
import com.renfeihn.jeeframe.modules.act.utils.ActUtils;
import com.renfeihn.jeeframe.modules.oa.entity.TestAudit;
import com.renfeihn.jeeframe.modules.oa.dao.TestAuditDao;
/**
* 审批Service
* @author renfei
* @version 2014-05-16
*/
@Service
@Transactional(readOnly = true)
public class TestAuditService extends CrudService<TestAuditDao, TestAudit> {
@Autowired
private ActTaskService actTaskService;
public TestAudit getByProcInsId(String procInsId) {
return dao.getByProcInsId(procInsId);
}
public Page<TestAudit> findPage(Page<TestAudit> page, TestAudit testAudit) {
testAudit.setPage(page);
page.setList(dao.findList(testAudit));
return page;
}
/**
* 审核新增或编辑
* @param testAudit
*/
@Transactional(readOnly = false)
public void save(TestAudit testAudit) {
// 申请发起
if (StringUtils.isBlank(testAudit.getId())){
testAudit.preInsert();
dao.insert(testAudit);
// 启动流程
actTaskService.startProcess(ActUtils.PD_TEST_AUDIT[0], ActUtils.PD_TEST_AUDIT[1], testAudit.getId(), testAudit.getContent());
}
// 重新编辑申请
else{
testAudit.preUpdate();
dao.update(testAudit);
testAudit.getAct().setComment(("yes".equals(testAudit.getAct().getFlag())?"[重申] ":"[销毁] ")+testAudit.getAct().getComment());
// 完成流程任务
Map<String, Object> vars = Maps.newHashMap();
vars.put("pass", "yes".equals(testAudit.getAct().getFlag())? "1" : "0");
actTaskService.complete(testAudit.getAct().getTaskId(), testAudit.getAct().getProcInsId(), testAudit.getAct().getComment(), testAudit.getContent(), vars);
}
}
/**
* 审核审批保存
* @param testAudit
*/
@Transactional(readOnly = false)
public void auditSave(TestAudit testAudit) {
// 设置意见
testAudit.getAct().setComment(("yes".equals(testAudit.getAct().getFlag())?"[同意] ":"[驳回] ")+testAudit.getAct().getComment());
testAudit.preUpdate();
// 对不同环节的业务逻辑进行操作
String taskDefKey = testAudit.getAct().getTaskDefKey();
// 审核环节
if ("audit".equals(taskDefKey)){
}
else if ("audit2".equals(taskDefKey)){
testAudit.setHrText(testAudit.getAct().getComment());
dao.updateHrText(testAudit);
}
else if ("audit3".equals(taskDefKey)){
testAudit.setLeadText(testAudit.getAct().getComment());
dao.updateLeadText(testAudit);
}
else if ("audit4".equals(taskDefKey)){
testAudit.setMainLeadText(testAudit.getAct().getComment());
dao.updateMainLeadText(testAudit);
}
else if ("apply_end".equals(taskDefKey)){
}
// 未知环节,直接返回
else{
return;
}
// 提交流程任务
Map<String, Object> vars = Maps.newHashMap();
vars.put("pass", "yes".equals(testAudit.getAct().getFlag())? "1" : "0");
actTaskService.complete(testAudit.getAct().getTaskId(), testAudit.getAct().getProcInsId(), testAudit.getAct().getComment(), vars);
}
}
| apache-2.0 |
johannesh2/textfieldformatter | src/test/java/org/vaadin/textfieldformatter/it/CustomStringBlockFormatterIT.java | 4191 | package org.vaadin.textfieldformatter.it;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.vaadin.textfieldformatter.BasicIBANFormatterUsageUI;
import org.vaadin.textfieldformatter.CSBFDelimitersUI;
import org.vaadin.textfieldformatter.CSBFNumericAndPrefixUI;
import org.vaadin.textfieldformatter.CSBFNumericAndPrefixWithBlocksUI;
import org.vaadin.textfieldformatter.CSBFNumericAndPrefixWithBuilderUI;
import org.vaadin.textfieldformatter.CSBFNumericOnlyUI;
import org.vaadin.textfieldformatter.CSBFReplacingMaskUI;
import org.vaadin.textfieldformatter.SetValueUI;
import com.vaadin.flow.component.button.testbench.ButtonElement;
import com.vaadin.flow.component.textfield.testbench.TextFieldElement;
public class CustomStringBlockFormatterIT extends AbstractCustomTestBenchTestCase {
@Before
public void init() {
startBrowser();
}
@Test
public void basicIban() throws InterruptedException {
openUI(BasicIBANFormatterUsageUI.class, BasicIBANFormatterUsageUI.BasicIBAN.class);
TextFieldElement tf = $(TextFieldElement.class).first();
tf.sendKeys("FI42500015100000231");
Assert.assertEquals("FI42 5000 1510 0000 23", tf.getValue());
}
@Test
public void replaceIbanFormatter() throws InterruptedException {
openUI(BasicIBANFormatterUsageUI.class, BasicIBANFormatterUsageUI.ReplaceIBAN.class);
TextFieldElement tf = $(TextFieldElement.class).first();
tf.sendKeys("FI425000151000002319999");
Assert.assertEquals("FI42 5000 1510 0000 2319 99", tf.getValue());
}
@Test
public void customBlockWithDelimiters() throws InterruptedException {
openUI(CSBFDelimitersUI.class);
TextFieldElement tf = $(TextFieldElement.class).first();
tf.sendKeys("12233k");
Assert.assertEquals("1-22-33k", tf.getValue());
}
@Test
public void customBlockWithDelimitersNumericOnly() throws InterruptedException {
openUI(CSBFNumericOnlyUI.class);
TextFieldElement tf = $(TextFieldElement.class).first();
tf.sendKeys("12233k");
Assert.assertEquals("1-22*33", tf.getValue());
}
@Test
public void customBlockWithReplacingMask() throws InterruptedException {
openUI(CSBFReplacingMaskUI.class);
TextFieldElement tf = $(TextFieldElement.class).first();
tf.sendKeys("12233abcd");
Assert.assertEquals("1-22-33A", tf.getValue());
$(ButtonElement.class).first().click();
Assert.assertEquals("1-*22", tf.getValue());
tf.clear();
tf.sendKeys("12233abcd");
Assert.assertEquals("12*23", tf.getValue());
}
@Test
public void customBlocksWithNumericAndPrefixBlocks() throws InterruptedException {
openUI(CSBFNumericAndPrefixWithBlocksUI.class);
TextFieldElement tf = $(TextFieldElement.class).first();
Assert.assertEquals("PREFIX: ", tf.getValue());
tf.sendKeys("1234bbbbb");
Assert.assertEquals("PREFIX: 1-23-4", tf.getValue());
}
@Test
public void customBlocksWithNumericAndPrefixWithBuilder() throws InterruptedException {
openUI(CSBFNumericAndPrefixWithBuilderUI.class);
TextFieldElement tf = $(TextFieldElement.class).first();
Assert.assertEquals("PREFIX: ", tf.getValue());
tf.sendKeys("1234bbbbb");
Assert.assertEquals("PREFIX: 1-23-4", tf.getValue());
}
@Test
public void customBlocksWithNumericAndPrefix() throws InterruptedException {
openUI(CSBFNumericAndPrefixUI.class);
TextFieldElement tf = $(TextFieldElement.class).first();
Assert.assertEquals("PREFIX:", tf.getValue());
tf.sendKeys("1234bbbbb");
Assert.assertEquals("PREFIX:1234", tf.getValue());
}
@Test
public void customBlocksWithLazyDelimiter() throws InterruptedException {
openUI(CSBFDelimitersUI.class, CSBFDelimitersUI.LazyDelimiter.class);
TextFieldElement tf = $(TextFieldElement.class).first();
tf.sendKeys("1");
Assert.assertEquals("1", tf.getValue());
tf.sendKeys("2");
Assert.assertEquals("1-2", tf.getValue());
}
@Test
@Ignore("Hacky fix for setValue broke with Vaadin TextField 2.1.2")
public void withSetValue() throws InterruptedException {
openUI(SetValueUI.class);
ButtonElement btn = $(ButtonElement.class).first();
btn.click();
TextFieldElement tf = $(TextFieldElement.class).first();
Assert.assertEquals("A-BB-CCC", tf.getValue());
}
}
| apache-2.0 |
Gugli/Openfire | src/plugins/rayo/src/java/com/sun/voip/server/ShutdownBridge.java | 2334 | /*
* Copyright 2007 Sun Microsystems, Inc.
*
* This file is part of jVoiceBridge.
*
* jVoiceBridge is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation and distributed hereunder
* to you.
*
* jVoiceBridge 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/>.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied this
* code.
*/
package com.sun.voip.server;
import com.sun.voip.Logger;
import java.io.IOException;
import java.net.Socket;
import java.net.InetAddress;
/**
* This class tells the Bridge server to shutdown
*
* and initiates calls as specified by the clients' request.
*/
public class ShutdownBridge {
public static void main(String[] args) {
String serverName = null;
if (args.length == 1) {
serverName = args[0];
} else {
try {
serverName = InetAddress.getLocalHost().getHostName();
} catch (Exception e) {
Logger.error(
"ShudownBridge: Can't get Local Host's IP Address! "
+ e.getMessage());
System.exit(0);
}
}
int serverPort = Integer.getInteger(
"com.sun.voip.server.BRIDGE_SERVER_PORT", 6666).intValue();
try {
Logger.println("Connecting to " + serverName + ":" + serverPort);
Socket socket = new Socket(serverName, serverPort);
String request = new String("SHUTDOWN\n\n");
socket.getOutputStream().write(request.getBytes());
socket.getOutputStream().flush();
Thread.sleep(1000); // give command a chance to happen
} catch (IOException e) {
} catch (Exception e) {
System.err.println("ShutdownBridge: Can't create socket "
+ serverName + ":" + serverPort + e.getMessage());
return;
}
}
}
| apache-2.0 |
sabi0/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonRunConfigurationType.java | 2927 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.griffon;
import com.intellij.compiler.options.CompileStepBeforeRun;
import com.intellij.compiler.options.CompileStepBeforeRunNoErrorCheck;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.ConfigurationTypeUtil;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import icons.JetgroovyIcons;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class GriffonRunConfigurationType implements ConfigurationType {
private final ConfigurationFactory myConfigurationFactory;
@NonNls private static final String GRIFFON_APPLICATION = "Griffon";
public GriffonRunConfigurationType() {
myConfigurationFactory = new ConfigurationFactory(this) {
@NotNull
@Override
public RunConfiguration createTemplateConfiguration(@NotNull Project project) {
return new GriffonRunConfiguration(this, project, GRIFFON_APPLICATION, "run-app");
}
@Override
public void configureBeforeRunTaskDefaults(Key<? extends BeforeRunTask> providerID, BeforeRunTask task) {
if (providerID == CompileStepBeforeRun.ID || providerID == CompileStepBeforeRunNoErrorCheck.ID) {
task.setEnabled(false);
}
}
};
}
@Override
public String getDisplayName() {
return GRIFFON_APPLICATION;
}
@Override
public String getConfigurationTypeDescription() {
return GRIFFON_APPLICATION;
}
@Override
public Icon getIcon() {
return JetgroovyIcons.Griffon.Griffon;
}
@Override
@NonNls
@NotNull
public String getId() {
return "GriffonRunConfigurationType";
}
@Override
public ConfigurationFactory[] getConfigurationFactories() {
return new ConfigurationFactory[]{myConfigurationFactory};
}
@Nullable
@Override
public String getHelpTopic() {
return null;
}
public static GriffonRunConfigurationType getInstance() {
return ConfigurationTypeUtil.findConfigurationType(GriffonRunConfigurationType.class);
}
}
| apache-2.0 |
tlvince/commafeed | src/main/java/com/commafeed/frontend/pages/PasswordRecoveryCallbackPage.java | 2914 | package com.commafeed.frontend.pages;
import java.util.Calendar;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.validation.validator.StringValidator;
import com.commafeed.backend.model.User;
import com.commafeed.backend.services.PasswordEncryptionService;
import com.commafeed.backend.services.UserService;
import com.commafeed.frontend.pages.components.BootstrapFeedbackPanel;
import com.commafeed.frontend.utils.exception.DisplayException;
@SuppressWarnings("serial")
public class PasswordRecoveryCallbackPage extends BasePage {
public static final String PARAM_EMAIL = "email";
public static final String PARAM_TOKEN = "token";
@Inject
PasswordEncryptionService encryptionService;
@Inject
UserService userService;
public PasswordRecoveryCallbackPage(PageParameters params) {
String email = params.get(PARAM_EMAIL).toString();
String token = params.get(PARAM_TOKEN).toString();
final User user = userDAO.findByEmail(email);
if (user == null) {
throw new DisplayException("email not found");
}
if (user.getRecoverPasswordToken() == null
|| !user.getRecoverPasswordToken().equals(token)) {
throw new DisplayException("invalid token");
}
if (user.getRecoverPasswordTokenDate().before(
DateUtils.addDays(Calendar.getInstance().getTime(), -2))) {
throw new DisplayException("token expired");
}
final IModel<String> password = new Model<String>();
final IModel<String> confirm = new Model<String>();
add(new BootstrapFeedbackPanel("feedback"));
Form<Void> form = new Form<Void>("form") {
@Override
protected void onSubmit() {
String passwd = password.getObject();
if (StringUtils.equals(passwd, confirm.getObject())) {
byte[] password = encryptionService.getEncryptedPassword(
passwd, user.getSalt());
user.setPassword(password);
user.setApiKey(userService.generateApiKey(user));
user.setRecoverPasswordToken(null);
user.setRecoverPasswordTokenDate(null);
userDAO.update(user);
info("Password saved.");
} else {
error("Passwords do not match.");
}
}
};
add(form);
form.add(new PasswordTextField("password", password).setResetPassword(
true).add(StringValidator.minimumLength(6)));
form.add(new PasswordTextField("confirm", confirm).setResetPassword(
true).add(StringValidator.minimumLength(6)));
form.add(new BookmarkablePageLink<Void>("cancel", HomePage.class));
}
}
| apache-2.0 |
gustavoanatoly/hbase | hbase-client/src/main/java/org/apache/hadoop/hbase/AsyncMetaTableAccessor.java | 24378 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import static org.apache.hadoop.hbase.TableName.META_TABLE_NAME;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.SortedMap;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.MetaTableAccessor.CollectingVisitor;
import org.apache.hadoop.hbase.MetaTableAccessor.QueryType;
import org.apache.hadoop.hbase.MetaTableAccessor.Visitor;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.client.Consistency;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.RawAsyncTable;
import org.apache.hadoop.hbase.client.RawScanResultConsumer;
import org.apache.hadoop.hbase.client.RegionReplicaUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.TableState;
import org.apache.hadoop.hbase.client.Scan.ReadType;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.Pair;
/**
* The asynchronous meta table accessor. Used to read/write region and assignment information store
* in <code>hbase:meta</code>.
*/
@InterfaceAudience.Private
public class AsyncMetaTableAccessor {
private static final Log LOG = LogFactory.getLog(AsyncMetaTableAccessor.class);
/** The delimiter for meta columns for replicaIds > 0 */
private static final char META_REPLICA_ID_DELIMITER = '_';
/** A regex for parsing server columns from meta. See above javadoc for meta layout */
private static final Pattern SERVER_COLUMN_PATTERN = Pattern
.compile("^server(_[0-9a-fA-F]{4})?$");
public static CompletableFuture<Boolean> tableExists(RawAsyncTable metaTable, TableName tableName) {
if (tableName.equals(META_TABLE_NAME)) {
return CompletableFuture.completedFuture(true);
}
return getTableState(metaTable, tableName).thenApply(Optional::isPresent);
}
public static CompletableFuture<Optional<TableState>> getTableState(RawAsyncTable metaTable,
TableName tableName) {
CompletableFuture<Optional<TableState>> future = new CompletableFuture<>();
Get get = new Get(tableName.getName()).addColumn(getTableFamily(), getStateColumn());
long time = EnvironmentEdgeManager.currentTime();
try {
get.setTimeRange(0, time);
metaTable.get(get).whenComplete((result, error) -> {
if (error != null) {
future.completeExceptionally(error);
return;
}
try {
future.complete(getTableState(result));
} catch (IOException e) {
future.completeExceptionally(e);
}
});
} catch (IOException ioe) {
future.completeExceptionally(ioe);
}
return future;
}
/**
* Returns the HRegionLocation from meta for the given region
* @param metaTable
* @param regionName region we're looking for
* @return HRegionLocation for the given region
*/
public static CompletableFuture<Optional<HRegionLocation>> getRegionLocation(
RawAsyncTable metaTable, byte[] regionName) {
CompletableFuture<Optional<HRegionLocation>> future = new CompletableFuture<>();
try {
HRegionInfo parsedRegionInfo = MetaTableAccessor.parseRegionInfoFromRegionName(regionName);
metaTable.get(
new Get(MetaTableAccessor.getMetaKeyForRegion(parsedRegionInfo))
.addFamily(HConstants.CATALOG_FAMILY)).whenComplete(
(r, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
future.complete(getRegionLocations(r).map(
locations -> locations.getRegionLocation(parsedRegionInfo.getReplicaId())));
});
} catch (IOException parseEx) {
LOG.warn("Failed to parse the passed region name: " + Bytes.toStringBinary(regionName));
future.completeExceptionally(parseEx);
}
return future;
}
/**
* Returns the HRegionLocation from meta for the given encoded region name
* @param metaTable
* @param encodedRegionName region we're looking for
* @return HRegionLocation for the given region
*/
public static CompletableFuture<Optional<HRegionLocation>> getRegionLocationWithEncodedName(
RawAsyncTable metaTable, byte[] encodedRegionName) {
CompletableFuture<Optional<HRegionLocation>> future = new CompletableFuture<>();
metaTable.scanAll(new Scan().setReadType(ReadType.PREAD).addFamily(HConstants.CATALOG_FAMILY))
.whenComplete(
(results, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
String encodedRegionNameStr = Bytes.toString(encodedRegionName);
results
.stream()
.filter(result -> !result.isEmpty())
.filter(result -> MetaTableAccessor.getHRegionInfo(result) != null)
.forEach(
result -> {
getRegionLocations(result).ifPresent(
locations -> {
for (HRegionLocation location : locations.getRegionLocations()) {
if (location != null
&& encodedRegionNameStr.equals(location.getRegionInfo()
.getEncodedName())) {
future.complete(Optional.of(location));
return;
}
}
});
});
future.complete(Optional.empty());
});
return future;
}
private static Optional<TableState> getTableState(Result r) throws IOException {
Cell cell = r.getColumnLatestCell(getTableFamily(), getStateColumn());
if (cell == null) return Optional.empty();
try {
return Optional.of(TableState.parseFrom(
TableName.valueOf(r.getRow()),
Arrays.copyOfRange(cell.getValueArray(), cell.getValueOffset(), cell.getValueOffset()
+ cell.getValueLength())));
} catch (DeserializationException e) {
throw new IOException("Failed to parse table state from result: " + r, e);
}
}
/**
* Used to get all region locations for the specific table.
* @param metaTable
* @param tableName table we're looking for, can be null for getting all regions
* @return the list of region locations. The return value will be wrapped by a
* {@link CompletableFuture}.
*/
public static CompletableFuture<List<HRegionLocation>> getTableHRegionLocations(
RawAsyncTable metaTable, final Optional<TableName> tableName) {
CompletableFuture<List<HRegionLocation>> future = new CompletableFuture<>();
getTableRegionsAndLocations(metaTable, tableName, true).whenComplete(
(locations, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else if (locations == null || locations.isEmpty()) {
future.complete(Collections.emptyList());
} else {
List<HRegionLocation> regionLocations = locations.stream()
.map(loc -> new HRegionLocation(loc.getFirst(), loc.getSecond()))
.collect(Collectors.toList());
future.complete(regionLocations);
}
});
return future;
}
/**
* Used to get table regions' info and server.
* @param metaTable
* @param tableName table we're looking for, can be null for getting all regions
* @param excludeOfflinedSplitParents don't return split parents
* @return the list of regioninfos and server. The return value will be wrapped by a
* {@link CompletableFuture}.
*/
private static CompletableFuture<List<Pair<HRegionInfo, ServerName>>> getTableRegionsAndLocations(
RawAsyncTable metaTable, final Optional<TableName> tableName,
final boolean excludeOfflinedSplitParents) {
CompletableFuture<List<Pair<HRegionInfo, ServerName>>> future = new CompletableFuture<>();
if (tableName.filter((t) -> t.equals(TableName.META_TABLE_NAME)).isPresent()) {
future.completeExceptionally(new IOException(
"This method can't be used to locate meta regions;" + " use MetaTableLocator instead"));
}
// Make a version of CollectingVisitor that collects HRegionInfo and ServerAddress
CollectingVisitor<Pair<HRegionInfo, ServerName>> visitor = new CollectingVisitor<Pair<HRegionInfo, ServerName>>() {
private Optional<RegionLocations> current = null;
@Override
public boolean visit(Result r) throws IOException {
current = getRegionLocations(r);
if (!current.isPresent() || current.get().getRegionLocation().getRegionInfo() == null) {
LOG.warn("No serialized HRegionInfo in " + r);
return true;
}
HRegionInfo hri = current.get().getRegionLocation().getRegionInfo();
if (excludeOfflinedSplitParents && hri.isSplitParent()) return true;
// Else call super and add this Result to the collection.
return super.visit(r);
}
@Override
void add(Result r) {
if (!current.isPresent()) {
return;
}
for (HRegionLocation loc : current.get().getRegionLocations()) {
if (loc != null) {
this.results.add(new Pair<HRegionInfo, ServerName>(loc.getRegionInfo(), loc
.getServerName()));
}
}
}
};
scanMeta(metaTable, tableName, QueryType.REGION, visitor).whenComplete((v, error) -> {
if (error != null) {
future.completeExceptionally(error);
return;
}
future.complete(visitor.getResults());
});
return future;
}
/**
* Performs a scan of META table for given table.
* @param metaTable
* @param tableName table withing we scan
* @param type scanned part of meta
* @param visitor Visitor invoked against each row
*/
private static CompletableFuture<Void> scanMeta(RawAsyncTable metaTable,
Optional<TableName> tableName, QueryType type, final Visitor visitor) {
return scanMeta(metaTable, getTableStartRowForMeta(tableName, type),
getTableStopRowForMeta(tableName, type), type, Integer.MAX_VALUE, visitor);
}
/**
* Performs a scan of META table for given table.
* @param metaTable
* @param startRow Where to start the scan
* @param stopRow Where to stop the scan
* @param type scanned part of meta
* @param maxRows maximum rows to return
* @param visitor Visitor invoked against each row
*/
private static CompletableFuture<Void> scanMeta(RawAsyncTable metaTable, Optional<byte[]> startRow,
Optional<byte[]> stopRow, QueryType type, int maxRows, final Visitor visitor) {
int rowUpperLimit = maxRows > 0 ? maxRows : Integer.MAX_VALUE;
Scan scan = getMetaScan(metaTable, rowUpperLimit);
for (byte[] family : type.getFamilies()) {
scan.addFamily(family);
}
startRow.ifPresent(scan::withStartRow);
stopRow.ifPresent(scan::withStopRow);
if (LOG.isTraceEnabled()) {
LOG.trace("Scanning META" + " starting at row=" + Bytes.toStringBinary(scan.getStartRow())
+ " stopping at row=" + Bytes.toStringBinary(scan.getStopRow()) + " for max="
+ rowUpperLimit + " with caching=" + scan.getCaching());
}
CompletableFuture<Void> future = new CompletableFuture<Void>();
metaTable.scan(scan, new MetaTableRawScanResultConsumer(rowUpperLimit, visitor, future));
return future;
}
private static final class MetaTableRawScanResultConsumer implements RawScanResultConsumer {
private int currentRowCount;
private final int rowUpperLimit;
private final Visitor visitor;
private final CompletableFuture<Void> future;
MetaTableRawScanResultConsumer(int rowUpperLimit, Visitor visitor, CompletableFuture<Void> future) {
this.rowUpperLimit = rowUpperLimit;
this.visitor = visitor;
this.future = future;
this.currentRowCount = 0;
}
@Override
public void onError(Throwable error) {
future.completeExceptionally(error);
}
@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NONNULL_PARAM_VIOLATION",
justification = "https://github.com/findbugsproject/findbugs/issues/79")
public void onComplete() {
future.complete(null);
}
@Override
public void onNext(Result[] results, ScanController controller) {
for (Result result : results) {
try {
if (!visitor.visit(result)) {
controller.terminate();
}
} catch (IOException e) {
future.completeExceptionally(e);
controller.terminate();
}
if (++currentRowCount >= rowUpperLimit) {
controller.terminate();
}
}
}
}
private static Scan getMetaScan(RawAsyncTable metaTable, int rowUpperLimit) {
Scan scan = new Scan();
int scannerCaching = metaTable.getConfiguration().getInt(HConstants.HBASE_META_SCANNER_CACHING,
HConstants.DEFAULT_HBASE_META_SCANNER_CACHING);
if (metaTable.getConfiguration().getBoolean(HConstants.USE_META_REPLICAS,
HConstants.DEFAULT_USE_META_REPLICAS)) {
scan.setConsistency(Consistency.TIMELINE);
}
if (rowUpperLimit <= scannerCaching) {
scan.setLimit(rowUpperLimit);
}
int rows = Math.min(rowUpperLimit, scannerCaching);
scan.setCaching(rows);
return scan;
}
/**
* Returns an HRegionLocationList extracted from the result.
* @return an HRegionLocationList containing all locations for the region range or null if we
* can't deserialize the result.
*/
private static Optional<RegionLocations> getRegionLocations(final Result r) {
if (r == null) return Optional.empty();
Optional<HRegionInfo> regionInfo = getHRegionInfo(r, getRegionInfoColumn());
if (!regionInfo.isPresent()) return Optional.empty();
List<HRegionLocation> locations = new ArrayList<HRegionLocation>(1);
NavigableMap<byte[], NavigableMap<byte[], byte[]>> familyMap = r.getNoVersionMap();
locations.add(getRegionLocation(r, regionInfo.get(), 0));
NavigableMap<byte[], byte[]> infoMap = familyMap.get(getCatalogFamily());
if (infoMap == null) return Optional.of(new RegionLocations(locations));
// iterate until all serverName columns are seen
int replicaId = 0;
byte[] serverColumn = getServerColumn(replicaId);
SortedMap<byte[], byte[]> serverMap = null;
serverMap = infoMap.tailMap(serverColumn, false);
if (serverMap.isEmpty()) return Optional.of(new RegionLocations(locations));
for (Map.Entry<byte[], byte[]> entry : serverMap.entrySet()) {
replicaId = parseReplicaIdFromServerColumn(entry.getKey());
if (replicaId < 0) {
break;
}
HRegionLocation location = getRegionLocation(r, regionInfo.get(), replicaId);
// In case the region replica is newly created, it's location might be null. We usually do not
// have HRL's in RegionLocations object with null ServerName. They are handled as null HRLs.
if (location == null || location.getServerName() == null) {
locations.add(null);
} else {
locations.add(location);
}
}
return Optional.of(new RegionLocations(locations));
}
/**
* Returns the HRegionLocation parsed from the given meta row Result
* for the given regionInfo and replicaId. The regionInfo can be the default region info
* for the replica.
* @param r the meta row result
* @param regionInfo RegionInfo for default replica
* @param replicaId the replicaId for the HRegionLocation
* @return HRegionLocation parsed from the given meta row Result for the given replicaId
*/
private static HRegionLocation getRegionLocation(final Result r, final HRegionInfo regionInfo,
final int replicaId) {
Optional<ServerName> serverName = getServerName(r, replicaId);
long seqNum = getSeqNumDuringOpen(r, replicaId);
HRegionInfo replicaInfo = RegionReplicaUtil.getRegionInfoForReplica(regionInfo, replicaId);
return new HRegionLocation(replicaInfo, serverName.orElse(null), seqNum);
}
/**
* Returns a {@link ServerName} from catalog table {@link Result}.
* @param r Result to pull from
* @return A ServerName instance.
*/
private static Optional<ServerName> getServerName(final Result r, final int replicaId) {
byte[] serverColumn = getServerColumn(replicaId);
Cell cell = r.getColumnLatestCell(getCatalogFamily(), serverColumn);
if (cell == null || cell.getValueLength() == 0) return Optional.empty();
String hostAndPort = Bytes.toString(cell.getValueArray(), cell.getValueOffset(),
cell.getValueLength());
byte[] startcodeColumn = getStartCodeColumn(replicaId);
cell = r.getColumnLatestCell(getCatalogFamily(), startcodeColumn);
if (cell == null || cell.getValueLength() == 0) return Optional.empty();
try {
return Optional.of(ServerName.valueOf(hostAndPort,
Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength())));
} catch (IllegalArgumentException e) {
LOG.error("Ignoring invalid region for server " + hostAndPort + "; cell=" + cell, e);
return Optional.empty();
}
}
/**
* The latest seqnum that the server writing to meta observed when opening the region.
* E.g. the seqNum when the result of {@link #getServerName(Result, int)} was written.
* @param r Result to pull the seqNum from
* @return SeqNum, or HConstants.NO_SEQNUM if there's no value written.
*/
private static long getSeqNumDuringOpen(final Result r, final int replicaId) {
Cell cell = r.getColumnLatestCell(getCatalogFamily(), getSeqNumColumn(replicaId));
if (cell == null || cell.getValueLength() == 0) return HConstants.NO_SEQNUM;
return Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
}
/**
* @param tableName table we're working with
* @return start row for scanning META according to query type
*/
private static Optional<byte[]> getTableStartRowForMeta(Optional<TableName> tableName,
QueryType type) {
return tableName.map((table) -> {
switch (type) {
case REGION:
byte[] startRow = new byte[table.getName().length + 2];
System.arraycopy(table.getName(), 0, startRow, 0, table.getName().length);
startRow[startRow.length - 2] = HConstants.DELIMITER;
startRow[startRow.length - 1] = HConstants.DELIMITER;
return startRow;
case ALL:
case TABLE:
default:
return table.getName();
}
});
}
/**
* @param tableName table we're working with
* @return stop row for scanning META according to query type
*/
private static Optional<byte[]> getTableStopRowForMeta(Optional<TableName> tableName,
QueryType type) {
return tableName.map((table) -> {
final byte[] stopRow;
switch (type) {
case REGION:
stopRow = new byte[table.getName().length + 3];
System.arraycopy(table.getName(), 0, stopRow, 0, table.getName().length);
stopRow[stopRow.length - 3] = ' ';
stopRow[stopRow.length - 2] = HConstants.DELIMITER;
stopRow[stopRow.length - 1] = HConstants.DELIMITER;
break;
case ALL:
case TABLE:
default:
stopRow = new byte[table.getName().length + 1];
System.arraycopy(table.getName(), 0, stopRow, 0, table.getName().length);
stopRow[stopRow.length - 1] = ' ';
break;
}
return stopRow;
});
}
/**
* Returns the HRegionInfo object from the column {@link HConstants#CATALOG_FAMILY} and
* <code>qualifier</code> of the catalog table result.
* @param r a Result object from the catalog table scan
* @param qualifier Column family qualifier
* @return An HRegionInfo instance.
*/
private static Optional<HRegionInfo> getHRegionInfo(final Result r, byte[] qualifier) {
Cell cell = r.getColumnLatestCell(getCatalogFamily(), qualifier);
if (cell == null) return Optional.empty();
return Optional.ofNullable(HRegionInfo.parseFromOrNull(cell.getValueArray(),
cell.getValueOffset(), cell.getValueLength()));
}
/**
* Returns the column family used for meta columns.
* @return HConstants.CATALOG_FAMILY.
*/
private static byte[] getCatalogFamily() {
return HConstants.CATALOG_FAMILY;
}
/**
* Returns the column family used for table columns.
* @return HConstants.TABLE_FAMILY.
*/
private static byte[] getTableFamily() {
return HConstants.TABLE_FAMILY;
}
/**
* Returns the column qualifier for serialized region info
* @return HConstants.REGIONINFO_QUALIFIER
*/
private static byte[] getRegionInfoColumn() {
return HConstants.REGIONINFO_QUALIFIER;
}
/**
* Returns the column qualifier for serialized table state
* @return HConstants.TABLE_STATE_QUALIFIER
*/
private static byte[] getStateColumn() {
return HConstants.TABLE_STATE_QUALIFIER;
}
/**
* Returns the column qualifier for server column for replicaId
* @param replicaId the replicaId of the region
* @return a byte[] for server column qualifier
*/
private static byte[] getServerColumn(int replicaId) {
return replicaId == 0
? HConstants.SERVER_QUALIFIER
: Bytes.toBytes(HConstants.SERVER_QUALIFIER_STR + META_REPLICA_ID_DELIMITER
+ String.format(HRegionInfo.REPLICA_ID_FORMAT, replicaId));
}
/**
* Returns the column qualifier for server start code column for replicaId
* @param replicaId the replicaId of the region
* @return a byte[] for server start code column qualifier
*/
private static byte[] getStartCodeColumn(int replicaId) {
return replicaId == 0
? HConstants.STARTCODE_QUALIFIER
: Bytes.toBytes(HConstants.STARTCODE_QUALIFIER_STR + META_REPLICA_ID_DELIMITER
+ String.format(HRegionInfo.REPLICA_ID_FORMAT, replicaId));
}
/**
* Returns the column qualifier for seqNum column for replicaId
* @param replicaId the replicaId of the region
* @return a byte[] for seqNum column qualifier
*/
private static byte[] getSeqNumColumn(int replicaId) {
return replicaId == 0
? HConstants.SEQNUM_QUALIFIER
: Bytes.toBytes(HConstants.SEQNUM_QUALIFIER_STR + META_REPLICA_ID_DELIMITER
+ String.format(HRegionInfo.REPLICA_ID_FORMAT, replicaId));
}
/**
* Parses the replicaId from the server column qualifier. See top of the class javadoc
* for the actual meta layout
* @param serverColumn the column qualifier
* @return an int for the replicaId
*/
private static int parseReplicaIdFromServerColumn(byte[] serverColumn) {
String serverStr = Bytes.toString(serverColumn);
Matcher matcher = SERVER_COLUMN_PATTERN.matcher(serverStr);
if (matcher.matches() && matcher.groupCount() > 0) {
String group = matcher.group(1);
if (group != null && group.length() > 0) {
return Integer.parseInt(group.substring(1), 16);
} else {
return 0;
}
}
return -1;
}
}
| apache-2.0 |
everttigchelaar/camel-svn | examples/camel-example-cxf/src/main/java/org/apache/camel/example/cxf/provider/GreeterProvider.java | 1797 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.example.cxf.provider;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.Provider;
import javax.xml.ws.Service.Mode;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceProvider;
// START SNIPPET: e1
@WebServiceProvider()
@ServiceMode(Mode.MESSAGE)
// END SNIPPET: e1
/**
* This class is used by Camel just for getting the endpoint configuration
* parameters. All the requests aimed at this class are intercepted and routed
* to the camel route specified. The route has to set the appropriate response
* message for the service to work.
*/
// START SNIPPET: e2
public class GreeterProvider implements Provider<SOAPMessage> {
public SOAPMessage invoke(SOAPMessage message) {
// Requests should not come here as the Camel route will
// intercept the call before this is invoked.
throw new UnsupportedOperationException("Placeholder method");
}
}
// END SNIPPET: e2
| apache-2.0 |
gitblit/iciql | src/test/java/com/iciql/test/TransactionTest.java | 3342 | /*
* Copyright 2012 Frédéric Gaillard.
*
* 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.iciql.test;
import com.iciql.Db;
import com.iciql.IciqlException;
import com.iciql.test.models.CategoryAnnotationOnly;
import com.iciql.test.models.ProductAnnotationOnlyWithForeignKey;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
/**
* Tests of transactions.
*/
public class TransactionTest {
/**
* This object represents a database (actually a connection to the
* database).
*/
private Db db;
@Before
public void setUp() {
db = IciqlSuite.openNewDb();
// tables creation
db.from(new CategoryAnnotationOnly());
db.from(new ProductAnnotationOnlyWithForeignKey());
startTransactionMode();
}
@After
public void tearDown() {
endTransactionMode();
db.dropTable(ProductAnnotationOnlyWithForeignKey.class);
db.dropTable(CategoryAnnotationOnly.class);
db.close();
}
@Test
public void testTransaction() {
// insert in 2 tables inside a transaction
// insertAll don't use save point in this transaction
db.insertAll(CategoryAnnotationOnly.getList());
db.insertAll(ProductAnnotationOnlyWithForeignKey.getList());
// don't commit changes
try {
db.getConnection().rollback();
} catch (SQLException e) {
throw new IciqlException(e, "Can't rollback");
}
ProductAnnotationOnlyWithForeignKey p = new ProductAnnotationOnlyWithForeignKey();
long count1 = db.from(p).selectCount();
CategoryAnnotationOnly c = new CategoryAnnotationOnly();
long count2 = db.from(c).selectCount();
// verify changes aren't committed
assertEquals(count1, 0L);
assertEquals(count2, 0L);
}
/**
* Helper to set transaction mode
*/
private void startTransactionMode() {
db.setSkipCreate(true);
db.setAutoSavePoint(false);
try {
db.getConnection().setAutoCommit(false);
} catch (SQLException e) {
throw new IciqlException(e, "Could not change auto-commit mode");
}
}
/**
* Helper to return to initial mode
*/
private void endTransactionMode() {
try {
db.getConnection().setAutoCommit(true);
} catch (SQLException e) {
throw new IciqlException(e, "Could not change auto-commit mode");
}
// returns to initial states
db.setSkipCreate(false);
db.setAutoSavePoint(true);
}
}
| apache-2.0 |
kozaxinan/OnePlus-One-Screen-Fix | app/src/main/java/com/kozaxinan/fixoposcreen/iab/Donation.java | 2580 | /*
* Copyright (C) 2014 AChep@xda <artemchep@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.kozaxinan.fixoposcreen.iab;
import java.util.Objects;
/**
* The helper class of donation item.
*
* @author Artem Chepurnoy
*/
public class Donation {
public final int amount;
public final String sku;
public final String text;
public Donation(int amount, String text) {
this.amount = amount;
this.text = text;
// Notice that all of them are defined in
// my Play Store's account!
this.sku = "donation_" + amount;
}
// /**
// * {@inheritDoc}
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(9, 51)
// .append(amount)
// .append(text)
// .append(sku)
// .toHashCode();
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public boolean equals(Object o) {
// if (o == null)
// return false;
// if (o == this)
// return true;
// if (!(o instanceof Donation))
// return false;
//
// Donation donation = (Donation) o;
// return new EqualsBuilder()
// .append(amount, donation.amount)
// .append(text, donation.text)
// .append(sku, donation.sku)
// .isEquals();
// }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Donation)) {
return false;
}
Donation donation = (Donation) o;
return amount == donation.amount &&
Objects.equals(sku, donation.sku) &&
Objects.equals(text, donation.text);
}
@Override
public int hashCode() {
return Objects.hash(amount, sku, text);
}
}
| apache-2.0 |
beetsolutions/opengl_circle | app/src/test/java/com/beetsolutions/opengl/circle/ExampleUnitTest.java | 409 | package com.beetsolutions.opengl.circle;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
geekdos/Personal_Labs | SOALab/GestionDesNotes/src/com/geekdos/client/Getvalidation.java | 719 |
package com.geekdos.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java pour getvalidation complex type.
*
* <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe.
*
* <pre>
* <complexType name="getvalidation">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getvalidation")
public class Getvalidation {
}
| apache-2.0 |
Lucidastar/hodgepodgeForAndroid | app/src/main/java/com/lucidastar/hodgepodge/utils/fragment/NavigationManagerFactory.java | 662 | package com.lucidastar.hodgepodge.utils.fragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
/**
* Created by qiuyouzone on 2019/4/30.
*/
public final class NavigationManagerFactory {
private NavigationManagerFactory() {
}
public static NavigationManager<Fragment> createV4(AppCompatActivity activity, int layoutId) {
return new TabFragment(activity, layoutId);
}
public static NavigationManager<Fragment> createV4Pager(AppCompatActivity activity, ViewPager viewPager) {
return new ViewPagerFragment(activity, viewPager);
}
}
| apache-2.0 |
osglworks/java-tool | src/test/java/org/osgl/util/BigLinesLineCountTest.java | 2014 | package org.osgl.util;
/*-
* #%L
* Java Tool
* %%
* Copyright (C) 2014 - 2019 OSGL (Open Source General Library)
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
@RunWith(Enclosed.class)
public abstract class BigLinesLineCountTest {
public static abstract class CountTestBase extends BigLineTestBase {
public CountTestBase(int lines) {
super(lines);
}
@Test
public void testLineCount() {
eq(lines, bigLines.lines());
}
}
public static class EmptyFileLineCountTest extends CountTestBase {
public EmptyFileLineCountTest() {
super(0);
}
@Test
public void testIteratingWithBigBuffer() {
int i = 0;
for (String s : bigLines.asIterable(100)) {
eq(i++, Integer.parseInt(s));
}
eq(0, i);
}
}
public static class OneLineFileLineCountTest extends CountTestBase {
public OneLineFileLineCountTest() {
super(1);
}
}
public static class TwoLinesFileLineCountTest extends CountTestBase {
public TwoLinesFileLineCountTest() {
super(2);
}
}
public static class MultipleLinesFileLineCountTest extends CountTestBase {
public MultipleLinesFileLineCountTest() {
super(100);
}
}
}
| apache-2.0 |
clafonta/canyon | src/dao/org/tll/canyon/dao/hibernate/BaseDaoHibernate.java | 1791 | package org.tll.canyon.dao.hibernate;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.tll.canyon.dao.Dao;
/**
* This class serves as the Base class for all other Daos - namely to hold
* common methods that they might all use. Can be used for standard CRUD
* operations.</p>
*
* <p><a href="BaseDaoHibernate.java.html"><i>View Source</i></a></p>
*
* @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
*/
public class BaseDaoHibernate extends HibernateDaoSupport implements Dao {
protected final Log log = LogFactory.getLog(getClass());
/**
* @see org.tll.canyon.dao.Dao#saveObject(java.lang.Object)
*/
public void saveObject(Object o) {
getHibernateTemplate().saveOrUpdate(o);
}
/**
* @see org.tll.canyon.dao.Dao#getObject(java.lang.Class, java.io.Serializable)
*/
public Object getObject(Class clazz, Serializable id) {
Object o = getHibernateTemplate().get(clazz, id);
if (o == null) {
throw new ObjectRetrievalFailureException(clazz, id);
}
return o;
}
/**
* @see org.tll.canyon.dao.Dao#getObjects(java.lang.Class)
*/
public List getObjects(Class clazz) {
return getHibernateTemplate().loadAll(clazz);
}
/**
* @see org.tll.canyon.dao.Dao#removeObject(java.lang.Class, java.io.Serializable)
*/
public void removeObject(Class clazz, Serializable id) {
getHibernateTemplate().delete(getObject(clazz, id));
}
}
| apache-2.0 |
wumingguo/avarua | casual/account/service/src/test/java/com/mingguo/avarua/casual/account/test/common/mess/concurrent/Charpter001Test.java | 2142 | package com.mingguo.avarua.casual.account.test.common.mess.concurrent;
import org.junit.Test;
/**
* Created by mingguo.wu on 2016/11/15.
*/
public class Charpter001Test {
@Test
public void test121() {
System.out.println(Thread.currentThread().getName());
}
@Test
public void test122() throws InterruptedException{
MyThread1 myThread = new MyThread1();
System.out.println("begin == " + myThread.isAlive());
myThread.start();
Thread.sleep(1000);
System.out.println("end == " + myThread.isAlive());
}
@Test
public void test123() {
CountOperate countOperate = new CountOperate();
Thread t1 = new Thread(countOperate);
System.out.println("main begin t1 isAlive=" + t1.isAlive());
t1.setName("A");
t1.start();;
System.out.println("main end t1 isAlive=" + t1.isAlive());
}
class MyThread2 extends Thread {
}
class CountOperate extends Thread {
public CountOperate() {
System.out.println("CountOpearate---begin");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread.isAlive()=" + Thread.currentThread().isAlive());
System.out.println("this.getName()=" + this.getName());
System.out.println("this.isAlive()=" + this.isAlive());
System.out.println("CountOpearate---end");
}
@Override
public void run() {
System.out.println("run---begin");
System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
System.out.println("Thread.currentThread.isAlive()=" + Thread.currentThread().isAlive());
System.out.println("this.getName()=" + this.getName());
System.out.println("this.isAlive()=" + this.isAlive());
System.out.println("run---end");
}
}
class MyThread1 extends Thread {
@Override
public void run() {
System.out.println("run=" + this.isAlive());
}
}
}
| apache-2.0 |
everttigchelaar/camel-svn | tests/camel-itest/src/test/java/org/apache/camel/itest/issues/BeanCallDerivedClassTest.java | 1684 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.itest.issues;
import org.apache.camel.test.junit4.CamelSpringTestSupport;
import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
/**
* @version
*/
public class BeanCallDerivedClassTest extends CamelSpringTestSupport {
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/itest/issues/BeanCallDerivedClassTest-context.xml");
}
@Test
public void testCallBean() throws Exception {
DerivedClass derived = context.getRegistry().lookup("derived", DerivedClass.class);
template.sendBody("direct:start", "Hello World");
assertEquals("Hello World", derived.getBody());
}
}
| apache-2.0 |
typesafe-query/typesafe-query | typesafe-query-core/src/test/java/com/github/typesafe_query/query/internal/expression/OrExpTest.java | 2749 | /**
*
*/
package com.github.typesafe_query.query.internal.expression;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.*;
import org.junit.Test;
import com.github.typesafe_query.meta.DBTable;
import com.github.typesafe_query.meta.impl.DBTableImpl;
import com.github.typesafe_query.meta.impl.NumberDBColumnImpl;
import com.github.typesafe_query.meta.impl.StringDBColumnImpl;
import com.github.typesafe_query.query.Exp;
import com.github.typesafe_query.query.QueryContext;
import com.github.typesafe_query.query.internal.DefaultQueryContext;
/**
* @author Takahiko Sato(MOSA architect Inc.)
*
*/
public class OrExpTest {
@Test
public void ok(){
DBTable t = new DBTableImpl("table1");
Exp[] exps = new Exp[2];
exps[0] = new LtExp<Integer>(new NumberDBColumnImpl<Integer>(t, "age"), 245);
exps[1] = new EqExp<String>(new StringDBColumnImpl(t, "name"), "piyo");
Exp exp = new OrExp(exps);
QueryContext context = new DefaultQueryContext(t);
String actual = exp.getSQL(context);
assertThat(actual, notNullValue());
assertThat(actual,is("(table1.age < 245 OR table1.name = 'piyo')"));
}
@Test
public void ok_andInAnd(){
DBTable t = new DBTableImpl("table1");
Exp[] inner = new Exp[3];
inner[0] = new LtExp<Integer>(new NumberDBColumnImpl<Integer>(t, "age"), 245);
inner[1] = new EqExp<String>(new StringDBColumnImpl(t, "name1"), "piyo");
inner[2] = new LikeExp(new StringDBColumnImpl(t, "name2"), "%piyo");
Exp[] exps = new Exp[2];
exps[0] = new LtExp<Integer>(new NumberDBColumnImpl<Integer>(t, "age"), 12);
exps[1] = new OrExp(inner);
Exp exp = new OrExp(exps);
QueryContext context = new DefaultQueryContext(t);
String actual = exp.getSQL(context);
assertThat(actual, notNullValue());
assertThat(actual,is("(table1.age < 12 OR (table1.age < 245 OR table1.name1 = 'piyo' OR table1.name2 LIKE '%piyo' ESCAPE '!'))"));
}
@Test(expected=NullPointerException.class)
public void ng_expsNull(){
Exp[] exps = null;
new OrExp(exps);
}
@Test
public void ok_exps_0(){
DBTable t = new DBTableImpl("table1");
Exp[] exps = new Exp[0];
Exp exp = new OrExp(exps);
QueryContext context = new DefaultQueryContext(t);
String actual = exp.getSQL(context);
assertNull(actual);
}
@Test
public void ok_exps_1(){
DBTable t = new DBTableImpl("table1");
Exp[] exps = new Exp[1];
exps[0] = new LtExp<Long>(new NumberDBColumnImpl<Long>(t, "age"), 245L);
Exp exp = new OrExp(exps);
QueryContext context = new DefaultQueryContext(t);
String actual = exp.getSQL(context);
assertThat(actual, notNullValue());
assertThat(actual,is("table1.age < 245"));
}
}
| apache-2.0 |
derekhiggins/ovirt-engine | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/widget/host/BondPanel.java | 1286 | package org.ovirt.engine.ui.webadmin.widget.host;
import org.ovirt.engine.ui.common.widget.TogglePanel;
import org.ovirt.engine.ui.uicommonweb.models.hosts.HostInterfaceLineModel;
import org.ovirt.engine.ui.webadmin.gin.ClientGinjectorProvider;
import org.ovirt.engine.ui.webadmin.widget.renderer.HostInterfaceBondNameRenderer;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.BorderStyle;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
public class BondPanel extends TogglePanel {
public BondPanel(HostInterfaceLineModel lineModel) {
super(lineModel);
clear();
Style style = getElement().getStyle();
style.setBorderColor("white"); //$NON-NLS-1$
style.setBorderWidth(1, Unit.PX);
style.setBorderStyle(BorderStyle.SOLID);
if (lineModel.getIsBonded()) {
add(getCheckBox());
// Bond icon
add(new Image(ClientGinjectorProvider.instance().getApplicationResources().splitImage()));
// Bond name
add(new Label(new HostInterfaceBondNameRenderer().render(lineModel)));
} else {
add(new Label("")); //$NON-NLS-1$
}
}
}
| apache-2.0 |
HuangLS/neo4j | enterprise/com/src/main/java/org/neo4j/com/CommittedTransactionSerializer.java | 2612 | /*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.com;
import org.jboss.netty.buffer.ChannelBuffer;
import java.io.IOException;
import org.neo4j.helpers.collection.Visitor;
import org.neo4j.kernel.impl.transaction.CommittedTransactionRepresentation;
import org.neo4j.kernel.impl.transaction.log.CommandWriter;
import org.neo4j.kernel.impl.transaction.log.entry.LogEntryCommit;
import org.neo4j.kernel.impl.transaction.log.entry.LogEntryStart;
import org.neo4j.kernel.impl.transaction.log.entry.LogEntryWriter;
/**
* Serialized {@link CommittedTransactionRepresentation transactions} to raw bytes on the {@link ChannelBuffer
* network}.
* One serializer can be instantiated per response and is able to serialize one or many transactions.
*/
public class CommittedTransactionSerializer implements Visitor<CommittedTransactionRepresentation,IOException>
{
private final NetworkWritableLogChannel channel;
private final LogEntryWriter writer;
public CommittedTransactionSerializer( ChannelBuffer targetBuffer )
{
this.channel = new NetworkWritableLogChannel( targetBuffer );
this.writer = new LogEntryWriter( channel, new CommandWriter( channel ) );
}
@Override
public boolean visit( CommittedTransactionRepresentation tx ) throws IOException
{
LogEntryStart startEntry = tx.getStartEntry();
writer.writeStartEntry( startEntry.getMasterId(), startEntry.getLocalId(),
startEntry.getTimeWritten(), startEntry.getLastCommittedTxWhenTransactionStarted(),
startEntry.getAdditionalHeader() );
writer.serialize( tx.getTransactionRepresentation() );
LogEntryCommit commitEntry = tx.getCommitEntry();
writer.writeCommitEntry( commitEntry.getTxId(), commitEntry.getTimeWritten() );
return false;
}
}
| apache-2.0 |
softindex/datakernel | core-net/src/main/java/io/datakernel/net/UdpPacket.java | 2293 | /*
* Copyright (C) 2015 SoftIndex LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.datakernel.net;
import io.datakernel.bytebuf.ByteBuf;
import org.jetbrains.annotations.Nullable;
import java.net.InetSocketAddress;
import static io.datakernel.common.Preconditions.checkNotNull;
import static io.datakernel.common.Utils.nullify;
/**
* This class represents a UDP packet.
* Each message is routed from one machine to another based solely on information contained within that packet
*/
public final class UdpPacket {
/**
* The data buffer to send
*/
@Nullable
private ByteBuf buf;
/**
* The address to which the packet should be sent or from which it
* was received.
*/
private final InetSocketAddress inetSocketAddress;
private UdpPacket(@Nullable ByteBuf buf, InetSocketAddress inetSocketAddress) {
this.buf = buf;
this.inetSocketAddress = inetSocketAddress;
}
/**
* Creates a new instance of UDP packet
*
* @param buf the data buffer to send or which was received
* @param inetSocketAddress the address to which the packet should be send or from which it
* was received
*/
public static UdpPacket of(ByteBuf buf, InetSocketAddress inetSocketAddress) {
return new UdpPacket(buf, inetSocketAddress);
}
/**
* Returns the data buffer to send or which was received
*/
public ByteBuf getBuf() {
return checkNotNull(buf, "Using UdpPacket after recycling");
}
/**
* Returns the address to which the packet should be sent or from which it
* was received.
*/
public InetSocketAddress getSocketAddress() {
return inetSocketAddress;
}
/**
* Recycles data buffer. You should do it after use.
*/
public void recycle() {
buf = nullify(buf, ByteBuf::recycle);
}
}
| apache-2.0 |
JamesHe1990/hw3-jiacongh1 | hw3-jiacongh/src/main/java/org/cleartk/ne/type/NamedEntityMention.java | 6338 |
/* First created by JCasGen Tue Nov 12 02:38:07 EST 2013 */
package org.cleartk.ne.type;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.jcas.cas.TOP_Type;
import org.apache.uima.jcas.tcas.Annotation;
import org.cleartk.score.type.ScoredAnnotation;
/**
* Updated by JCasGen Tue Nov 19 00:48:18 EST 2013
* XML source: C:/Users/James_He/git/hw3-jiacongh1/hw3-jiacongh/src/main/resources/descriptors/EvaluationAnnotation.xml
* @generated */
public class NamedEntityMention extends ScoredAnnotation {
/** @generated
* @ordered
*/
@SuppressWarnings ("hiding")
public final static int typeIndexID = JCasRegistry.register(NamedEntityMention.class);
/** @generated
* @ordered
*/
@SuppressWarnings ("hiding")
public final static int type = typeIndexID;
/** @generated */
@Override
public int getTypeIndexID() {return typeIndexID;}
/** Never called. Disable default constructor
* @generated */
protected NamedEntityMention() {/* intentionally empty block */}
/** Internal - constructor used by generator
* @generated */
public NamedEntityMention(int addr, TOP_Type type) {
super(addr, type);
readObject();
}
/** @generated */
public NamedEntityMention(JCas jcas) {
super(jcas);
readObject();
}
/** @generated */
public NamedEntityMention(JCas jcas, int begin, int end) {
super(jcas);
setBegin(begin);
setEnd(end);
readObject();
}
/** <!-- begin-user-doc -->
* Write your own initialization here
* <!-- end-user-doc -->
@generated modifiable */
private void readObject() {/*default - does nothing empty block */}
//*--------------*
//* Feature: mentionType
/** getter for mentionType - gets
* @generated */
public String getMentionType() {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_mentionType == null)
jcasType.jcas.throwFeatMissing("mentionType", "org.cleartk.ne.type.NamedEntityMention");
return jcasType.ll_cas.ll_getStringValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_mentionType);}
/** setter for mentionType - sets
* @generated */
public void setMentionType(String v) {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_mentionType == null)
jcasType.jcas.throwFeatMissing("mentionType", "org.cleartk.ne.type.NamedEntityMention");
jcasType.ll_cas.ll_setStringValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_mentionType, v);}
//*--------------*
//* Feature: mentionedEntity
/** getter for mentionedEntity - gets
* @generated */
public NamedEntity getMentionedEntity() {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_mentionedEntity == null)
jcasType.jcas.throwFeatMissing("mentionedEntity", "org.cleartk.ne.type.NamedEntityMention");
return (NamedEntity)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_mentionedEntity)));}
/** setter for mentionedEntity - sets
* @generated */
public void setMentionedEntity(NamedEntity v) {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_mentionedEntity == null)
jcasType.jcas.throwFeatMissing("mentionedEntity", "org.cleartk.ne.type.NamedEntityMention");
jcasType.ll_cas.ll_setRefValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_mentionedEntity, jcasType.ll_cas.ll_getFSRef(v));}
//*--------------*
//* Feature: annotation
/** getter for annotation - gets
* @generated */
public Annotation getAnnotation() {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_annotation == null)
jcasType.jcas.throwFeatMissing("annotation", "org.cleartk.ne.type.NamedEntityMention");
return (Annotation)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_annotation)));}
/** setter for annotation - sets
* @generated */
public void setAnnotation(Annotation v) {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_annotation == null)
jcasType.jcas.throwFeatMissing("annotation", "org.cleartk.ne.type.NamedEntityMention");
jcasType.ll_cas.ll_setRefValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_annotation, jcasType.ll_cas.ll_getFSRef(v));}
//*--------------*
//* Feature: head
/** getter for head - gets
* @generated */
public Annotation getHead() {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_head == null)
jcasType.jcas.throwFeatMissing("head", "org.cleartk.ne.type.NamedEntityMention");
return (Annotation)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_head)));}
/** setter for head - sets
* @generated */
public void setHead(Annotation v) {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_head == null)
jcasType.jcas.throwFeatMissing("head", "org.cleartk.ne.type.NamedEntityMention");
jcasType.ll_cas.ll_setRefValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_head, jcasType.ll_cas.ll_getFSRef(v));}
//*--------------*
//* Feature: mentionId
/** getter for mentionId - gets
* @generated */
public String getMentionId() {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_mentionId == null)
jcasType.jcas.throwFeatMissing("mentionId", "org.cleartk.ne.type.NamedEntityMention");
return jcasType.ll_cas.ll_getStringValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_mentionId);}
/** setter for mentionId - sets
* @generated */
public void setMentionId(String v) {
if (NamedEntityMention_Type.featOkTst && ((NamedEntityMention_Type)jcasType).casFeat_mentionId == null)
jcasType.jcas.throwFeatMissing("mentionId", "org.cleartk.ne.type.NamedEntityMention");
jcasType.ll_cas.ll_setStringValue(addr, ((NamedEntityMention_Type)jcasType).casFeatCode_mentionId, v);}
}
| apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p410/Test8201.java | 2111 | package org.gradle.test.performance.mediummonolithicjavaproject.p410;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test8201 {
Production8201 objectUnderTest = new Production8201();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | apache-2.0 |
jbeecham/ovirt-engine | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/TagsDirector.java | 14974 | package org.ovirt.engine.core.bll;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.action.TagsOperationParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.tags;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Regex;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.TagDAO;
import org.ovirt.engine.core.utils.collections.CopyOnAccessMap;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
enum TagReturnValueIndicator {
ID,
NAME
}
/**
* This class responsible to In memory Tags handling. On Vdc starting in memory tags tree initialized. All Tags changing
* operations go throw this class
*/
public class TagsDirector {
private static Log log = LogFactory.getLog(TagsDirector.class);
protected static final Guid ROOT_TAG_ID = Guid.Empty;
/**
* In memory nodes cache for quicker access to each node by ID: O(1) instead O(lnN) of tree
*/
private final java.util.Map<Guid, tags> tagsMapByID =
new CopyOnAccessMap<Guid, tags>(new java.util.HashMap<Guid, tags>());
/**
* In memory nodes cache for quicker access to each node by name
*/
private final java.util.Map<String, tags> tagsMapByName =
new CopyOnAccessMap<String, tags>(new java.util.HashMap<String, tags>());
private static TagsDirector instance = new TagsDirector();
private TagsDirector() {
}
/**
* In memory tree initialized during initialization
*/
protected void init() {
log.info("TagsDirector initialization");
tagsMapByID.clear();
tagsMapByName.clear();
tags root = new tags("root", null, true, ROOT_TAG_ID, "root");
AddTagToHash(root);
AddChildren(root);
}
private void AddTagToHash(tags tag) {
tagsMapByID.put(tag.gettag_id(), tag);
tagsMapByName.put(tag.gettag_name(), tag);
if (tag.getparent_id() != null) {
// If the tag has a parent, the parent should have in its children the added tag instead
// of the old version of the tag , if exists
tags parentTag = tagsMapByID.get(tag.getparent_id());
if (parentTag == null) {
log.error(String.format("Could not obtain tag for guid %1$s", tag.getparent_id()));
return;
}
List<tags> parentChildren = parentTag.getChildren();
replaceTagInChildren(tag, parentChildren);
AddTagToHash(parentTag); // replace the parent tag after the modification
}
}
private void replaceTagInChildren(tags tag, List<tags> parentChildren) {
for (int counter = 0; counter < parentChildren.size(); counter++) {
if (parentChildren.get(counter).gettag_id().equals(tag.gettag_id())) {
parentChildren.set(counter, tag);
break;
}
}
}
private void RemoveTagFromHash(tags tag) {
tagsMapByID.remove(tag.gettag_id());
tagsMapByName.remove(tag.gettag_name());
}
/**
* Recurcive tree initialization call
*
* @param tag
*/
private void AddChildren(tags tag) {
log.infoFormat("Tag {0} added to tree", tag.gettag_name());
List<tags> children = getTagDAO().getAllForParent(tag.gettag_id());
for (tags child : children) {
AddChildren(child);
log.infoFormat("Tag {0} added as child to parent {1}", child.gettag_name(), tag.gettag_name());
tag.getChildren().add(child);
AddTagToHash(tag);
AddTagToHash(child);
}
}
protected TagDAO getTagDAO() {
return DbFacade.getInstance().getTagDao();
}
private void RemoveTagAndChildren(tags tag) {
for (tags child : tag.getChildren()) {
RemoveTagAndChildren(child);
}
RemoveTagFromHash(tag);
}
public static TagsDirector getInstance() {
return instance;
}
public void AddTag(tags tag) {
if (tagsMapByID.containsKey(tag.getparent_id())) {
tags parent = tagsMapByID.get(tag.getparent_id());
parent.getChildren().add(tag);
AddTagToHash(tag);
AddTagToHash(parent);
} else {
log.errorFormat("Trying to add tag {0}, parent doesn't exist in Data Structure - {1}", tag.gettag_name(),
tag.getparent_id());
}
}
/**
* Remove tag operation. For tag with children all tag's children will be removed as well
*
* @param tagId
* tag to remove
*/
public void RemoveTag(Guid tagId) {
if (tagsMapByID.containsKey(tagId)) {
tags tag = tagsMapByID.get(tagId);
RemoveTagAndChildren(tag);
tags parent = tagsMapByID.get(tag.getparent_id());
parent.getChildren().remove(tag);
AddTagToHash(parent);
} else {
log.warnFormat("Trying to remove tag, not exists in Data Structure - {0}", tagId);
}
}
/**
* Update tag. We assume that the id doesn't change.
*
* @param tag
*/
public void UpdateTag(tags tag) {
if (tagsMapByID.containsKey(tag.gettag_id())) {
tags tagFromCache = tagsMapByID.get(tag.gettag_id());
String oldName = tagFromCache.gettag_name();
// check if tag name has changed. If it has - modify name dictionary
// accordingly:
if (!tag.gettag_name().equals(oldName)) {
tagsMapByName.remove(oldName);
}
// Copy the children of the cached tag to keep the object hierarchy consistent.
tag.setChildren(tagFromCache.getChildren());
AddTagToHash(tag);
} else {
log.warnFormat("Trying to update tag, not exists in Data Structure - {0}", tag.gettag_name());
}
}
public void MoveTag(Guid tagId, Guid newParent) {
if (tagsMapByID.containsKey(tagId)) {
tags tag = tagsMapByID.get(tagId);
if (tagsMapByID.containsKey(newParent)) {
if (tagsMapByID.containsKey(tag.getparent_id())) {
tags parentTag = tagsMapByID.get(tag.getparent_id());
parentTag.getChildren().remove(tag);
AddTagToHash(parentTag);
} else {
log.warnFormat("Trying to move tag from parent that doesn't exist in Data Structure - {0}",
tag.getparent_id());
}
tags newParentTag = tagsMapByID.get(newParent);
newParentTag.getChildren().add(tag);
tag.setparent_id(newParent);
AddTagToHash(newParentTag); // Parent got changed, modify it.
updateTagInBackend(tag);
} else {
log.errorFormat("Trying to move tag, to parent not exists in Data Structure - {0}", newParent);
}
} else {
log.errorFormat("Trying to move tag, not exists in Data Structure - {0}", tagId);
}
}
protected void updateTagInBackend(tags tag) {
Backend.getInstance().runInternalAction(VdcActionType.UpdateTag, new TagsOperationParameters(tag));
}
private String GetTagIdAndParentsIds(tags tag) {
StringBuilder builder = new StringBuilder();
builder.append(tag.gettag_id());
Guid tempTagId = new Guid(tag.getparent_id().toString());
while (!tempTagId.equals(Guid.Empty)) {
builder.append(String.format(",%1$s", tempTagId));
tag = GetTagById(tempTagId);
tempTagId = new Guid(tag.getparent_id().toString());
}
return builder.toString();
}
/**
* This function will return the tag's ID and its parents IDs.
*
* @param tagId
* the tag ID.
* @return a comma seperated list of IDs.
*/
public String GetTagIdAndParentsIds(Guid tagId) {
tags tag = GetTagById(tagId);
return GetTagIdAndParentsIds(tag);
}
/**
* This function will return the tag's ID and its parents IDs.
*
* @param tagId
* the tag ID.
* @return a comma seperated list of IDs.
*/
public String GetTagIdAndParentsIds(String tagName) {
tags tag = GetTagByName(tagName);
return GetTagIdAndParentsIds(tag);
}
/**
* This function will return the tag's ID and its children IDs. Its used to determine if a tag is assigned to an
* entity. Tag is determined as assigned to an entity if the entity is assigned to the tag or to one of its
* children.
*
* @param tagId
* the ID of the 'root' tag.
* @return a comma separated list of IDs.
*/
public String GetTagIdAndChildrenIds(Guid tagId) {
tags tag = GetTagById(tagId);
if (tag == null) {
return StringUtils.EMPTY;
}
StringBuilder sb = tag.GetTagIdAndChildrenIds();
return sb.toString();
}
public String GetTagNameAndChildrenNames(Guid tagId) {
tags tag = GetTagById(tagId);
StringBuilder sb = tag.GetTagNameAndChildrenNames();
return sb.toString();
}
public java.util.HashSet<Guid> GetTagIdAndChildrenIdsAsSet(Guid tagId) {
tags tag = GetTagById(tagId);
java.util.HashSet<Guid> set = new java.util.HashSet<Guid>();
tag.GetTagIdAndChildrenIdsAsList(set);
return set;
}
/**
* This function will return the tag's ID and its children IDs. Its used to determine if a tag is assigned to an
* entity. Tag is determined as assigned to an entity if the entity is assigned to the tag or to one of its
* children.
*
* @param tagName
* the name of the 'root' tag.
* @return a comma separated list of IDs.
*/
public String GetTagIdAndChildrenIds(String tagName) {
tags tag = GetTagByName(tagName);
StringBuilder sb = tag.GetTagIdAndChildrenIds();
return sb.toString();
}
/**
* This function will return the tags IDs of all tags that their names match the specified regular expression and
* ALL their children (regardless if the children match the reg-exp or not). Its used to determine if a tag is
* assigned to an entity. Tag is determined as assigned to an entity if the entity is assigned to the tag or to one
* of its children.
*
* @param tagName
* the name of the 'root' tag.
* @return a comma separated list of IDs.
*/
public String GetTagIdsAndChildrenIdsByRegExp(String tagNameRegExp) {
// add RegEx chars or beginning of string ('^') and end of string ('$'):
tagNameRegExp = String.format("^%1$s$", tagNameRegExp);
// convert to the regular expression format:
tagNameRegExp = tagNameRegExp.replace("*", ".*");
StringBuilder sb = new StringBuilder();
RecursiveGetTagsAndChildrenByRegExp(tagNameRegExp, sb, GetRootTag(), TagReturnValueIndicator.ID);
return sb.toString();
}
public String GetTagNamesAndChildrenNamesByRegExp(String tagNameRegExp) {
// add RegEx chars or beginning of string ('^') and end of string ('$'):
tagNameRegExp = String.format("^%1$s$", tagNameRegExp);
// convert to the regular expression format:
tagNameRegExp = tagNameRegExp.replace("*", ".*");
StringBuilder sb = new StringBuilder();
RecursiveGetTagsAndChildrenByRegExp(tagNameRegExp, sb, GetRootTag(), TagReturnValueIndicator.NAME);
return sb.toString();
}
private void RecursiveGetTagsAndChildrenByRegExp(String tagNameRegExp, StringBuilder sb, tags tag, TagReturnValueIndicator indicator ) {
if ((tag.getChildren() != null) && (tag.getChildren().size() > 0)) {
for (tags child : tag.getChildren()) {
if (Regex.IsMatch(child.gettag_name(), tagNameRegExp))
// the tag matches the regular expression -> add it and all its
// children
// (we prevent searching a regular expression match on them -
// unnecessary).
{
if (sb.length() == 0) {
if (indicator == TagReturnValueIndicator.ID)
sb.append(child.GetTagIdAndChildrenIds());
else
sb.append(child.GetTagNameAndChildrenNames());
} else {
if (indicator == TagReturnValueIndicator.ID)
sb.append(String.format(",%1$s", child.GetTagIdAndChildrenIds()));
else
sb.append(String.format(",%1$s", child.GetTagNameAndChildrenNames()));
}
} else {
RecursiveGetTagsAndChildrenByRegExp(tagNameRegExp, sb, child, indicator);
}
}
}
}
/**
* Get tag from in memory data structure (by ID). This tag will be with all children tree initialized as opposite to
* tag from db.
*
* @param tagId
* @return
*/
public tags GetTagById(Guid tagId) {
if (tagsMapByID.containsKey(tagId)) {
return tagsMapByID.get(tagId);
} else {
return null;
}
}
/**
* Get tag from in memory data structure (by name).
*
* @param tagName
* @return
*/
public tags GetTagByName(String tagName) {
if (tagsMapByName.containsKey(tagName)) {
return tagsMapByName.get(tagName);
} else {
return null;
}
}
/**
* Gets a list of all the tags in the system.
*
* @return a tags list.
*/
public java.util.ArrayList<tags> GetAllTags() {
java.util.ArrayList<tags> ret = new java.util.ArrayList<tags>(tagsMapByID.values());
// remove the root - it is not a real tag:
ret.remove(GetRootTag());
return ret;
}
/**
* Returns the root tag in the system.
*
* @return the root tag.
*/
public tags GetRootTag() {
return tagsMapByID.get(ROOT_TAG_ID);
}
public boolean IsTagDescestorOfTag(Guid sourceTagId, Guid potentialDescestorId) {
if (sourceTagId.equals(potentialDescestorId)) {
return true;
}
tags tag = GetTagById(sourceTagId);
if (tag != null && tag.getChildren() != null) {
for (tags childTag : tag.getChildren()) {
if (IsTagDescestorOfTag(childTag.gettag_id(), potentialDescestorId)) {
return true;
}
}
}
return false;
}
}
| apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/ArtifactStore.java | 7562 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.codepipeline.model;
import java.io.Serializable;
/**
* <p>
* The Amazon S3 location where artifacts are stored for the pipeline. If this
* Amazon S3 bucket is created manually, it must meet the requirements for AWS
* CodePipeline. For more information, see the <ulink url=
* "http://docs.aws.amazon.com/codepipeline/latest/UserGuide/concepts.html"
* >Concepts</ulink>.
* </p>
*/
public class ArtifactStore implements Serializable, Cloneable {
/**
* <p>
* The type of the artifact store, such as S3.
* </p>
*/
private String type;
/**
* <p>
* The location for storing the artifacts for a pipeline, such as an S3
* bucket or folder.
* </p>
*/
private String location;
private EncryptionKey encryptionKey;
/**
* <p>
* The type of the artifact store, such as S3.
* </p>
*
* @param type
* The type of the artifact store, such as S3.
* @see ArtifactStoreType
*/
public void setType(String type) {
this.type = type;
}
/**
* <p>
* The type of the artifact store, such as S3.
* </p>
*
* @return The type of the artifact store, such as S3.
* @see ArtifactStoreType
*/
public String getType() {
return this.type;
}
/**
* <p>
* The type of the artifact store, such as S3.
* </p>
*
* @param type
* The type of the artifact store, such as S3.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see ArtifactStoreType
*/
public ArtifactStore withType(String type) {
setType(type);
return this;
}
/**
* <p>
* The type of the artifact store, such as S3.
* </p>
*
* @param type
* The type of the artifact store, such as S3.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see ArtifactStoreType
*/
public void setType(ArtifactStoreType type) {
this.type = type.toString();
}
/**
* <p>
* The type of the artifact store, such as S3.
* </p>
*
* @param type
* The type of the artifact store, such as S3.
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see ArtifactStoreType
*/
public ArtifactStore withType(ArtifactStoreType type) {
setType(type);
return this;
}
/**
* <p>
* The location for storing the artifacts for a pipeline, such as an S3
* bucket or folder.
* </p>
*
* @param location
* The location for storing the artifacts for a pipeline, such as an
* S3 bucket or folder.
*/
public void setLocation(String location) {
this.location = location;
}
/**
* <p>
* The location for storing the artifacts for a pipeline, such as an S3
* bucket or folder.
* </p>
*
* @return The location for storing the artifacts for a pipeline, such as an
* S3 bucket or folder.
*/
public String getLocation() {
return this.location;
}
/**
* <p>
* The location for storing the artifacts for a pipeline, such as an S3
* bucket or folder.
* </p>
*
* @param location
* The location for storing the artifacts for a pipeline, such as an
* S3 bucket or folder.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ArtifactStore withLocation(String location) {
setLocation(location);
return this;
}
/**
* @param encryptionKey
*/
public void setEncryptionKey(EncryptionKey encryptionKey) {
this.encryptionKey = encryptionKey;
}
/**
* @return
*/
public EncryptionKey getEncryptionKey() {
return this.encryptionKey;
}
/**
* @param encryptionKey
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ArtifactStore withEncryptionKey(EncryptionKey encryptionKey) {
setEncryptionKey(encryptionKey);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getType() != null)
sb.append("Type: " + getType() + ",");
if (getLocation() != null)
sb.append("Location: " + getLocation() + ",");
if (getEncryptionKey() != null)
sb.append("EncryptionKey: " + getEncryptionKey());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ArtifactStore == false)
return false;
ArtifactStore other = (ArtifactStore) obj;
if (other.getType() == null ^ this.getType() == null)
return false;
if (other.getType() != null
&& other.getType().equals(this.getType()) == false)
return false;
if (other.getLocation() == null ^ this.getLocation() == null)
return false;
if (other.getLocation() != null
&& other.getLocation().equals(this.getLocation()) == false)
return false;
if (other.getEncryptionKey() == null ^ this.getEncryptionKey() == null)
return false;
if (other.getEncryptionKey() != null
&& other.getEncryptionKey().equals(this.getEncryptionKey()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getType() == null) ? 0 : getType().hashCode());
hashCode = prime * hashCode
+ ((getLocation() == null) ? 0 : getLocation().hashCode());
hashCode = prime
* hashCode
+ ((getEncryptionKey() == null) ? 0 : getEncryptionKey()
.hashCode());
return hashCode;
}
@Override
public ArtifactStore clone() {
try {
return (ArtifactStore) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
} | apache-2.0 |
ragerri/opennlp | opennlp-tools/src/test/java/opennlp/tools/chunker/ChunkerMETest.java | 5644 | /*
* 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 opennlp.tools.chunker;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import opennlp.tools.formats.ResourceAsStreamFactory;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.util.InsufficientTrainingDataException;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.Sequence;
import opennlp.tools.util.Span;
import opennlp.tools.util.TrainingParameters;
/**
* This is the test class for {@link NameFinderME}.
* <p>
* A proper testing and evaluation of the name finder is only possible with a
* large corpus which contains a huge amount of test sentences.
* <p>
* The scope of this test is to make sure that the name finder code can be
* executed. This test can not detect mistakes which lead to incorrect feature
* generation or other mistakes which decrease the tagging performance of the
* name finder.
* <p>
* In this test the {@link NameFinderME} is trained with a small amount of
* training sentences and then the computed model is used to predict sentences
* from the training sentences.
*/
public class ChunkerMETest {
private Chunker chunker;
private static String[] toks1 = { "Rockwell", "said", "the", "agreement", "calls", "for",
"it", "to", "supply", "200", "additional", "so-called", "shipsets",
"for", "the", "planes", "." };
private static String[] tags1 = { "NNP", "VBD", "DT", "NN", "VBZ", "IN", "PRP", "TO", "VB",
"CD", "JJ", "JJ", "NNS", "IN", "DT", "NNS", "." };
private static String[] expect1 = { "B-NP", "B-VP", "B-NP", "I-NP", "B-VP", "B-SBAR",
"B-NP", "B-VP", "I-VP", "B-NP", "I-NP", "I-NP", "I-NP", "B-PP", "B-NP",
"I-NP", "O" };
@Before
public void startup() throws IOException {
// train the chunker
ResourceAsStreamFactory in = new ResourceAsStreamFactory(getClass(),
"/opennlp/tools/chunker/test.txt");
ObjectStream<ChunkSample> sampleStream = new ChunkSampleStream(
new PlainTextByLineStream(in, StandardCharsets.UTF_8));
TrainingParameters params = new TrainingParameters();
params.put(TrainingParameters.ITERATIONS_PARAM, 70);
params.put(TrainingParameters.CUTOFF_PARAM, 1);
ChunkerModel chunkerModel = ChunkerME.train("en", sampleStream, params, new ChunkerFactory());
this.chunker = new ChunkerME(chunkerModel);
}
@Test
public void testChunkAsArray() throws Exception {
String[] preds = chunker.chunk(toks1, tags1);
Assert.assertArrayEquals(expect1, preds);
}
@Test
public void testChunkAsSpan() throws Exception {
Span[] preds = chunker.chunkAsSpans(toks1, tags1);
System.out.println(Arrays.toString(preds));
Assert.assertEquals(10, preds.length);
Assert.assertEquals(new Span(0, 1, "NP"), preds[0]);
Assert.assertEquals(new Span(1, 2, "VP"), preds[1]);
Assert.assertEquals(new Span(2, 4, "NP"), preds[2]);
Assert.assertEquals(new Span(4, 5, "VP"), preds[3]);
Assert.assertEquals(new Span(5, 6, "SBAR"), preds[4]);
Assert.assertEquals(new Span(6, 7, "NP"), preds[5]);
Assert.assertEquals(new Span(7, 9, "VP"), preds[6]);
Assert.assertEquals(new Span(9, 13, "NP"), preds[7]);
Assert.assertEquals(new Span(13, 14, "PP"), preds[8]);
Assert.assertEquals(new Span(14, 16, "NP"), preds[9]);
}
@Test
public void testTokenProbArray() throws Exception {
Sequence[] preds = chunker.topKSequences(toks1, tags1);
Assert.assertTrue(preds.length > 0);
Assert.assertEquals(expect1.length, preds[0].getProbs().length);
Assert.assertEquals(Arrays.asList(expect1), preds[0].getOutcomes());
Assert.assertNotSame(Arrays.asList(expect1), preds[1].getOutcomes());
}
@Test
public void testTokenProbMinScore() throws Exception {
Sequence[] preds = chunker.topKSequences(toks1, tags1, -5.55);
Assert.assertEquals(4, preds.length);
Assert.assertEquals(expect1.length, preds[0].getProbs().length);
Assert.assertEquals(Arrays.asList(expect1), preds[0].getOutcomes());
Assert.assertNotSame(Arrays.asList(expect1), preds[1].getOutcomes());
}
@Test(expected = InsufficientTrainingDataException.class)
public void testInsufficientData() throws IOException {
ResourceAsStreamFactory in = new ResourceAsStreamFactory(getClass(),
"/opennlp/tools/chunker/test-insufficient.txt");
ObjectStream<ChunkSample> sampleStream = new ChunkSampleStream(
new PlainTextByLineStream(in, StandardCharsets.UTF_8));
TrainingParameters params = new TrainingParameters();
params.put(TrainingParameters.ITERATIONS_PARAM, 70);
params.put(TrainingParameters.CUTOFF_PARAM, 1);
ChunkerME.train("en", sampleStream, params, new ChunkerFactory());
}
}
| apache-2.0 |
Qi4j/qi4j-libraries | eventsourcing/src/main/java/org/qi4j/library/eventsourcing/application/source/helper/ApplicationTransactionTracker.java | 6295 | /*
* Copyright 2009-2010 Rickard Öberg AB
*
* 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.qi4j.library.eventsourcing.application.source.helper;
import org.qi4j.api.configuration.Configuration;
import org.qi4j.io.Output;
import org.qi4j.io.Receiver;
import org.qi4j.io.Sender;
import org.qi4j.library.eventsourcing.application.api.TransactionApplicationEvents;
import org.qi4j.library.eventsourcing.application.source.ApplicationEventSource;
import org.qi4j.library.eventsourcing.application.source.ApplicationEventStream;
import org.qi4j.library.eventsourcing.domain.source.helper.DomainEventTrackerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper that enables a service to easily track transactions. Upon startup
* the tracker will get all the transactions from the store since the last
* check, and delegate them to the given Output. It will also register itself
* with the store so that it can get continuous updates.
* <p/>
* Then, as transactions come in from the store, they will be processed in real-time.
* If a transaction is successfully handled the configuration of the service, which must
* extend DomainEventTrackerConfiguration, will update the marker for the last successfully handled transaction.
*/
public class ApplicationTransactionTracker<ReceiverThrowableType extends Throwable>
{
private Configuration<? extends DomainEventTrackerConfiguration> configuration;
private Output<TransactionApplicationEvents, ReceiverThrowableType> output;
private ApplicationEventStream stream;
private ApplicationEventSource source;
private boolean started = false;
private boolean upToSpeed = false;
private Logger logger;
private Output<TransactionApplicationEvents, ReceiverThrowableType> trackerOutput;
public ApplicationTransactionTracker( ApplicationEventStream stream, ApplicationEventSource source,
Configuration<? extends DomainEventTrackerConfiguration> configuration,
Output<TransactionApplicationEvents, ReceiverThrowableType> output )
{
this.stream = stream;
this.configuration = configuration;
this.source = source;
this.output = output;
logger = LoggerFactory.getLogger( output.getClass() );
}
public void start()
{
if (!started)
{
started = true;
// Get events since last check
upToSpeed = true; // Pretend that we are up to speed from now on
trackerOutput = output();
try
{
source.transactionsAfter( configuration.configuration().lastOffset().get(), Long.MAX_VALUE ).transferTo( trackerOutput );
} catch (Throwable receiverThrowableType)
{
upToSpeed = false;
}
stream.registerListener( trackerOutput );
}
}
public void stop()
{
if (started)
{
started = false;
stream.unregisterListener( trackerOutput );
upToSpeed = false;
}
}
private Output<TransactionApplicationEvents, ReceiverThrowableType> output()
{
return new Output<TransactionApplicationEvents, ReceiverThrowableType>()
{
@Override
public <SenderThrowableType extends Throwable> void receiveFrom(final Sender<? extends TransactionApplicationEvents, SenderThrowableType> sender) throws ReceiverThrowableType, SenderThrowableType
{
if (!upToSpeed)
{
// The tracker has not handled successfully all transactions before,
// so it needs to get the backlog first
upToSpeed = true; // Pretend that we are up to speed from now on
// Get all transactions from last timestamp, including the one in this call
try
{
source.transactionsAfter( configuration.configuration().lastOffset().get(), Long.MAX_VALUE ).transferTo( trackerOutput );
} catch (Throwable e)
{
upToSpeed = false;
throw (SenderThrowableType) e;
}
}
try
{
output.receiveFrom( new Sender<TransactionApplicationEvents, SenderThrowableType>()
{
@Override
public <ReceiverThrowableType extends Throwable> void sendTo(final Receiver<? super TransactionApplicationEvents, ReceiverThrowableType> receiver) throws ReceiverThrowableType, SenderThrowableType
{
sender.sendTo( new Receiver<TransactionApplicationEvents, ReceiverThrowableType>()
{
public void receive( TransactionApplicationEvents item ) throws ReceiverThrowableType
{
receiver.receive( item );
// Events in this transactionDomain were handled successfully so store new marker
configuration.configuration().lastOffset().set( item.timestamp().get() );
configuration.save();
}
} );
}
} );
} catch (Throwable receiverThrowableType)
{
upToSpeed = false;
throw (ReceiverThrowableType) receiverThrowableType;
}
}
};
}
}
| apache-2.0 |
sjaco002/incubator-asterixdb | asterix-aql/src/main/java/edu/uci/ics/asterix/aql/expression/FieldAccessor.java | 1713 | /*
* Copyright 2009-2013 by The Regents of the University of California
* 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 from
*
* 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.uci.ics.asterix.aql.expression;
import edu.uci.ics.asterix.aql.base.Expression;
import edu.uci.ics.asterix.aql.expression.visitor.IAqlExpressionVisitor;
import edu.uci.ics.asterix.aql.expression.visitor.IAqlVisitorWithVoidReturn;
import edu.uci.ics.asterix.common.exceptions.AsterixException;
public class FieldAccessor extends AbstractAccessor {
private Identifier ident;
public FieldAccessor(Expression expr, Identifier ident) {
super(expr);
this.ident = ident;
}
public Identifier getIdent() {
return ident;
}
public void setIdent(Identifier ident) {
this.ident = ident;
}
@Override
public Kind getKind() {
return Kind.FIELD_ACCESSOR_EXPRESSION;
}
@Override
public <T> void accept(IAqlVisitorWithVoidReturn<T> visitor, T arg) throws AsterixException {
visitor.visit(this, arg);
}
@Override
public <R, T> R accept(IAqlExpressionVisitor<R, T> visitor, T arg) throws AsterixException {
return visitor.visitFieldAccessor(this, arg);
}
}
| apache-2.0 |
nssales/Strata | modules/engine/src/test/java/com/opengamma/strata/engine/marketdata/TestMapping.java | 1256 | /**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.engine.marketdata;
import java.util.Objects;
import com.opengamma.strata.basics.market.MarketDataId;
import com.opengamma.strata.engine.marketdata.mapping.MarketDataMapping;
/**
* Market data mapping used in tests.
*/
public final class TestMapping implements MarketDataMapping<String, TestKey> {
private final String str;
public TestMapping(String str) {
this.str = str;
}
@Override
public Class<? extends TestKey> getMarketDataKeyType() {
throw new UnsupportedOperationException("getMarketDataKeyType not implemented");
}
@Override
public MarketDataId<String> getIdForKey(TestKey key) {
return TestId.of(key.getValue());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TestMapping that = (TestMapping) o;
return Objects.equals(str, that.str);
}
@Override
public int hashCode() {
return Objects.hash(str);
}
@Override
public String toString() {
return "TestMapping [str='" + str + "']";
}
}
| apache-2.0 |
CharlesNo/Chronos | Chronos/src/business/Performance.java | 3312 | /* _________________________________________________________ */
/* _________________________________________________________ */
/**
* Fichier : Performance.java
*
* Créé le 31 oct. 2013 à 13:12:58
*
* Auteur : Charles NEAU
* Jérôme POINAS
*/
package business;
import utility.Formatter;
/* _________________________________________________________ */
/**
* The Class Performance.
* Un {@link Performance} est un le résultat d'une performance.
* Il contient le temps du chronomètre, la distance parcouru,
* ainsi que la date de la création de ce temps.
*
* @author Charles NEAU
*/
public class Performance
{
/** The chrono. */
private final long chrono;
/** La date. */
private final String date;
/** The distance. */
private final int distance;
/**
* Athlete qui possède cette performance (nécessaire pour la base de
* données)
*/
private final Athlete athlete;
/* _________________________________________________________ */
/**
* Instantiates a new performance. Utilisé lors de l'ajout d'une nouvelle
* performance.
*
* @param athlete
* L'athlete a qui est rattaché la performance.
* @param chrono
* the chrono
* @param distance
* the distance
*/
public Performance(final Athlete athlete, final long chrono,
final int distance)
{
super();
date = Formatter.formatDate();
this.chrono = chrono;
this.distance = distance;
this.athlete = athlete;
}
/* _________________________________________________________ */
/**
* Instantiates a new performance. Utiliser pour charger les éléments déja
* présent dans la BDD.
*
* @param athlete
* L'athlete a qui est rattaché à la performance.
* @param chrono
* the chrono
* @param distance
* the distance
* @param date
* the date.
*/
public Performance(final Athlete athlete, final long chrono,
final int distance, final String date)
{
super();
this.chrono = chrono;
this.distance = distance;
this.athlete = athlete;
this.date = date;
}
/* _________________________________________________________ */
/**
* Retourne la valeur du champ chrono.
*
* @return la valeur du champ chrono.
*/
public long getChrono()
{
return chrono;
}
/* _________________________________________________________ */
/**
* Retourne la valeur du champ date.
*
* @return la valeur du champ date.
*/
public String getDate()
{
return date;
}
/* _________________________________________________________ */
/**
* Retourne la valeur du champ distance.
*
* @return la valeur du champ distance.
*/
public int getDistance()
{
return distance;
}
/* _________________________________________________________ */
/**
* @return Description performance.
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
final StringBuilder build = new StringBuilder();
build.append("Le ").append(date).append(", ").append("\n");
build.append(Formatter.miseEnForme(chrono)).append(" (")
.append(distance).append("m)");
return build.toString();
}
}
/* _________________________________________________________ */
/*
* Fin du fichier Performance.java.
* /*_________________________________________________________
*/
| apache-2.0 |
oswa/bianccoAdmin | BianccoAdministrator/src/main/java/com/biancco/admin/persistence/dao/RoleDAO.java | 1278 | /**
* SOSExcellence S.A. de C.V. all rights reserved 2016.
*/
package com.biancco.admin.persistence.dao;
import java.util.List;
import com.biancco.admin.app.exception.DBException;
import com.biancco.admin.model.catalog.RoleSimpleRecord;
import com.biancco.admin.persistence.model.Role;
/**
* Manage the persistence for Role objects.
*
* @author SOSExcellence.
*/
public interface RoleDAO {
/**
* Saves a role.
*
* @param role
* A role.
* @return The role saved.
* @throws DBException
* If a problem occurs.
*/
Role save(Role role) throws DBException;
/**
* Updates a role.
*
* @param role
* A role.
* @throws DBException
* If a problem occurs.
*/
void update(Role role) throws DBException;
/**
* Deletes a role.
*
* @param role
* A role.
* @throws DBException
* If a problem occurs.
*/
void delete(Role role) throws DBException;
/**
* Gets all roles.
*
* @param enabledOnly
* Enabled filter.
*
* @return A role list.
* @throws DBException
* If a problem occurs.
*/
List<RoleSimpleRecord> getAll(boolean enabledOnly) throws DBException;
}
| apache-2.0 |
springzero/WebFinalExercises | smart-framework/src/main/java/org/smart4j/framework/util/ArrayUtil.java | 447 | package org.smart4j.framework.util;
import org.apache.commons.lang3.ArrayUtils;
/**
* Created by Administrator on 2016/5/6.
*/
public class ArrayUtil {
/*
* 判断字符串是否为空
* */
public static boolean isEmpty(Object[] arr) {
return ArrayUtils.isEmpty(arr);
}
/*
* 判断字符串是否非空
* */
public static boolean isNotEmpty(Object[] arr) {
return !isEmpty(arr);
}
}
| apache-2.0 |
currying/molecule | molecule/src/main/java/com/toparchy/molecule/push/netty/NettyPushService.java | 885 | package com.toparchy.molecule.push.netty;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
@ApplicationScoped
public class NettyPushService {
@Inject
private PushService pushService;
/**
* 消息推送
*
* @param pushMessageBean
* @return
*/
public BaseDataWrapper push(PushMessageForm pushMessageBean) {
BaseDataWrapper json = new BaseDataWrapper();
PushMessagePacket pushMessage = null;
// 消息序列化
try {
pushMessage = pushMessageBean.parsePushMessage();
} catch (Exception e) {
json.setSuccess(false);
return json;
}
// 推送消息
try {
pushService.sendOnLineClient(pushMessageBean.getClient(), pushMessage);
} catch (Exception e) {
e.printStackTrace();
json.setSuccess(false);
return json;
}
json.setSuccess(true);
return json;
}
}
| apache-2.0 |
YY-ORG/yycloud | yy-api/yy-admin-api/src/main/java/com/yy/cloud/api/admin/service/OrgnizationService.java | 1434 | package com.yy.cloud.api.admin.service;
import java.util.List;
import com.yy.cloud.common.data.GeneralContentResult;
import com.yy.cloud.common.data.GeneralPagingResult;
import com.yy.cloud.common.data.GeneralResult;
import com.yy.cloud.common.data.PageInfo;
import com.yy.cloud.common.data.otd.usermgmt.OrganizationItem;
import com.yy.cloud.common.data.otd.usermgmt.OrganizationProfile;
public interface OrgnizationService {
/**
* 创建组织
*
* @param _organizationProfile
* 组织信息
* @return 组织ID
*/
GeneralContentResult<String> createOrgnization(OrganizationProfile _organizationProfile);
GeneralResult updateOrgnization(String _organizationId, OrganizationProfile _organizationProfile);
/**
* 删除组织
*
* @param _organizationId
* 组织ID
*/
GeneralResult deleteOrgnization(String _organizationId);
/**
* 修改组织状态
*
* @param _organizationId
* 组织ID
* @param _status
* 状态
*/
void updateOrgnizationStatus(String _organizationId, Byte _status);
/**
* 分页列出组织
*
* @param _pageInfo
* @param _status
* @return
*/
GeneralPagingResult<List<OrganizationItem>> listOrganizationsByPage(
Byte _status, Integer _page,
Integer _size);
GeneralContentResult<OrganizationItem> findOrganizationItemById(String _organizationId);
}
| apache-2.0 |
Axway/ats-framework | actionlibrary/src/main/java/com/axway/ats/action/objects/model/NoSuchHeaderException.java | 1267 | /*
* Copyright 2017 Axway Software
*
* 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.axway.ats.action.objects.model;
@SuppressWarnings( "serial")
public class NoSuchHeaderException extends PackageException {
public NoSuchHeaderException( String headerName,
int headerIndex ) {
super("Message does not contain header with name '" + headerName + "' at position " + headerIndex);
}
public NoSuchHeaderException( String headerName,
int partNum,
int headerIndex ) {
super("MIME part number " + partNum + " does not contain header with name '" + headerName
+ "' at position " + headerIndex);
}
}
| apache-2.0 |
trasa/aws-sdk-java | aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/PriorRequestNotCompleteException.java | 1212 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.route53.model;
import com.amazonaws.AmazonServiceException;
/**
* <p>
* The request was rejected because Amazon Route 53 was still processing a prior
* request.
* </p>
*/
public class PriorRequestNotCompleteException extends AmazonServiceException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new PriorRequestNotCompleteException with the specified
* error message.
*
* @param message
* Describes the error encountered.
*/
public PriorRequestNotCompleteException(String message) {
super(message);
}
} | apache-2.0 |
approvals/ApprovalTests.Java | approvaltests-util/src/main/java/com/spun/util/database/SQLQuery.java | 8195 | package com.spun.util.database;
import com.spun.util.DatabaseUtils;
import com.spun.util.ObjectUtils;
import com.spun.util.StringUtils;
import java.sql.Statement;
import java.util.ArrayList;
public class SQLQuery
{
public static final class JOINS
{
public static final String INNER_JOIN = "INNER JOIN";
public static final String LEFT_OUTER_JOIN = "LEFT OUTER JOIN";
public static final String RIGHT_OUTER_JOIN = "RIGHT OUTER JOIN";
}
public static final String BREAK = "\n";
private ArrayList<String> select = null;
private ArrayList<FromPart> from = null;
private SQLWhere where = null;
private ArrayList<OrderByPart> orderBy = null;
private ArrayList<String> groupBy = null;
private ArrayList<String> having = null;
private boolean reversed = false;
private LimitPart limitPart;
private int tableAliasOffset;
private boolean distinct;
public SQLQuery()
{
this(0);
}
public SQLQuery(int tableAliasOffset)
{
this.tableAliasOffset = tableAliasOffset;
select = new ArrayList<String>();
from = new ArrayList<FromPart>();
where = null;
orderBy = new ArrayList<OrderByPart>();
groupBy = new ArrayList<String>();
having = new ArrayList<String>();
}
public void addSelect(String part)
{
select.add(part);
}
public void addSelect(String part, String alias)
{
select.add(part + " AS " + alias);
}
public void addDistinct()
{
distinct = true;
}
public boolean isDistinct()
{
return distinct;
}
public String getFirstAliasForTableName(String tableName)
{
for (int i = 0; i < from.size(); i++)
{
FromPart part = (FromPart) from.get(i);
if (part.part.indexOf(tableName + " AS") != -1)
{ return "" + ((char) ('a' + i)); }
}
return null;
}
public void addFromPart(FromPart from)
{
this.from.add(from);
}
public void addOrderByPart(OrderByPart orderBy)
{
this.orderBy.add(orderBy);
}
public void setLimitPart(LimitPart limit)
{
this.limitPart = limit;
}
public int getAliasCount()
{
return getFromParts().length;
}
public String addFrom(String table)
{
String alias = "" + (char) ('a' + tableAliasOffset + from.size());
from.add(new FromPart(table + " AS " + alias, false));
return alias;
}
public String addFromWithInnerJoin(String table, String joinWith, String joinOn)
{
return addFromWithJoin(table, joinWith, joinOn, JOINS.INNER_JOIN);
}
public String addFromWithLeftOuterJoin(String table, String joinWith, String joinOn)
{
return addFromWithJoin(table, joinWith, joinOn, JOINS.LEFT_OUTER_JOIN);
}
public String addFromWithRightOuterJoin(String table, String joinWith, String joinOn)
{
return addFromWithJoin(table, joinWith, joinOn, JOINS.RIGHT_OUTER_JOIN);
}
public String addFromWithJoin(String table, String joinWith, String joinOn, String joinType)
{
String alias = "" + (char) ('a' + tableAliasOffset + from.size());
String sql = joinType + " " + table + " AS " + alias + " ON " + joinWith + " = " + alias + "." + joinOn;
from.add(new FromPart(sql, true));
return alias;
}
public void addWhere(String part)
{
addWhere(new SQLWhere(part), true);
}
public void addWhere(SQLWhere part)
{
addWhere(part, true);
}
public void addWhere(String part, boolean joinWithAnd)
{
addWhere(new SQLWhere(part), joinWithAnd);
}
public void addWhere(SQLWhere part, boolean joinWithAnd)
{
where = joinWithAnd ? SQLWhere.joinByAnd(where, part) : SQLWhere.joinByOr(where, part);
}
public String toString()
{
return toString(DatabaseUtils.SQLSERVER);
}
public String toString(Statement stmt)
{
try
{
return toString(DatabaseUtils.getDatabaseType(stmt));
}
catch (Exception e)
{
throw ObjectUtils.throwAsError(e);
}
}
public String toString(int databaseType)
{
SQLQueryWriter writer = getSQLQueryWriter(databaseType);
return writer.toString(this);
}
private SQLQueryWriter getSQLQueryWriter(int databaseType)
{
if (limitPart == null || DatabaseUtils.MY_SQL == databaseType)
{
return new SimpleQueryWriter(databaseType);
}
else if (limitPart.startingZeroBasedIndex == 0)
{
return new SimpleQueryWriter(databaseType);
}
else
{
return new ReverseOrderLimitQueryWriter(databaseType);
}
}
public void addOrderBy(String orderByClause, boolean ascending)
{
orderBy.add(new OrderByPart(orderByClause, ascending));
}
public void addOrderBy(ColumnMetadata submitted, String alias, boolean ascending)
{
addOrderBy(submitted.getNameWithPrefix(alias), ascending);
}
public void addGroupBy(String groupByClause)
{
groupBy.add(groupByClause);
}
public void addHaving(String havingClause)
{
having.add(havingClause);
}
public void setOrderReversed(boolean reversed)
{
this.reversed = reversed;
}
public boolean isOrderReversed()
{
return reversed;
}
public void addLimit(int startingZeroBasedIndex, int numberOfRowsDesired, String mainTableAlias,
String mainTablePkeyColumn)
{
this.limitPart = new LimitPart(startingZeroBasedIndex, numberOfRowsDesired, mainTableAlias,
mainTablePkeyColumn);
}
public void addLimit(int startingZeroBasedIndex, int numberOfRowsDesired, String mainTableAlias,
ColumnMetadata mainTablePkeyColumn)
{
addLimit(startingZeroBasedIndex, numberOfRowsDesired, mainTableAlias, mainTablePkeyColumn.getName());
}
public LimitPart getLimitPart()
{
return limitPart;
}
public String[] getSelectParts()
{
return StringUtils.toArray(select);
}
public String[] getGroupByParts()
{
return StringUtils.toArray(groupBy);
}
public String[] getHavingParts()
{
return StringUtils.toArray(having);
}
public FromPart[] getFromParts()
{
return (FromPart[]) from.toArray(new FromPart[from.size()]);
}
public SQLWhere getWherePart()
{
return where;
}
public OrderByPart[] getOrderByParts()
{
return (OrderByPart[]) orderBy.toArray(new OrderByPart[orderBy.size()]);
}
/** INNER CLASSES **/
public static class LimitPart implements Cloneable
{
private int startingZeroBasedIndex;
public int numberOfRowsDesired;
public String mainTableAlias;
public String mainTablePkeyColumn;
public LimitPart(int startingZeroBasedIndex, int numberOfRowsDesired, String mainTableAlias,
String mainTablePkeyColumn)
{
this.setStartingZeroBasedIndex(startingZeroBasedIndex);
this.numberOfRowsDesired = numberOfRowsDesired;
this.mainTableAlias = mainTableAlias;
this.mainTablePkeyColumn = mainTablePkeyColumn;
}
public int getStartingZeroBasedIndex()
{
return startingZeroBasedIndex;
}
public void setStartingZeroBasedIndex(int startingZeroBasedIndex)
{
if (startingZeroBasedIndex < 0)
{ throw new Error("startingZeroBasedIndex: " + startingZeroBasedIndex + " must be greater than 0."); }
this.startingZeroBasedIndex = startingZeroBasedIndex;
}
}
public static class OrderByPart implements Cloneable
{
public String part = null;
public boolean ascending = false;
public OrderByPart(String part, boolean ascending)
{
this.part = part;
this.ascending = ascending;
}
public String toString(boolean isFirst)
{
String sql = part + (ascending ? " ASC " : " DESC ");
if (!isFirst)
{
sql = (isFirst ? " " : ", ") + sql;
}
return sql;
}
}
public static class FromPart implements Cloneable
{
public String part = null;
public boolean isJoin = false;
public FromPart(String part, boolean isJoin)
{
this.part = part;
this.isJoin = isJoin;
}
public String toString(boolean isFirst)
{
String sql = part;
if (!isFirst)
{
sql = (isJoin ? " " : ", ") + sql;
}
return sql;
}
}
}
| apache-2.0 |
VirtualGamer/SnowEngine | Dependencies/opengl/src/org/lwjgl/opengl/WGLARBFramebufferSRGB.java | 977 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengl;
/**
* Native bindings to the <a href="http://www.opengl.org/registry/specs/ARB/framebuffer_sRGB.txt">WGL_ARB_framebuffer_sRGB</a> extension.
*
* <p>WGL functionality for {@link ARBFramebufferSRGB ARB_framebuffer_sRGB}.</p>
*
* <p>Requires {@link WGLEXTExtensionsString WGL_EXT_extensions_string}, {@link WGLARBPixelFormat WGL_ARB_pixel_format} and {@link ARBFramebufferObject ARB_framebuffer_object}.</p>
*/
public final class WGLARBFramebufferSRGB {
/**
* Accepted by the {@code attributes} parameter of {@link WGLARBPixelFormat#wglGetPixelFormatAttribiARB GetPixelFormatAttribiARB} and the {@code attribIList} of
* {@link WGLARBPixelFormat#wglChoosePixelFormatARB ChoosePixelFormatARB}.
*/
public static final int WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB = 0x20A9;
private WGLARBFramebufferSRGB() {}
} | apache-2.0 |
baowp/platform | biz/src/main/java/com/abbcc/module/product/PopularizeAction.java | 2146 | package com.abbcc.module.product;
import java.util.Date;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import com.abbcc.action.BaseAction;
import com.abbcc.common.CommonConst;
import com.abbcc.models.AbcPopularize;
import com.abbcc.service.PopularizeService;
import com.abbcc.service.ProductService;
import com.abbcc.util.StringUtil;
import com.abbcc.util.checkKey.CheckKey;
public class PopularizeAction extends BaseAction<AbcPopularize> {
private PopularizeService popularizeService;
public void setPopularizeService(PopularizeService popularizeService) {
this.popularizeService = popularizeService;
}
private String entId;
private String[] prodIds;
private String entName;
private String searchKey;
private String prodState=CommonConst.STATEINIT;
private String SEARCH="search";
private String LISTSEARCH="listsearch";
public String view(){
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(AbcPopularize.class);
detachedCriteria.add(Restrictions.eq("state", CommonConst.STATENORMAL));
detachedCriteria.addOrder(Order.desc("addTime"));
this.startIndex = (this.page - 1) * pageSize;
this.pageList = popularizeService.findPageByCriteria(detachedCriteria,
pageSize, startIndex);
if (pageList.getTotalCount() == 0)
result = CommonConst.NORESULT;
return VIEW;
}
public String add(){
return "add";
}
public String save(){
if (!CheckKey.checkKey(entity.getKey())) {
this.addFieldError("key", "存在非法字符!");
return INPUT;
}
if (!CheckKey.checkKey(entity.getpName())) {
this.addFieldError("pName", "存在非法字符!");
return INPUT;
}
entity.setAddTime(new Date());
entity.setAdminId(this.getCurrentAdmin().getAdminId());
entity.setState(CommonConst.STATENORMAL);
popularizeService.save(entity);
this.result=CommonConst.ADDSUCCESS;
return "save";
}
public String del(){
entity.setState(CommonConst.STATEDEL);
popularizeService.saveOrUpdate(entity);
this.result=CommonConst.DELSUCCESS;
return "save";
}
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202202/AdSpotTargetingType.java | 3855 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* AdSpotTargetingType.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202202;
public class AdSpotTargetingType implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected AdSpotTargetingType(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _NOT_REQUIRED = "NOT_REQUIRED";
public static final java.lang.String _EXPLICITLY_TARGETED = "EXPLICITLY_TARGETED";
public static final java.lang.String _EXPLICITLY_TARGETED_EXCEPT_HOUSE = "EXPLICITLY_TARGETED_EXCEPT_HOUSE";
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final AdSpotTargetingType NOT_REQUIRED = new AdSpotTargetingType(_NOT_REQUIRED);
public static final AdSpotTargetingType EXPLICITLY_TARGETED = new AdSpotTargetingType(_EXPLICITLY_TARGETED);
public static final AdSpotTargetingType EXPLICITLY_TARGETED_EXCEPT_HOUSE = new AdSpotTargetingType(_EXPLICITLY_TARGETED_EXCEPT_HOUSE);
public static final AdSpotTargetingType UNKNOWN = new AdSpotTargetingType(_UNKNOWN);
public java.lang.String getValue() { return _value_;}
public static AdSpotTargetingType fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
AdSpotTargetingType enumeration = (AdSpotTargetingType)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static AdSpotTargetingType fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AdSpotTargetingType.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "AdSpotTargetingType"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| apache-2.0 |
illicitonion/buck | src/com/facebook/buck/util/cache/WatchedFileHashCache.java | 2581 | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.util.cache;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.io.WatchEvents;
import com.facebook.buck.log.Logger;
import com.google.common.collect.Maps;
import com.google.common.eventbus.Subscribe;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.Optional;
public class WatchedFileHashCache extends DefaultFileHashCache {
private static final Logger LOG = Logger.get(WatchedFileHashCache.class);
public WatchedFileHashCache(ProjectFilesystem projectFilesystem) {
super(projectFilesystem, Optional.empty());
}
/**
* Called when file change events are posted to the file change EventBus to invalidate cached
* build rules if required. {@link Path}s contained within events must all be relative to the
* {@link ProjectFilesystem} root.
*/
@Subscribe
public synchronized void onFileSystemChange(WatchEvent<?> event) {
if (WatchEvents.isPathChangeEvent(event)) {
// Path event, remove the path from the cache as it has been changed, added or deleted.
final Path path = ((Path) event.context()).normalize();
LOG.verbose("Invalidating %s", path);
Iterable<Path> pathsToInvalidate =
Maps.filterEntries(
loadingCache.asMap(),
entry -> {
switch (entry.getValue().getType()) {
case ARCHIVE:
case FILE:
return path.equals(entry.getKey());
case DIRECTORY:
return path.startsWith(entry.getKey());
}
return false;
}
).keySet();
LOG.verbose("Paths to invalidate: %s", pathsToInvalidate);
loadingCache.invalidateAll(pathsToInvalidate);
} else {
// Non-path change event, likely an overflow due to many change events: invalidate everything.
LOG.debug("Invalidating all");
loadingCache.invalidateAll();
}
}
}
| apache-2.0 |
araqne/logdb | araqne-logdb/src/main/java/org/araqne/logdb/SubQueryCommand.java | 86 | package org.araqne.logdb;
public interface SubQueryCommand {
Query getSubQuery();
}
| apache-2.0 |
baev/allure-report | generator/src/main/java/org/allurefw/report/utils/ListUtils.java | 1214 | package org.allurefw.report.utils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* @author charlie (Dmitry Baev).
*/
public final class ListUtils {
ListUtils() {
}
public static <T> T computeIfAbsent(List<T> list, Predicate<T> predicate, Supplier<T> defaultValue) {
Optional<T> any = list.stream().filter(predicate).findAny();
if (any.isPresent()) {
return any.get();
}
T value = defaultValue.get();
list.add(value);
return value;
}
public static <T, S> Predicate<T> compareBy(Function<T, S> map, Supplier<S> compareWith) {
return item -> Objects.nonNull(item) && Objects.equals(map.apply(item), compareWith.get());
}
public static <T> T firstNonNull(T... items) {
return Stream.of(items)
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new IllegalStateException("firstNonNull method should have at " +
"least one non null parameter"));
}
}
| apache-2.0 |
sauloperez/sos | src/coding/json/src/main/java/org/n52/sos/encode/json/impl/FieldEncoder.java | 8871 | /**
* Copyright (C) 2013
* by 52 North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* info@52north.org
*
* This program is free software; you can redistribute and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; even without 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 (see gnu-gpl v2.txt). If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or
* visit the Free Software Foundation web page, http://www.fsf.org.
*/
package org.n52.sos.encode.json.impl;
import static org.n52.sos.util.DateTimeHelper.formatDateTime2IsoString;
import org.n52.sos.coding.json.JSONConstants;
import org.n52.sos.encode.json.JSONEncoder;
import org.n52.sos.exception.ows.concrete.UnsupportedEncoderInputException;
import org.n52.sos.ogc.ows.OwsExceptionReport;
import org.n52.sos.ogc.swe.SweAbstractDataComponent;
import org.n52.sos.ogc.swe.SweField;
import org.n52.sos.ogc.swe.simpleType.SweBoolean;
import org.n52.sos.ogc.swe.simpleType.SweCategory;
import org.n52.sos.ogc.swe.simpleType.SweCount;
import org.n52.sos.ogc.swe.simpleType.SweCountRange;
import org.n52.sos.ogc.swe.simpleType.SweObservableProperty;
import org.n52.sos.ogc.swe.simpleType.SweQuantity;
import org.n52.sos.ogc.swe.simpleType.SweQuantityRange;
import org.n52.sos.ogc.swe.simpleType.SweText;
import org.n52.sos.ogc.swe.simpleType.SweTime;
import org.n52.sos.ogc.swe.simpleType.SweTimeRange;
import org.n52.sos.util.DateTimeHelper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* TODO JavaDoc
*
* @author Christian Autermann <c.autermann@52north.org>
*
* @since 4.0.0
*/
public class FieldEncoder extends JSONEncoder<SweField> {
public FieldEncoder() {
super(SweField.class);
}
@Override
public JsonNode encodeJSON(SweField field) throws OwsExceptionReport {
switch (field.getElement().getDataComponentType()) {
case Count:
return encodeSweCountField(field);
case Boolean:
return encodeSweBooleanField(field);
case CountRange:
return encodeSweCountRangeField(field);
case ObservableProperty:
return encodeSweObservableProperyField(field);
case Text:
return encodeSweTextField(field);
case Quantity:
return encodeSweQuantityField(field);
case QuantityRange:
return encodeSweQuantityRangeField(field);
case Time:
return encodeSweTimeField(field);
case TimeRange:
return encodeSweTimeRangeField(field);
case Category:
return encodeSweCategoryField(field);
default:
throw new UnsupportedEncoderInputException(this, field);
}
}
private ObjectNode createField(SweField field) {
ObjectNode jfield = nodeFactory().objectNode();
jfield.put(JSONConstants.NAME, field.getName());
SweAbstractDataComponent element = field.getElement();
if (element.isSetDefinition()) {
jfield.put(JSONConstants.DEFINITION, element.getDefinition());
}
if (element.isSetDescription()) {
jfield.put(JSONConstants.DESCRIPTION, element.getDescription());
}
if (element.isSetIdentifier()) {
jfield.put(JSONConstants.IDENTIFIER, element.getIdentifier());
}
if (element.isSetLabel()) {
jfield.put(JSONConstants.LABEL, element.getLabel());
}
return jfield;
}
private ObjectNode encodeSweCountField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.COUNT_TYPE);
SweCount sweCount = (SweCount) field.getElement();
if (sweCount.isSetValue()) {
jfield.put(JSONConstants.VALUE, sweCount.getValue());
}
return jfield;
}
private ObjectNode encodeSweBooleanField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.BOOLEAN_TYPE);
SweBoolean sweBoolean = (SweBoolean) field.getElement();
if (sweBoolean.isSetValue()) {
jfield.put(JSONConstants.VALUE, sweBoolean.getValue());
}
return jfield;
}
private ObjectNode encodeSweCountRangeField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.COUNT_RANGE_TYPE);
SweCountRange sweCountRange = (SweCountRange) field.getElement();
if (sweCountRange.isSetValue()) {
ArrayNode av = jfield.putArray(JSONConstants.VALUE);
av.add(sweCountRange.getValue().getRangeStart());
av.add(sweCountRange.getValue().getRangeEnd());
}
return jfield;
}
private ObjectNode encodeSweObservableProperyField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.OBSERVABLE_PROPERTY_TYPE);
SweObservableProperty sweObservableProperty = (SweObservableProperty) field.getElement();
if (sweObservableProperty.isSetValue()) {
jfield.put(JSONConstants.VALUE, sweObservableProperty.getValue());
}
return jfield;
}
private ObjectNode encodeSweTextField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.TEXT_TYPE);
SweText sweText = (SweText) field.getElement();
if (sweText.isSetValue()) {
jfield.put(JSONConstants.VALUE, sweText.getValue());
}
return jfield;
}
private ObjectNode encodeSweQuantityField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.QUANTITY_TYPE);
SweQuantity sweQuantity = (SweQuantity) field.getElement();
if (sweQuantity.isSetValue()) {
jfield.put(JSONConstants.VALUE, sweQuantity.getValue());
}
jfield.put(JSONConstants.UOM, sweQuantity.getUom());
return jfield;
}
private ObjectNode encodeSweQuantityRangeField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.QUANTITY_RANGE_TYPE);
SweQuantityRange sweQuantityRange = (SweQuantityRange) field.getElement();
jfield.put(JSONConstants.UOM, sweQuantityRange.getUom());
if (sweQuantityRange.isSetValue()) {
ArrayNode av = jfield.putArray(JSONConstants.VALUE);
av.add(sweQuantityRange.getValue().getRangeStart());
av.add(sweQuantityRange.getValue().getRangeEnd());
}
return jfield;
}
private ObjectNode encodeSweTimeField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.TIME_TYPE);
SweTime sweTime = (SweTime) field.getElement();
jfield.put(JSONConstants.UOM, sweTime.getUom());
if (sweTime.isSetValue()) {
jfield.put(JSONConstants.VALUE, formatDateTime2IsoString(sweTime.getValue()));
}
return jfield;
}
private ObjectNode encodeSweTimeRangeField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.TIME_RANGE_TYPE);
SweTimeRange sweTimeRange = (SweTimeRange) field.getElement();
jfield.put(JSONConstants.UOM, sweTimeRange.getUom());
if (sweTimeRange.isSetValue()) {
ArrayNode av = jfield.putArray(JSONConstants.VALUE);
av.add(DateTimeHelper.formatDateTime2IsoString(sweTimeRange.getValue().getRangeStart()));
av.add(DateTimeHelper.formatDateTime2IsoString(sweTimeRange.getValue().getRangeEnd()));
}
return jfield;
}
private ObjectNode encodeSweCategoryField(SweField field) {
ObjectNode jfield = createField(field);
jfield.put(JSONConstants.TYPE, JSONConstants.CATEGORY_TYPE);
SweCategory sweCategory = (SweCategory) field.getElement();
jfield.put(JSONConstants.CODESPACE, sweCategory.getCodeSpace());
if (sweCategory.isSetValue()) {
jfield.put(JSONConstants.VALUE, sweCategory.getValue());
}
return jfield;
}
}
| apache-2.0 |
RenukaGurumurthy/nucleus-indexer-tracker | src/main/java/org/gooru/index/tracker/responses/transformers/HttpResponseTransformer.java | 3916 | package org.gooru.index.tracker.responses.transformers;
import java.util.HashMap;
import java.util.Map;
import org.gooru.index.tracker.constants.MessageConstants;
import org.gooru.index.tracker.responses.transformers.ResponseTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
class HttpResponseTransformer implements ResponseTransformer {
private static final Logger LOG = LoggerFactory.getLogger(ResponseTransformer.class);
private final Message<Object> message;
private boolean transformed = false;
private Map<String, String> headers;
private int httpStatus;
private JsonObject httpBody;
public HttpResponseTransformer(Message<Object> message) {
this.message = message;
if (message == null) {
LOG.error("Invalid or null Message<Object> for initialization");
throw new IllegalArgumentException("Invalid or null Message<Object> for initialization");
}
if (!(message.body() instanceof JsonObject)) {
LOG.error("Message body should be JsonObject");
throw new IllegalArgumentException("Message body should be JsonObject");
}
}
@Override
public void transform() {
if (!this.transformed) {
processTransformation();
this.transformed = true;
}
}
@Override
public JsonObject transformedBody() {
transform();
return this.httpBody;
}
@Override
public Map<String, String> transformedHeaders() {
transform();
return this.headers;
}
@Override
public int transformedStatus() {
transform();
return this.httpStatus;
}
private void processTransformation() {
JsonObject messageBody = (JsonObject) message.body();
// First initialize the http status
this.httpStatus = messageBody.getInteger(MessageConstants.MSG_HTTP_STATUS);
// Then initialize the headers
processHeaders(messageBody);
JsonObject httpBodyContainer = messageBody.getJsonObject(MessageConstants.MSG_HTTP_BODY);
// Now delegate the body handling
String result = message.headers().get(MessageConstants.MSG_OP_STATUS);
if (result != null && result.equalsIgnoreCase(MessageConstants.MSG_OP_STATUS_SUCCESS)) {
processSuccessTransformation(httpBodyContainer);
} else if (result != null && result.equalsIgnoreCase(MessageConstants.MSG_OP_STATUS_ERROR)) {
processErrorTransformation(httpBodyContainer);
} else if (result != null && result.equalsIgnoreCase(MessageConstants.MSG_OP_STATUS_VALIDATION_ERROR)) {
processValidationErrorTransformation(httpBodyContainer);
} else {
LOG.error("Invalid or incorrect message header passed on for operation");
throw new IllegalStateException("Invalid or incorrect message header passed on for operation");
}
// Now that we are done, mark it as transformed
this.transformed = true;
}
private void processHeaders(JsonObject jsonObject) {
JsonObject jsonHeaders = jsonObject.getJsonObject(MessageConstants.MSG_HTTP_HEADERS);
this.headers = new HashMap<>();
if (jsonHeaders != null && !jsonHeaders.isEmpty()) {
Map<String, Object> headerMap = jsonHeaders.getMap();
for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
this.headers.put(entry.getKey(), entry.getValue().toString());
}
}
}
private void processValidationErrorTransformation(JsonObject messageBody) {
this.httpBody = messageBody.getJsonObject(MessageConstants.MSG_HTTP_VALIDATION_ERROR);
}
private void processErrorTransformation(JsonObject messageBody) {
this.httpBody = messageBody.getJsonObject(MessageConstants.MSG_HTTP_ERROR);
}
private void processSuccessTransformation(JsonObject messageBody) {
this.httpBody = messageBody.getJsonObject(MessageConstants.MSG_HTTP_RESPONSE);
}
}
| apache-2.0 |
qw3rtrun/aubengine | src/main/java/org/qw3rtrun/aub/engine/opengl/Uniform.java | 1310 | package org.qw3rtrun.aub.engine.opengl;
import javafx.beans.property.Property;
import org.lwjgl.opengl.GL20;
import org.qw3rtrun.aub.engine.vectmath.Matrix4f;
import org.qw3rtrun.aub.engine.vectmath.Vector3f;
public abstract class Uniform<T> {
private final String name;
private final Shader shader;
private final int location;
private final Property<T> value;
protected Uniform(String name, Shader shader, int location, Property<T> value) {
this.name = name;
this.shader = shader;
this.location = location;
this.value = value;
value.addListener((self, old, _new) -> program(shader.self(), location, _new));
}
public static Uniform<Matrix4f> getUniformMat4(Shader shader, String name) {
return new UniformMat4(name, shader, GL20.glGetUniformLocation(shader.self(), name));
}
public static Uniform<Vector3f> getUniform2f(Shader shader, String name) {
return new Uniform2f(name, shader, GL20.glGetUniformLocation(shader.self(), name));
}
public Property<T> valueProperty() {
return value;
}
public String getName() {
return name;
}
public int getLocation() {
return location;
}
protected abstract void program(int program, int location, T value);
}
| apache-2.0 |
JasonBian/azkaban | azkaban-common/src/test/java/azkaban/trigger/JdbcTriggerLoaderTest.java | 7068 | /*
* Copyright 2014 LinkedIn Corp.
*
* 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 azkaban.trigger;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
import azkaban.database.DataSourceUtils;
import azkaban.executor.ExecutionOptions;
import azkaban.trigger.builtin.BasicTimeChecker;
import azkaban.trigger.builtin.ExecuteFlowAction;
import azkaban.utils.Props;
import azkaban.utils.Utils;
public class JdbcTriggerLoaderTest {
private static boolean testDBExists = false;
// @TODO remove this and turn into local host.
private static final String host = "localhost";
private static final int port = 3306;
private static final String database = "azkaban2";
private static final String user = "azkaban";
private static final String password = "azkaban";
private static final int numConnections = 10;
private TriggerLoader loader;
private CheckerTypeLoader checkerLoader;
private ActionTypeLoader actionLoader;
@Before
public void setup() throws TriggerException {
Props props = new Props();
props.put("database.type", "mysql");
props.put("mysql.host", host);
props.put("mysql.port", port);
props.put("mysql.user", user);
props.put("mysql.database", database);
props.put("mysql.password", password);
props.put("mysql.numconnections", numConnections);
loader = new JdbcTriggerLoader(props);
checkerLoader = new CheckerTypeLoader();
checkerLoader.init(new Props());
Condition.setCheckerLoader(checkerLoader);
actionLoader = new ActionTypeLoader();
actionLoader.init(new Props());
Trigger.setActionTypeLoader(actionLoader);
setupDB();
}
public void setupDB() {
DataSource dataSource =
DataSourceUtils.getMySQLDataSource(host, port, database, user,
password, numConnections, 3000l);
testDBExists = true;
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
testDBExists = false;
DbUtils.closeQuietly(connection);
return;
}
CountHandler countHandler = new CountHandler();
QueryRunner runner = new QueryRunner();
try {
runner.query(connection, "SELECT COUNT(1) FROM triggers", countHandler);
} catch (SQLException e) {
e.printStackTrace();
testDBExists = false;
DbUtils.closeQuietly(connection);
return;
}
DbUtils.closeQuietly(connection);
clearDB();
}
@After
public void clearDB() {
if (!testDBExists) {
return;
}
DataSource dataSource =
DataSourceUtils.getMySQLDataSource(host, port, database, user,
password, numConnections, 3000l);
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
testDBExists = false;
DbUtils.closeQuietly(connection);
return;
}
QueryRunner runner = new QueryRunner();
try {
runner.update(connection, "DELETE FROM triggers");
} catch (SQLException e) {
e.printStackTrace();
testDBExists = false;
DbUtils.closeQuietly(connection);
return;
}
DbUtils.closeQuietly(connection);
}
@Ignore @Test
public void addTriggerTest() throws TriggerLoaderException {
Trigger t1 = createTrigger("testProj1", "testFlow1", "source1");
Trigger t2 = createTrigger("testProj2", "testFlow2", "source2");
loader.addTrigger(t1);
List<Trigger> ts = loader.loadTriggers();
assertTrue(ts.size() == 1);
Trigger t3 = ts.get(0);
assertTrue(t3.getSource().equals("source1"));
loader.addTrigger(t2);
ts = loader.loadTriggers();
assertTrue(ts.size() == 2);
for (Trigger t : ts) {
if (t.getTriggerId() == t2.getTriggerId()) {
t.getSource().equals(t2.getSource());
}
}
}
@Ignore @Test
public void removeTriggerTest() throws TriggerLoaderException {
Trigger t1 = createTrigger("testProj1", "testFlow1", "source1");
Trigger t2 = createTrigger("testProj2", "testFlow2", "source2");
loader.addTrigger(t1);
loader.addTrigger(t2);
List<Trigger> ts = loader.loadTriggers();
assertTrue(ts.size() == 2);
loader.removeTrigger(t2);
ts = loader.loadTriggers();
assertTrue(ts.size() == 1);
assertTrue(ts.get(0).getTriggerId() == t1.getTriggerId());
}
@Ignore @Test
public void updateTriggerTest() throws TriggerLoaderException {
Trigger t1 = createTrigger("testProj1", "testFlow1", "source1");
t1.setResetOnExpire(true);
loader.addTrigger(t1);
List<Trigger> ts = loader.loadTriggers();
assertTrue(ts.get(0).isResetOnExpire() == true);
t1.setResetOnExpire(false);
loader.updateTrigger(t1);
ts = loader.loadTriggers();
assertTrue(ts.get(0).isResetOnExpire() == false);
}
private Trigger createTrigger(String projName, String flowName, String source) {
DateTime now = DateTime.now();
ConditionChecker checker1 =
new BasicTimeChecker("timeChecker1", now.getMillis(), now.getZone(),
true, true, Utils.parsePeriodString("1h"));
Map<String, ConditionChecker> checkers1 =
new HashMap<String, ConditionChecker>();
checkers1.put(checker1.getId(), checker1);
String expr1 = checker1.getId() + ".eval()";
Condition triggerCond = new Condition(checkers1, expr1);
Condition expireCond = new Condition(checkers1, expr1);
List<TriggerAction> actions = new ArrayList<TriggerAction>();
TriggerAction action =
new ExecuteFlowAction("executeAction", 1, projName, flowName,
"azkaban", new ExecutionOptions(), null);
actions.add(action);
Trigger t =
new Trigger(now.getMillis(), now.getMillis(), "azkaban", source,
triggerCond, expireCond, actions);
return t;
}
public static class CountHandler implements ResultSetHandler<Integer> {
@Override
public Integer handle(ResultSet rs) throws SQLException {
int val = 0;
while (rs.next()) {
val++;
}
return val;
}
}
}
| apache-2.0 |
navicore/oemap | android/OeMap/src/main/java/com/onextent/oemap/settings/SpaceSettingsDialog.java | 4416 | /*
* Copyright (c) 2013. Ed Sweeney. All Rights Reserved.
*/
package com.onextent.oemap.settings;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.SeekBar;
import com.onextent.android.util.OeLog;
import com.onextent.oemap.OeMapActivity;
import com.onextent.oemap.R;
import com.onextent.oemap.provider.SpaceHelper;
public class SpaceSettingsDialog extends BaseSpaceSettingsDialog {
private String _space = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
if (args != null)
_space = args.getString(getString(R.string.bundle_spacename));
View view = inflater.inflate(R.layout.space_settings_dialog, container);
setupQuitTimeSeekBar(view);
setupMaxPresenceSeekBar(view);
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setTitle(_space);
OeMapActivity a = (OeMapActivity) getActivity();
if (_space == null || (!_space.equals(a.getCurrentSpaceId()))) {
OeLog.w("map name for dialog and active map do not match: " + _space + " vs " + a.getCurrentSpaceId()); //tmp todo: ejs
}
return view;
}
protected void setupMaxPresenceSeekBar(View view) {
SeekBar seek = (SeekBar) view.findViewById(R.id.max_presence_edit_SeekBar);
final EditText maxText = (EditText) view.findViewById(R.id.max_presence_edit_fld);
final SpaceHelper h = new SpaceHelper(getActivity());
final SpaceHelper.Space s = h.getSpace(_space);
int max = SpaceHelper.PRESENCE_PARAM_DEFAULT_MAX_COUNT;
if (s != null) {
max = s.getMaxPoints();
}
ProgressCallback cb = new ProgressCallback() {
@Override
public void setProgress(int progress) {
if (s != null) {
s.setMaxPoints(progress);
h.deleteSpacename(_space);
h.insert(s);
OeMapActivity a = (OeMapActivity) getActivity();
a.wakePresenceService();
}
}
};
setMaxChangeListener(maxText, seek, max, cb);
}
@Override
public void onPause() {
OeMapActivity a = (OeMapActivity) getActivity();
super.onPause();
}
private void setupQuitTimeSeekBar(View view) {
SeekBar seek = (SeekBar) view.findViewById(R.id.space_settings_quitTimeSeekBar);
final EditText time = (EditText) view.findViewById(R.id.space_settings_quitTime);
setEditTextDate(time, _space);
setSeekBarProgress(seek, _space);
seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
setQuitDate(i);
if (_progressMsg != null) {
time.setText(_progressMsg);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
SpaceHelper h = new SpaceHelper(getActivity());
SpaceHelper.Space s = h.getSpace(_space);
if (h == null) throw new NullPointerException("no space to update");
h.deleteSpacename(_space);
if (_quitDate != null) {
time.setText(DateUtils.getRelativeDateTimeString(getActivity(),
_quitDate.getTime(), DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0));
s.setLease(_quitDate);
h.insert(s);
} else {
time.setText("Until I manually quit");
h.insert(s);
}
OeMapActivity a = (OeMapActivity) getActivity();
a.wakePresenceService();
}
});
}
}
| apache-2.0 |
LionKingzlq/NettyDemo | ClientDemo/src/main/java/com/abraham/netty/ClientMain.java | 2616 | package com.abraham.netty;
import com.abraham.netty.handler.MsgpackDecoder;
import com.abraham.netty.handler.MsgpackEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.string.StringDecoder;
/**
* Created by Abraham on 2017/2/27.
*/
public class ClientMain {
public static void main(String[] args) throws Exception{
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (Exception e) {
}
}
new ClientMain().connect(port, "127.0.0.1");
}
public void connect(int port, String host) throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// socketChannel.pipeline().addLast("msgpack decoder", new MsgpackDecoder());
// socketChannel.pipeline().addLast("msgpack encoder",new MsgpackEncoder());
socketChannel.pipeline().addLast(new HttpResponseDecoder());
socketChannel.pipeline().addLast(new HttpRequestEncoder());
socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new ClientChannelHandler());
}
});
ChannelFuture f = b.connect(host,port).sync();
f.channel().closeFuture().sync();
}catch (Exception e){
}finally {
group.shutdownGracefully();
}
}
}
| apache-2.0 |
andrea-pilzer/riciclo_qrcode | sco.riciclo-web/src/main/java/it/smartcommunitylab/riciclo/model/Riciclabolario.java | 1581 | /**
* Copyright 2015 Fondazione Bruno Kessler - Trento RISE
*
* 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 it.smartcommunitylab.riciclo.model;
public class Riciclabolario extends BaseObject {
private String nome;
private String area;
private String tipologiaUtenza;
private String tipologiaRifiuto;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getTipologiaUtenza() {
return tipologiaUtenza;
}
public void setTipologiaUtenza(String tipologiaUtenza) {
this.tipologiaUtenza = tipologiaUtenza;
}
public String getTipologiaRifiuto() {
return tipologiaRifiuto;
}
public void setTipologiaRifiuto(String tipologiaRifiuto) {
this.tipologiaRifiuto = tipologiaRifiuto;
}
@Override
public String toString() {
return "Riciclabolario [" + nome + "," + area + "," + tipologiaUtenza + "," + tipologiaRifiuto + "]";
}
}
| apache-2.0 |
google-code-export/google-api-dfp-java | src/com/google/api/ads/dfp/v201211/Size.java | 6821 | /**
* Size.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201211;
/**
* Represents the dimensions of an {@link AdUnit}, {@link LineItem}
* or {@link Creative}.
* <p>
* For interstitial size (out-of-page), {@code Size} must
* be 1x1.
*/
public class Size implements java.io.Serializable {
/* The width of the {@link AdUnit}, {@link LineItem} or {@link
* Creative}. */
private java.lang.Integer width;
/* The height of the {@link AdUnit}, {@link LineItem} or {@link
* Creative}. */
private java.lang.Integer height;
/* True if this size represents an aspect ratio, false otherwise. */
private java.lang.Boolean isAspectRatio;
public Size() {
}
public Size(
java.lang.Integer width,
java.lang.Integer height,
java.lang.Boolean isAspectRatio) {
this.width = width;
this.height = height;
this.isAspectRatio = isAspectRatio;
}
/**
* Gets the width value for this Size.
*
* @return width * The width of the {@link AdUnit}, {@link LineItem} or {@link
* Creative}.
*/
public java.lang.Integer getWidth() {
return width;
}
/**
* Sets the width value for this Size.
*
* @param width * The width of the {@link AdUnit}, {@link LineItem} or {@link
* Creative}.
*/
public void setWidth(java.lang.Integer width) {
this.width = width;
}
/**
* Gets the height value for this Size.
*
* @return height * The height of the {@link AdUnit}, {@link LineItem} or {@link
* Creative}.
*/
public java.lang.Integer getHeight() {
return height;
}
/**
* Sets the height value for this Size.
*
* @param height * The height of the {@link AdUnit}, {@link LineItem} or {@link
* Creative}.
*/
public void setHeight(java.lang.Integer height) {
this.height = height;
}
/**
* Gets the isAspectRatio value for this Size.
*
* @return isAspectRatio * True if this size represents an aspect ratio, false otherwise.
*/
public java.lang.Boolean getIsAspectRatio() {
return isAspectRatio;
}
/**
* Sets the isAspectRatio value for this Size.
*
* @param isAspectRatio * True if this size represents an aspect ratio, false otherwise.
*/
public void setIsAspectRatio(java.lang.Boolean isAspectRatio) {
this.isAspectRatio = isAspectRatio;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof Size)) return false;
Size other = (Size) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.width==null && other.getWidth()==null) ||
(this.width!=null &&
this.width.equals(other.getWidth()))) &&
((this.height==null && other.getHeight()==null) ||
(this.height!=null &&
this.height.equals(other.getHeight()))) &&
((this.isAspectRatio==null && other.getIsAspectRatio()==null) ||
(this.isAspectRatio!=null &&
this.isAspectRatio.equals(other.getIsAspectRatio())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getWidth() != null) {
_hashCode += getWidth().hashCode();
}
if (getHeight() != null) {
_hashCode += getHeight().hashCode();
}
if (getIsAspectRatio() != null) {
_hashCode += getIsAspectRatio().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(Size.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "Size"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("width");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "width"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("height");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "height"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isAspectRatio");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "isAspectRatio"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-sesv2/src/main/java/com/amazonaws/services/simpleemailv2/model/ListContactsFilter.java | 6777 | /*
* 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.simpleemailv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* A filter that can be applied to a list of contacts.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sesv2-2019-09-27/ListContactsFilter" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListContactsFilter implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* </p>
*/
private String filteredStatus;
/**
* <p>
* Used for filtering by a specific topic preference.
* </p>
*/
private TopicFilter topicFilter;
/**
* <p>
* The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* </p>
*
* @param filteredStatus
* The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* @see SubscriptionStatus
*/
public void setFilteredStatus(String filteredStatus) {
this.filteredStatus = filteredStatus;
}
/**
* <p>
* The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* </p>
*
* @return The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* @see SubscriptionStatus
*/
public String getFilteredStatus() {
return this.filteredStatus;
}
/**
* <p>
* The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* </p>
*
* @param filteredStatus
* The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see SubscriptionStatus
*/
public ListContactsFilter withFilteredStatus(String filteredStatus) {
setFilteredStatus(filteredStatus);
return this;
}
/**
* <p>
* The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* </p>
*
* @param filteredStatus
* The status by which you are filtering: <code>OPT_IN</code> or <code>OPT_OUT</code>.
* @return Returns a reference to this object so that method calls can be chained together.
* @see SubscriptionStatus
*/
public ListContactsFilter withFilteredStatus(SubscriptionStatus filteredStatus) {
this.filteredStatus = filteredStatus.toString();
return this;
}
/**
* <p>
* Used for filtering by a specific topic preference.
* </p>
*
* @param topicFilter
* Used for filtering by a specific topic preference.
*/
public void setTopicFilter(TopicFilter topicFilter) {
this.topicFilter = topicFilter;
}
/**
* <p>
* Used for filtering by a specific topic preference.
* </p>
*
* @return Used for filtering by a specific topic preference.
*/
public TopicFilter getTopicFilter() {
return this.topicFilter;
}
/**
* <p>
* Used for filtering by a specific topic preference.
* </p>
*
* @param topicFilter
* Used for filtering by a specific topic preference.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListContactsFilter withTopicFilter(TopicFilter topicFilter) {
setTopicFilter(topicFilter);
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 (getFilteredStatus() != null)
sb.append("FilteredStatus: ").append(getFilteredStatus()).append(",");
if (getTopicFilter() != null)
sb.append("TopicFilter: ").append(getTopicFilter());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListContactsFilter == false)
return false;
ListContactsFilter other = (ListContactsFilter) obj;
if (other.getFilteredStatus() == null ^ this.getFilteredStatus() == null)
return false;
if (other.getFilteredStatus() != null && other.getFilteredStatus().equals(this.getFilteredStatus()) == false)
return false;
if (other.getTopicFilter() == null ^ this.getTopicFilter() == null)
return false;
if (other.getTopicFilter() != null && other.getTopicFilter().equals(this.getTopicFilter()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFilteredStatus() == null) ? 0 : getFilteredStatus().hashCode());
hashCode = prime * hashCode + ((getTopicFilter() == null) ? 0 : getTopicFilter().hashCode());
return hashCode;
}
@Override
public ListContactsFilter clone() {
try {
return (ListContactsFilter) 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.simpleemailv2.model.transform.ListContactsFilterMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
consulo/consulo-java | java-impl/src/main/java/com/intellij/refactoring/safeDelete/usageInfo/SafeDeleteExtendsClassUsageInfo.java | 3988 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.safeDelete.usageInfo;
import consulo.logging.Logger;
import com.intellij.psi.*;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.IncorrectOperationException;
/**
* @author ven
*/
public class SafeDeleteExtendsClassUsageInfo extends SafeDeleteReferenceUsageInfo {
private static final Logger LOG = Logger.getInstance(SafeDeleteExtendsClassUsageInfo.class);
private final PsiClass myExtendingClass;
private final PsiSubstitutor mySubstitutor;
public SafeDeleteExtendsClassUsageInfo(final PsiJavaCodeReferenceElement reference, PsiClass refClass, PsiClass extendingClass) {
super(reference, refClass, true);
myExtendingClass = extendingClass;
mySubstitutor = TypeConversionUtil.getClassSubstitutor(refClass, myExtendingClass, PsiSubstitutor.EMPTY);
LOG.assertTrue(mySubstitutor != null);
}
public PsiClass getReferencedElement() {
return (PsiClass)super.getReferencedElement();
}
public void deleteElement() throws IncorrectOperationException {
final PsiElement parent = getElement().getParent();
LOG.assertTrue(parent instanceof PsiReferenceList);
final PsiClass refClass = getReferencedElement();
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(refClass.getProject()).getElementFactory();
final PsiReferenceList extendsList = refClass.getExtendsList();
final PsiReferenceList extendingImplementsList = myExtendingClass.getImplementsList();
if (extendsList != null) {
final PsiClassType[] referenceTypes = extendsList.getReferencedTypes();
final PsiReferenceList listToAddExtends = refClass.isInterface() == myExtendingClass.isInterface() ? myExtendingClass.getExtendsList() : extendingImplementsList;
final PsiClassType[] existingRefTypes = listToAddExtends.getReferencedTypes();
for (PsiClassType referenceType : referenceTypes) {
if (ArrayUtilRt.find(existingRefTypes, referenceType) > -1) continue;
listToAddExtends.add(elementFactory.createReferenceElementByType((PsiClassType)mySubstitutor.substitute(referenceType)));
}
}
final PsiReferenceList implementsList = refClass.getImplementsList();
if (implementsList != null) {
final PsiClassType[] existingRefTypes = extendingImplementsList.getReferencedTypes();
PsiClassType[] referenceTypes = implementsList.getReferencedTypes();
for (PsiClassType referenceType : referenceTypes) {
if (ArrayUtilRt.find(existingRefTypes, referenceType) > -1) continue;
extendingImplementsList.add(elementFactory.createReferenceElementByType((PsiClassType)mySubstitutor.substitute(referenceType)));
}
}
getElement().delete();
}
public boolean isSafeDelete() {
if (getElement() == null) return false;
final PsiClass refClass = getReferencedElement();
if (refClass.getExtendsListTypes().length > 0) {
final PsiReferenceList listToAddExtends = refClass.isInterface() == myExtendingClass.isInterface() ? myExtendingClass.getExtendsList() :
myExtendingClass.getImplementsList();
if (listToAddExtends == null) return false;
}
if (refClass.getImplementsListTypes().length > 0) {
if (myExtendingClass.getImplementsList() == null) return false;
}
return true;
}
}
| apache-2.0 |
a1705164/Restaurante | Restaurante/Web/src/servlet/mapping/FuncaoServletMapping.java | 516 | package servlet.mapping;
import javax.servlet.http.HttpServletRequest;
import domain.Funcao;
public class FuncaoServletMapping {
public Funcao cadastrar(HttpServletRequest request){
Funcao funcao = new Funcao();
funcao.setDescricao(request.getParameter("descricao"));
return funcao;
}
public Funcao buscar(HttpServletRequest request){
return null;
}
public Funcao alterar(HttpServletRequest request){
return null;
}
public Funcao excluir(HttpServletRequest request){
return null;
}
}
| apache-2.0 |
Orange-OpenSource/matos-profiles | matos-android/src/main/java/com/android/org/bouncycastle/util/IPAddress.java | 1311 | package com.android.org.bouncycastle.util;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
public class IPAddress
{
// Constructors
public IPAddress(){
}
// Methods
public static boolean isValid(java.lang.String arg1){
return false;
}
public static boolean isValidIPv6WithNetmask(java.lang.String arg1){
return false;
}
public static boolean isValidIPv6(java.lang.String arg1){
return false;
}
public static boolean isValidIPv4WithNetmask(java.lang.String arg1){
return false;
}
public static boolean isValidIPv4(java.lang.String arg1){
return false;
}
public static boolean isValidWithNetMask(java.lang.String arg1){
return false;
}
}
| apache-2.0 |
wyukawa/presto | presto-main/src/main/java/io/prestosql/sql/gen/InCodeGenerator.java | 17681 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.gen;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import io.airlift.bytecode.BytecodeBlock;
import io.airlift.bytecode.BytecodeNode;
import io.airlift.bytecode.Scope;
import io.airlift.bytecode.Variable;
import io.airlift.bytecode.control.IfStatement;
import io.airlift.bytecode.control.SwitchStatement.SwitchBuilder;
import io.airlift.bytecode.instruction.LabelNode;
import io.prestosql.metadata.Metadata;
import io.prestosql.metadata.Signature;
import io.prestosql.operator.scalar.ScalarFunctionImplementation;
import io.prestosql.spi.function.OperatorType;
import io.prestosql.spi.type.BigintType;
import io.prestosql.spi.type.DateType;
import io.prestosql.spi.type.IntegerType;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.relational.ConstantExpression;
import io.prestosql.sql.relational.RowExpression;
import io.prestosql.util.FastutilSetHelper;
import java.lang.invoke.MethodHandle;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static io.airlift.bytecode.expression.BytecodeExpressions.constantFalse;
import static io.airlift.bytecode.expression.BytecodeExpressions.constantTrue;
import static io.airlift.bytecode.expression.BytecodeExpressions.invokeStatic;
import static io.airlift.bytecode.instruction.JumpInstruction.jump;
import static io.prestosql.spi.function.OperatorType.HASH_CODE;
import static io.prestosql.spi.function.OperatorType.INDETERMINATE;
import static io.prestosql.sql.gen.BytecodeUtils.ifWasNullPopAndGoto;
import static io.prestosql.sql.gen.BytecodeUtils.invoke;
import static io.prestosql.sql.gen.BytecodeUtils.loadConstant;
import static io.prestosql.util.FastutilSetHelper.toFastutilHashSet;
import static java.lang.Math.toIntExact;
import static java.util.Objects.requireNonNull;
public class InCodeGenerator
implements BytecodeGenerator
{
private final Metadata metadata;
public InCodeGenerator(Metadata metadata)
{
this.metadata = requireNonNull(metadata, "metadata is null");
}
enum SwitchGenerationCase
{
DIRECT_SWITCH,
HASH_SWITCH,
SET_CONTAINS
}
@VisibleForTesting
static SwitchGenerationCase checkSwitchGenerationCase(Type type, List<RowExpression> values)
{
if (values.size() > 32) {
// 32 is chosen because
// * SET_CONTAINS performs worst when smaller than but close to power of 2
// * Benchmark shows performance of SET_CONTAINS is better at 50, but similar at 25.
return SwitchGenerationCase.SET_CONTAINS;
}
if (!(type instanceof IntegerType || type instanceof BigintType || type instanceof DateType)) {
return SwitchGenerationCase.HASH_SWITCH;
}
for (RowExpression expression : values) {
// For non-constant expressions, they will be added to the default case in the generated switch code. They do not affect any of
// the cases other than the default one. Therefore, it's okay to skip them when choosing between DIRECT_SWITCH and HASH_SWITCH.
// Same argument applies for nulls.
if (!(expression instanceof ConstantExpression)) {
continue;
}
Object constant = ((ConstantExpression) expression).getValue();
if (constant == null) {
continue;
}
long longConstant = ((Number) constant).longValue();
if (longConstant < Integer.MIN_VALUE || longConstant > Integer.MAX_VALUE) {
return SwitchGenerationCase.HASH_SWITCH;
}
}
return SwitchGenerationCase.DIRECT_SWITCH;
}
@Override
public BytecodeNode generateExpression(Signature signature, BytecodeGeneratorContext generatorContext, Type returnType, List<RowExpression> arguments)
{
List<RowExpression> values = arguments.subList(1, arguments.size());
// empty IN statements are not allowed by the standard, and not possible here
// the implementation assumes this condition is always met
checkArgument(values.size() > 0, "values must not be empty");
Type type = arguments.get(0).getType();
Class<?> javaType = type.getJavaType();
SwitchGenerationCase switchGenerationCase = checkSwitchGenerationCase(type, values);
Signature hashCodeSignature = generatorContext.getMetadata().resolveOperator(HASH_CODE, ImmutableList.of(type));
MethodHandle hashCodeFunction = generatorContext.getMetadata().getScalarFunctionImplementation(hashCodeSignature).getMethodHandle();
Signature isIndeterminateSignature = generatorContext.getMetadata().resolveOperator(INDETERMINATE, ImmutableList.of(type));
ScalarFunctionImplementation isIndeterminateFunction = generatorContext.getMetadata().getScalarFunctionImplementation(isIndeterminateSignature);
ImmutableListMultimap.Builder<Integer, BytecodeNode> hashBucketsBuilder = ImmutableListMultimap.builder();
ImmutableList.Builder<BytecodeNode> defaultBucket = ImmutableList.builder();
ImmutableSet.Builder<Object> constantValuesBuilder = ImmutableSet.builder();
for (RowExpression testValue : values) {
BytecodeNode testBytecode = generatorContext.generate(testValue);
if (isDeterminateConstant(testValue, isIndeterminateFunction.getMethodHandle())) {
ConstantExpression constant = (ConstantExpression) testValue;
Object object = constant.getValue();
switch (switchGenerationCase) {
case DIRECT_SWITCH:
case SET_CONTAINS:
constantValuesBuilder.add(object);
break;
case HASH_SWITCH:
try {
int hashCode = toIntExact(Long.hashCode((Long) hashCodeFunction.invoke(object)));
hashBucketsBuilder.put(hashCode, testBytecode);
}
catch (Throwable throwable) {
throw new IllegalArgumentException("Error processing IN statement: error calculating hash code for " + object, throwable);
}
break;
default:
throw new IllegalArgumentException("Not supported switch generation case: " + switchGenerationCase);
}
}
else {
defaultBucket.add(testBytecode);
}
}
ImmutableListMultimap<Integer, BytecodeNode> hashBuckets = hashBucketsBuilder.build();
ImmutableSet<Object> constantValues = constantValuesBuilder.build();
LabelNode end = new LabelNode("end");
LabelNode match = new LabelNode("match");
LabelNode noMatch = new LabelNode("noMatch");
LabelNode defaultLabel = new LabelNode("default");
Scope scope = generatorContext.getScope();
Variable value = scope.createTempVariable(javaType);
BytecodeNode switchBlock;
Variable expression = scope.createTempVariable(int.class);
SwitchBuilder switchBuilder = new SwitchBuilder().expression(expression);
switch (switchGenerationCase) {
case DIRECT_SWITCH:
// A white-list is used to select types eligible for DIRECT_SWITCH.
// For these types, it's safe to not use presto HASH_CODE and EQUAL operator.
for (Object constantValue : constantValues) {
switchBuilder.addCase(toIntExact((Long) constantValue), jump(match));
}
switchBuilder.defaultCase(jump(defaultLabel));
switchBlock = new BytecodeBlock()
.comment("lookupSwitch(<stackValue>))")
.append(new IfStatement()
.condition(invokeStatic(InCodeGenerator.class, "isInteger", boolean.class, value))
.ifFalse(new BytecodeBlock()
.gotoLabel(defaultLabel)))
.append(expression.set(value.cast(int.class)))
.append(switchBuilder.build());
break;
case HASH_SWITCH:
for (Map.Entry<Integer, Collection<BytecodeNode>> bucket : hashBuckets.asMap().entrySet()) {
Collection<BytecodeNode> testValues = bucket.getValue();
BytecodeBlock caseBlock = buildInCase(
generatorContext,
scope,
type,
match,
defaultLabel,
value,
testValues,
false,
isIndeterminateSignature,
isIndeterminateFunction);
switchBuilder.addCase(bucket.getKey(), caseBlock);
}
switchBuilder.defaultCase(jump(defaultLabel));
Binding hashCodeBinding = generatorContext
.getCallSiteBinder()
.bind(hashCodeFunction);
switchBlock = new BytecodeBlock()
.comment("lookupSwitch(hashCode(<stackValue>))")
.getVariable(value)
.append(invoke(hashCodeBinding, hashCodeSignature))
.invokeStatic(Long.class, "hashCode", int.class, long.class)
.putVariable(expression)
.append(switchBuilder.build());
break;
case SET_CONTAINS:
Set<?> constantValuesSet = toFastutilHashSet(constantValues, type, metadata);
Binding constant = generatorContext.getCallSiteBinder().bind(constantValuesSet, constantValuesSet.getClass());
switchBlock = new BytecodeBlock()
.comment("inListSet.contains(<stackValue>)")
.append(new IfStatement()
.condition(new BytecodeBlock()
.comment("value")
.getVariable(value)
.comment("set")
.append(loadConstant(constant))
// TODO: use invokeVirtual on the set instead. This requires swapping the two elements in the stack
.invokeStatic(FastutilSetHelper.class, "in", boolean.class, javaType.isPrimitive() ? javaType : Object.class, constantValuesSet.getClass()))
.ifTrue(jump(match)));
break;
default:
throw new IllegalArgumentException("Not supported switch generation case: " + switchGenerationCase);
}
BytecodeBlock defaultCaseBlock = buildInCase(
generatorContext,
scope,
type,
match,
noMatch,
value,
defaultBucket.build(),
true,
isIndeterminateSignature,
isIndeterminateFunction)
.setDescription("default");
BytecodeBlock block = new BytecodeBlock()
.comment("IN")
.append(generatorContext.generate(arguments.get(0)))
.append(ifWasNullPopAndGoto(scope, end, boolean.class, javaType))
.putVariable(value)
.append(switchBlock)
.visitLabel(defaultLabel)
.append(defaultCaseBlock);
BytecodeBlock matchBlock = new BytecodeBlock()
.setDescription("match")
.visitLabel(match)
.append(generatorContext.wasNull().set(constantFalse()))
.push(true)
.gotoLabel(end);
block.append(matchBlock);
BytecodeBlock noMatchBlock = new BytecodeBlock()
.setDescription("noMatch")
.visitLabel(noMatch)
.push(false)
.gotoLabel(end);
block.append(noMatchBlock);
block.visitLabel(end);
return block;
}
public static boolean isInteger(long value)
{
return value == (int) value;
}
private static BytecodeBlock buildInCase(
BytecodeGeneratorContext generatorContext,
Scope scope,
Type type,
LabelNode matchLabel,
LabelNode noMatchLabel,
Variable value,
Collection<BytecodeNode> testValues,
boolean checkForNulls,
Signature isIndeterminateSignature,
ScalarFunctionImplementation isIndeterminateFunction)
{
Variable caseWasNull = null; // caseWasNull is set to true the first time a null in `testValues` is encountered
if (checkForNulls) {
caseWasNull = scope.createTempVariable(boolean.class);
}
BytecodeBlock caseBlock = new BytecodeBlock();
if (checkForNulls) {
caseBlock.putVariable(caseWasNull, false);
}
LabelNode elseLabel = new LabelNode("else");
BytecodeBlock elseBlock = new BytecodeBlock()
.visitLabel(elseLabel);
Variable wasNull = generatorContext.wasNull();
if (checkForNulls) {
// Consider following expression: "ARRAY[null] IN (ARRAY[1], ARRAY[2], ARRAY[3]) => NULL"
// All lookup values will go to the SET_CONTAINS, since neither of them is indeterminate.
// As ARRAY[null] is not among them, the code will fall through to the defaultCaseBlock.
// Since there is no values in the defaultCaseBlock, the defaultCaseBlock will return FALSE.
// That is incorrect. Doing an explicit check for indeterminate is required to correctly return NULL.
if (testValues.isEmpty()) {
elseBlock.append(new BytecodeBlock()
.append(generatorContext.generateCall(isIndeterminateSignature.getName(), isIndeterminateFunction, ImmutableList.of(value)))
.putVariable(wasNull));
}
else {
elseBlock.append(wasNull.set(caseWasNull));
}
}
elseBlock.gotoLabel(noMatchLabel);
Signature equalsSignature = generatorContext.getMetadata().resolveOperator(OperatorType.EQUAL, ImmutableList.of(type, type));
ScalarFunctionImplementation equalsFunction = generatorContext.getMetadata().getScalarFunctionImplementation(equalsSignature);
BytecodeNode elseNode = elseBlock;
for (BytecodeNode testNode : testValues) {
LabelNode testLabel = new LabelNode("test");
IfStatement test = new IfStatement();
BytecodeNode equalsCall = generatorContext.generateCall(
equalsSignature.getName(),
equalsFunction,
ImmutableList.of(value, testNode));
test.condition()
.visitLabel(testLabel)
.append(equalsCall);
if (checkForNulls) {
IfStatement wasNullCheck = new IfStatement("if wasNull, set caseWasNull to true, clear wasNull, pop boolean, and goto next test value");
wasNullCheck.condition(wasNull);
wasNullCheck.ifTrue(new BytecodeBlock()
.append(caseWasNull.set(constantTrue()))
.append(wasNull.set(constantFalse()))
.pop(boolean.class)
.gotoLabel(elseLabel));
test.condition().append(wasNullCheck);
}
test.ifTrue().gotoLabel(matchLabel);
test.ifFalse(elseNode);
elseNode = test;
elseLabel = testLabel;
}
caseBlock.append(elseNode);
return caseBlock;
}
private static boolean isDeterminateConstant(RowExpression expression, MethodHandle isIndeterminateFunction)
{
if (!(expression instanceof ConstantExpression)) {
return false;
}
ConstantExpression constantExpression = (ConstantExpression) expression;
Object value = constantExpression.getValue();
boolean isNull = value == null;
if (isNull) {
return false;
}
try {
return !(boolean) isIndeterminateFunction.invoke(value, false);
}
catch (Throwable t) {
throwIfUnchecked(t);
throw new RuntimeException(t);
}
}
}
| apache-2.0 |
Nodstuff/hapi-fhir | hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/valuesets/SupplyrequestKindEnumFactory.java | 2483 | package org.hl7.fhir.instance.model.valuesets;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 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 HOLDER 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.
*/
// Generated on Sat, Aug 22, 2015 23:00-0400 for FHIR v0.5.0
import org.hl7.fhir.instance.model.EnumFactory;
public class SupplyrequestKindEnumFactory implements EnumFactory<SupplyrequestKind> {
public SupplyrequestKind fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
return null;
if ("central".equals(codeString))
return SupplyrequestKind.CENTRAL;
if ("nonstock".equals(codeString))
return SupplyrequestKind.NONSTOCK;
throw new IllegalArgumentException("Unknown SupplyrequestKind code '"+codeString+"'");
}
public String toCode(SupplyrequestKind code) {
if (code == SupplyrequestKind.CENTRAL)
return "central";
if (code == SupplyrequestKind.NONSTOCK)
return "nonstock";
return "?";
}
}
| apache-2.0 |
davidbuhler/maven-gwt-appengine-jdo-seed-project | src/main/java/com/davidbuhler/plaidsuit/client/view/ClickableSafeHtmlCell.java | 1166 | package com.davidbuhler.plaidsuit.client.view;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
public class ClickableSafeHtmlCell extends AbstractCell<SafeHtml>
{
public ClickableSafeHtmlCell()
{
super("click", "keydown");
}
@Override
public void onBrowserEvent(Context context, Element parent, SafeHtml value, NativeEvent event, ValueUpdater<SafeHtml> valueUpdater)
{
super.onBrowserEvent(context, parent, value, event, valueUpdater);
if ("click".equals(event.getType()))
{
onEnterKeyDown(context, parent, value, event, valueUpdater);
}
}
@Override
protected void onEnterKeyDown(Context context, Element parent, SafeHtml value, NativeEvent event, ValueUpdater<SafeHtml> valueUpdater)
{
if (valueUpdater != null)
{
valueUpdater.update(value);
}
}
@Override
public void render(Context context, SafeHtml value, SafeHtmlBuilder sb)
{
if (value != null)
{
sb.append(value);
}
}
} | apache-2.0 |
gzsombor/ranger | agents-audit/src/main/java/org/apache/ranger/audit/provider/MiscUtil.java | 24568 | /*
* 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.ranger.audit.provider;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.rmi.dgc.VMID;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.security.auth.Subject;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.util.KerberosName;
import org.apache.hadoop.security.authentication.util.KerberosUtil;
import org.apache.log4j.helpers.LogLog;
import org.apache.ranger.authorization.hadoop.utils.RangerCredentialProvider;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import static org.apache.hadoop.util.PlatformName.IBM_JAVA;
public class MiscUtil {
private static final Log logger = LogFactory.getLog(MiscUtil.class);
public static final String TOKEN_START = "%";
public static final String TOKEN_END = "%";
public static final String TOKEN_HOSTNAME = "hostname";
public static final String TOKEN_APP_TYPE = "app-type";
public static final String TOKEN_JVM_INSTANCE = "jvm-instance";
public static final String TOKEN_TIME = "time:";
public static final String TOKEN_PROPERTY = "property:";
public static final String TOKEN_ENV = "env:";
public static final String ESCAPE_STR = "\\";
static VMID sJvmID = new VMID();
public static String LINE_SEPARATOR = System.getProperty("line.separator");
private static Gson sGsonBuilder = null;
private static String sApplicationType = null;
private static UserGroupInformation ugiLoginUser = null;
private static Subject subjectLoginUser = null;
private static String local_hostname = null;
private static Map<String, LogHistory> logHistoryList = new Hashtable<String, LogHistory>();
private static int logInterval = 30000; // 30 seconds
static {
try {
sGsonBuilder = new GsonBuilder().setDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS").create();
} catch (Throwable excp) {
LogLog.warn(
"failed to create GsonBuilder object. stringify() will return obj.toString(), instead of Json",
excp);
}
initLocalHost();
}
public static String replaceTokens(String str, long time) {
if (str == null) {
return str;
}
if (time <= 0) {
time = System.currentTimeMillis();
}
for (int startPos = 0; startPos < str.length();) {
int tagStartPos = str.indexOf(TOKEN_START, startPos);
if (tagStartPos == -1) {
break;
}
int tagEndPos = str.indexOf(TOKEN_END,
tagStartPos + TOKEN_START.length());
if (tagEndPos == -1) {
break;
}
String tag = str.substring(tagStartPos,
tagEndPos + TOKEN_END.length());
String token = tag.substring(TOKEN_START.length(),
tag.lastIndexOf(TOKEN_END));
String val = "";
if (token != null) {
if (token.equals(TOKEN_HOSTNAME)) {
val = getHostname();
} else if (token.equals(TOKEN_APP_TYPE)) {
val = getApplicationType();
} else if (token.equals(TOKEN_JVM_INSTANCE)) {
val = getJvmInstanceId();
} else if (token.startsWith(TOKEN_PROPERTY)) {
String propertyName = token.substring(TOKEN_PROPERTY
.length());
val = getSystemProperty(propertyName);
} else if (token.startsWith(TOKEN_ENV)) {
String envName = token.substring(TOKEN_ENV.length());
val = getEnv(envName);
} else if (token.startsWith(TOKEN_TIME)) {
String dtFormat = token.substring(TOKEN_TIME.length());
val = getFormattedTime(time, dtFormat);
}
}
if (val == null) {
val = "";
}
str = str.substring(0, tagStartPos) + val
+ str.substring(tagEndPos + TOKEN_END.length());
startPos = tagStartPos + val.length();
}
return str;
}
public static String getHostname() {
String ret = local_hostname;
if (ret == null) {
initLocalHost();
ret = local_hostname;
if (ret == null) {
ret = "unknown";
}
}
return ret;
}
public static void setApplicationType(String applicationType) {
sApplicationType = applicationType;
}
public static String getApplicationType() {
return sApplicationType;
}
public static String getJvmInstanceId() {
Integer val = Integer.valueOf(sJvmID.toString().hashCode());
long longVal = val.longValue();
String ret = Long.toString(Math.abs(longVal));
return ret;
}
public static String getSystemProperty(String propertyName) {
String ret = null;
try {
ret = propertyName != null ? System.getProperty(propertyName)
: null;
} catch (Exception excp) {
LogLog.warn("getSystemProperty(" + propertyName + ") failed", excp);
}
return ret;
}
public static String getEnv(String envName) {
String ret = null;
try {
ret = envName != null ? System.getenv(envName) : null;
} catch (Exception excp) {
LogLog.warn("getenv(" + envName + ") failed", excp);
}
return ret;
}
public static String getFormattedTime(long time, String format) {
String ret = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
ret = sdf.format(time);
} catch (Exception excp) {
LogLog.warn("SimpleDateFormat.format() failed: " + format, excp);
}
return ret;
}
public static void createParents(File file) {
if (file != null) {
String parentName = file.getParent();
if (parentName != null) {
File parentDir = new File(parentName);
if (!parentDir.exists()) {
if (!parentDir.mkdirs()) {
LogLog.warn("createParents(): failed to create "
+ parentDir.getAbsolutePath());
}
}
}
}
}
public static long getNextRolloverTime(long lastRolloverTime, long interval) {
long now = System.currentTimeMillis() / 1000 * 1000; // round to second
if (lastRolloverTime <= 0) {
// should this be set to the next multiple-of-the-interval from
// start of the day?
return now + interval;
} else if (lastRolloverTime <= now) {
long nextRolloverTime = now + interval;
// keep it at 'interval' boundary
long trimInterval = (nextRolloverTime - lastRolloverTime)
% interval;
return nextRolloverTime - trimInterval;
} else {
return lastRolloverTime;
}
}
public static long getRolloverStartTime(long nextRolloverTime, long interval) {
return (nextRolloverTime <= interval) ? System.currentTimeMillis()
: nextRolloverTime - interval;
}
public static int parseInteger(String str, int defValue) {
int ret = defValue;
if (str != null) {
try {
ret = Integer.parseInt(str);
} catch (Exception excp) {
// ignore
}
}
return ret;
}
public static String generateUniqueId() {
return UUID.randomUUID().toString();
}
public static <T> String stringify(T log) {
String ret = null;
if (log != null) {
if (log instanceof String) {
ret = (String) log;
} else if (MiscUtil.sGsonBuilder != null) {
ret = MiscUtil.sGsonBuilder.toJson(log);
} else {
ret = log.toString();
}
}
return ret;
}
static public <T> T fromJson(String jsonStr, Class<T> clazz) {
return sGsonBuilder.fromJson(jsonStr, clazz);
}
public static String getStringProperty(Properties props, String propName) {
String ret = null;
if (props != null && propName != null) {
String val = props.getProperty(propName);
if (val != null) {
ret = val;
}
}
return ret;
}
public static boolean getBooleanProperty(Properties props, String propName,
boolean defValue) {
boolean ret = defValue;
if (props != null && propName != null) {
String val = props.getProperty(propName);
if (val != null) {
ret = Boolean.valueOf(val);
}
}
return ret;
}
public static int getIntProperty(Properties props, String propName,
int defValue) {
int ret = defValue;
if (props != null && propName != null) {
String val = props.getProperty(propName);
if (val != null) {
try {
ret = Integer.parseInt(val);
} catch (NumberFormatException excp) {
ret = defValue;
}
}
}
return ret;
}
public static long getLongProperty(Properties props, String propName,
long defValue) {
long ret = defValue;
if (props != null && propName != null) {
String val = props.getProperty(propName);
if (val != null) {
try {
ret = Long.parseLong(val);
} catch (NumberFormatException excp) {
ret = defValue;
}
}
}
return ret;
}
public static Map<String, String> getPropertiesWithPrefix(Properties props,
String prefix) {
Map<String, String> prefixedProperties = new HashMap<String, String>();
if (props != null && prefix != null) {
for (String key : props.stringPropertyNames()) {
if (key == null) {
continue;
}
String val = props.getProperty(key);
if (key.startsWith(prefix)) {
key = key.substring(prefix.length());
if (key == null) {
continue;
}
prefixedProperties.put(key, val);
}
}
}
return prefixedProperties;
}
/**
* @param destListStr
* @param delim
* @return
*/
public static List<String> toArray(String destListStr, String delim) {
List<String> list = new ArrayList<String>();
if (destListStr != null && !destListStr.isEmpty()) {
StringTokenizer tokenizer = new StringTokenizer(destListStr,
delim.trim());
while (tokenizer.hasMoreTokens()) {
list.add(tokenizer.nextToken());
}
}
return list;
}
public static String getCredentialString(String url, String alias) {
if (url != null && alias != null) {
return RangerCredentialProvider.getInstance()
.getCredentialString(url, alias);
}
return null;
}
public static UserGroupInformation createUGIFromSubject(Subject subject)
throws IOException {
logger.info("SUBJECT " + (subject == null ? "not found" : "found"));
UserGroupInformation ugi = null;
if (subject != null) {
logger.info("SUBJECT.PRINCIPALS.size()="
+ subject.getPrincipals().size());
Set<Principal> principals = subject.getPrincipals();
for (Principal principal : principals) {
logger.info("SUBJECT.PRINCIPAL.NAME=" + principal.getName());
}
try {
// Do not remove the below statement. The default
// getLoginUser does some initialization which is needed
// for getUGIFromSubject() to work.
UserGroupInformation.getLoginUser();
logger.info("Default UGI before using new Subject:"
+ UserGroupInformation.getLoginUser());
} catch (Throwable t) {
logger.error(t);
}
ugi = UserGroupInformation.getUGIFromSubject(subject);
logger.info("SUBJECT.UGI.NAME=" + ugi.getUserName() + ", ugi="
+ ugi);
} else {
logger.info("Server username is not available");
}
return ugi;
}
/**
* @param ugiLoginUser
*/
public static void setUGILoginUser(UserGroupInformation newUGI,
Subject newSubject) {
if (newUGI != null) {
UserGroupInformation.setLoginUser(newUGI);
ugiLoginUser = newUGI;
logger.info("Setting UGI=" + newUGI);
} else {
logger.error("UGI is null. Not setting it.");
}
if (newSubject != null) {
logger.info("Setting SUBJECT");
subjectLoginUser = newSubject;
}
}
public static UserGroupInformation getUGILoginUser() {
UserGroupInformation ret = ugiLoginUser;
if (ret == null) {
try {
// Do not cache ugiLoginUser if it is not explicitly set with
// setUGILoginUser.
// It appears that the user represented by
// the returned object is periodically logged out and logged back
// in when the token is scheduled to expire. So it is better
// to get the user object every time from UserGroupInformation class and
// not cache it
ret = getLoginUser();
} catch (IOException e) {
logger.error("Error getting UGI.", e);
}
}
if(ret != null) {
try {
ret.checkTGTAndReloginFromKeytab();
} catch(IOException ioe) {
logger.error("Error renewing TGT and relogin. Ignoring Exception, and continuing with the old TGT", ioe);
}
}
return ret;
}
/**
* Execute the {@link PrivilegedExceptionAction} on the {@link UserGroupInformation} if it's set, otherwise call it directly
*/
public static <X> X executePrivilegedAction(final PrivilegedExceptionAction<X> action) throws Exception {
final UserGroupInformation ugi = getUGILoginUser();
if (ugi != null) {
return ugi.doAs(action);
} else {
return action.run();
}
}
/**
* Execute the {@link PrivilegedAction} on the {@link UserGroupInformation} if it's set, otherwise call it directly.
*/
public static <X> X executePrivilegedAction(final PrivilegedAction<X> action) {
final UserGroupInformation ugi = getUGILoginUser();
if (ugi != null) {
return ugi.doAs(action);
} else {
return action.run();
}
}
public static Subject getSubjectLoginUser() {
return subjectLoginUser;
}
public static String getKerberosNamesRules() {
return KerberosName.getRules();
}
/**
*
* @param principal
* This could be in the format abc/host@domain.com
* @return
*/
static public String getShortNameFromPrincipalName(String principal) {
if (principal == null) {
return null;
}
try {
// Assuming it is kerberos name for now
KerberosName kerbrosName = new KerberosName(principal);
String userName = kerbrosName.getShortName();
userName = StringUtils.substringBefore(userName, "/");
userName = StringUtils.substringBefore(userName, "@");
return userName;
} catch (Throwable t) {
logger.error("Error converting kerberos name. principal="
+ principal + ", KerberosName.rules=" + KerberosName.getRules());
}
return principal;
}
/**
* @param userName
* @return
*/
static public Set<String> getGroupsForRequestUser(String userName) {
if (userName != null) {
try {
UserGroupInformation ugi = UserGroupInformation
.createRemoteUser(userName);
String[] groups = ugi.getGroupNames();
if (groups != null && groups.length > 0) {
Set<String> groupsSet = new java.util.HashSet<String>();
for (String group : groups) {
groupsSet.add(group);
}
return groupsSet;
}
} catch (Throwable e) {
logErrorMessageByInterval(logger,
"Error getting groups for users. userName=" + userName, e);
}
}
return Collections.emptySet();
}
static public boolean logErrorMessageByInterval(Log useLogger,
String message) {
return logErrorMessageByInterval(useLogger, message, null);
}
/**
* @param string
* @param e
*/
static public boolean logErrorMessageByInterval(Log useLogger,
String message, Throwable e) {
if (message == null) {
return false;
}
LogHistory log = logHistoryList.get(message);
if (log == null) {
log = new LogHistory();
logHistoryList.put(message, log);
}
if ((System.currentTimeMillis() - log.lastLogTime) > logInterval) {
log.lastLogTime = System.currentTimeMillis();
int counter = log.counter;
log.counter = 0;
if (counter > 0) {
message += ". Messages suppressed before: " + counter;
}
if (e == null) {
useLogger.error(message);
} else {
useLogger.error(message, e);
}
return true;
} else {
log.counter++;
}
return false;
}
public static void setUGIFromJAASConfig(String jaasConfigAppName) throws Exception {
String keytabFile = null;
String principal = null;
UserGroupInformation ugi = null;
if (logger.isDebugEnabled()){
logger.debug("===> MiscUtil.setUGIFromJAASConfig() jaasConfigAppName: " + jaasConfigAppName);
}
try {
AppConfigurationEntry entries[] = Configuration.getConfiguration().getAppConfigurationEntry(jaasConfigAppName);
if(!ArrayUtils.isEmpty(entries)) {
for (AppConfigurationEntry entry : entries) {
if (entry.getOptions().get("keyTab") != null) {
keytabFile = (String) entry.getOptions().get("keyTab");
}
if (entry.getOptions().get("principal") != null) {
principal = (String) entry.getOptions().get("principal");
}
if (!StringUtils.isEmpty(principal) && !StringUtils.isEmpty(keytabFile)) {
break;
}
}
if (!StringUtils.isEmpty(principal) && !StringUtils.isEmpty(keytabFile)) {
// This will login and set the UGI
UserGroupInformation.loginUserFromKeytab(principal, keytabFile);
ugi = UserGroupInformation.getLoginUser();
} else {
String error_mesage = "Unable to get the principal/keytab from jaasConfigAppName: " + jaasConfigAppName;
logger.error(error_mesage);
throw new Exception(error_mesage);
}
logger.info("MiscUtil.setUGIFromJAASConfig() UGI: " + ugi + " principal: " + principal + " keytab: " + keytabFile);
} else {
logger.warn("JAASConfig file not found! Ranger Plugin will not working in a Secure Cluster...");
}
} catch ( Exception e) {
logger.error("Unable to set UGI for Principal: " + principal + " keytab: " + keytabFile );
throw e;
}
if (logger.isDebugEnabled()) {
logger.debug("<=== MiscUtil.setUGIFromJAASConfig() jaasConfigAppName: " + jaasConfigAppName + " UGI: " + ugi + " principal: " + principal + " keytab: " + keytabFile);
}
}
public static void authWithKerberos(String keytab, String principal,
String nameRules) {
if (keytab == null || principal == null) {
return;
}
Subject serverSubject = new Subject();
int successLoginCount = 0;
String[] spnegoPrincipals = null;
try {
if (principal.equals("*")) {
spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab,
Pattern.compile("HTTP/.*"));
if (spnegoPrincipals.length == 0) {
logger.error("No principals found in keytab=" + keytab);
}
} else {
spnegoPrincipals = new String[] { principal };
}
if (nameRules != null) {
KerberosName.setRules(nameRules);
}
boolean useKeytab = true;
if (!useKeytab) {
logger.info("Creating UGI with subject");
LoginContext loginContext = null;
List<LoginContext> loginContexts = new ArrayList<LoginContext>();
for (String spnegoPrincipal : spnegoPrincipals) {
try {
logger.info("Login using keytab " + keytab
+ ", for principal " + spnegoPrincipal);
final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(
keytab, spnegoPrincipal);
loginContext = new LoginContext("",
serverSubject, null, kerberosConfiguration);
loginContext.login();
successLoginCount++;
logger.info("Login success keytab " + keytab
+ ", for principal " + spnegoPrincipal);
loginContexts.add(loginContext);
} catch (Throwable t) {
logger.error("Login failed keytab " + keytab
+ ", for principal " + spnegoPrincipal, t);
}
if (successLoginCount > 0) {
logger.info("Total login success count="
+ successLoginCount);
try {
UserGroupInformation
.loginUserFromSubject(serverSubject);
// UserGroupInformation ugi =
// createUGIFromSubject(serverSubject);
// if (ugi != null) {
// setUGILoginUser(ugi, serverSubject);
// }
} catch (Throwable e) {
logger.error("Error creating UGI from subject. subject="
+ serverSubject);
} finally {
if (loginContext != null) {
loginContext.logout();
}
}
} else {
logger.error("Total logins were successfull from keytab="
+ keytab + ", principal=" + principal);
}
}
} else {
logger.info("Creating UGI from keytab directly. keytab="
+ keytab + ", principal=" + spnegoPrincipals[0]);
UserGroupInformation ugi = UserGroupInformation
.loginUserFromKeytabAndReturnUGI(spnegoPrincipals[0],
keytab);
MiscUtil.setUGILoginUser(ugi, null);
}
} catch (Throwable t) {
logger.error("Failed to login with given keytab and principal", t);
}
}
static class LogHistory {
long lastLogTime = 0;
int counter = 0;
}
/**
* Kerberos context configuration for the JDK GSS library.
*/
private static class KerberosConfiguration extends Configuration {
private String keytab;
private String principal;
public KerberosConfiguration(String keytab, String principal) {
this.keytab = keytab;
this.principal = principal;
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, String> options = new HashMap<String, String>();
if (IBM_JAVA) {
options.put("useKeytab", keytab.startsWith("file://") ? keytab
: "file://" + keytab);
options.put("principal", principal);
options.put("credsType", "acceptor");
} else {
options.put("keyTab", keytab);
options.put("principal", principal);
options.put("useKeyTab", "true");
options.put("storeKey", "true");
options.put("doNotPrompt", "true");
options.put("useTicketCache", "true");
options.put("renewTGT", "true");
options.put("isInitiator", "false");
}
options.put("refreshKrb5Config", "true");
String ticketCache = System.getenv("KRB5CCNAME");
if (ticketCache != null) {
if (IBM_JAVA) {
options.put("useDefaultCcache", "true");
// The first value searched when "useDefaultCcache" is used.
System.setProperty("KRB5CCNAME", ticketCache);
options.put("renewTGT", "true");
options.put("credsType", "both");
} else {
options.put("ticketCache", ticketCache);
}
}
if (logger.isDebugEnabled()) {
options.put("debug", "true");
}
return new AppConfigurationEntry[] { new AppConfigurationEntry(
KerberosUtil.getKrb5LoginModuleName(),
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
options), };
}
}
public static UserGroupInformation getLoginUser() throws IOException {
return UserGroupInformation.getLoginUser();
}
private static void initLocalHost() {
if ( logger.isDebugEnabled() ) {
logger.debug("==> MiscUtil.initLocalHost()");
}
try {
local_hostname = InetAddress.getLocalHost().getHostName();
} catch (Throwable excp) {
LogLog.warn("getHostname()", excp);
}
if ( logger.isDebugEnabled() ) {
logger.debug("<== MiscUtil.initLocalHost()");
}
}
public static Date getUTCDateForLocalDate(Date date) {
TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
Calendar local = Calendar.getInstance();
int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
utc.setTimeInMillis(date.getTime());
utc.add(Calendar.MILLISECOND, -offset);
return utc.getTime();
}
public static Date getUTCDate() {
TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0");
Calendar local = Calendar.getInstance();
int offset = local.getTimeZone().getOffset(local.getTimeInMillis());
GregorianCalendar utc = new GregorianCalendar(gmtTimeZone);
utc.setTimeInMillis(local.getTimeInMillis());
utc.add(Calendar.MILLISECOND, -offset);
return utc.getTime();
}
}
| apache-2.0 |
googleinterns/voter-central | info-compiler/src/main/java/com/google/sps/webcrawler/RelevancyChecker.java | 4077 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.webcrawler;
import com.google.cloud.language.v1.AnalyzeEntitiesRequest;
import com.google.cloud.language.v1.AnalyzeEntitiesResponse;
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.Document.Type;
import com.google.cloud.language.v1.EncodingType;
import com.google.cloud.language.v1.Entity;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.sps.data.NewsArticle;
import java.io.IOException;
/**
* A utility class that performs entity analysis to check the relevancy of news article content to a
* candidate.
*/
public class RelevancyChecker {
static final double CANDIDATE_SALIENCE_THRESHOLD = 0.18;
static final double PARTY_SALIENCE_THRESHOLD = 0.001;
static final String NO_PARTY_AFFILIATION = "No Party Affiliation";
static final String NON_PARTISAN = "Non Partisan";
static final String NONPARTISAN = "Nonpartisan";
private LanguageServiceClient languageServiceClient;
/**
* Constructs a {@code RelevancyChecker} instance to use the Google Natural Language API.
*
* @throws IOException if {@code LanguageServiceClient} instantiation fails, such as because of
* lack of permission to access the library.
*/
public RelevancyChecker() throws IOException {
this(LanguageServiceClient.create());
}
/** For testing purposes. */
RelevancyChecker(LanguageServiceClient languageServiceClient) {
this.languageServiceClient = languageServiceClient;
}
/**
* Checks whether the {@code newsArticle} is relevant to the {@code candidateName} of interest.
* Defines relevancy as the salience of {@code candidateName} and {@code partyName} in the
* content both being bigger than their respective threshold. If {@code partyName} is null,
* skips the salience checking for {@code partyName} and determines relevancy solely by looking
* at the salience of {@code candidateName}.
*/
public boolean isRelevant(NewsArticle newsArticle, String candidateName, String partyName) {
double candidateNameSalience = computeSalienceOfName(newsArticle.getContent(), candidateName);
if (partyName == null
|| partyName.equalsIgnoreCase(NO_PARTY_AFFILIATION)
|| partyName.equalsIgnoreCase(NON_PARTISAN)
|| partyName.equalsIgnoreCase(NONPARTISAN)) {
return candidateNameSalience >= CANDIDATE_SALIENCE_THRESHOLD;
} else {
double partyNameSalience = computeSalienceOfName(newsArticle.getContent(), partyName);
return (candidateNameSalience >= CANDIDATE_SALIENCE_THRESHOLD
&& partyNameSalience >= PARTY_SALIENCE_THRESHOLD);
}
}
/**
* Performs entity analysis, and computes the salience score of {@code name} in the {@code
* content}. Salience has range [0, 1], with higher salience indicating higher relevance of
* {@code name} to {@code content} overall.
*/
double computeSalienceOfName(String content, String name) {
Document doc = Document.newBuilder().setContent(content).setType(Type.PLAIN_TEXT).build();
AnalyzeEntitiesRequest request =
AnalyzeEntitiesRequest.newBuilder()
.setDocument(doc)
.setEncodingType(EncodingType.UTF8)
.build();
AnalyzeEntitiesResponse response = languageServiceClient.analyzeEntities(request);
for (Entity entity : response.getEntitiesList()) {
if (name.equalsIgnoreCase(entity.getName())) {
return entity.getSalience();
}
}
return 0;
}
}
| apache-2.0 |
amannm/wildfly-swarm | runtime/keycloak/src/main/java/org/wildfly/swarm/runtime/keycloak/KeycloakSecurityContextAssociation.java | 616 | package org.wildfly.swarm.runtime.keycloak;
import org.keycloak.KeycloakSecurityContext;
/**
* @author Bob McWhirter
*/
public class KeycloakSecurityContextAssociation {
private static ThreadLocal<KeycloakSecurityContext> SECURITY_CONTEXT = new ThreadLocal<>();
public static KeycloakSecurityContext get() {
KeycloakSecurityContext context = SECURITY_CONTEXT.get();
return context;
}
public static void associate(KeycloakSecurityContext context) {
SECURITY_CONTEXT.set(context);
}
public static void disassociate() {
SECURITY_CONTEXT.remove();
}
}
| apache-2.0 |
eResearchSA/conveyer | src/main/java/au/edu/ersa/conveyer/cli/ListObjects.java | 896 | package au.edu.ersa.conveyer.cli;
import io.airlift.airline.Command;
import io.airlift.airline.Option;
import java.util.List;
import au.edu.ersa.conveyer.openstack.swift.Driver;
@Command(name = "list-objects", description = "List objects")
public class ListObjects extends Base {
@Option(name = { "-r", "--region" }, description = "Region (default: all)", required = true)
public String region;
@Option(name = { "-C", "--container" }, description = "Container", required = true)
public String container;
public void run() {
super.run();
try {
Driver swift = new Driver(access, region);
List<String> objects = swift.list(container);
if (objects != null) {
print(swift.list(container));
} else {
System.err.println("Error: no such container.");
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
System.exit(1);
}
}
}
| apache-2.0 |
consulo/consulo-maven | plugin/src/main/java/org/jetbrains/idea/maven/dom/refactorings/extract/SelectMavenProjectDialog.java | 5357 | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.maven.dom.refactorings.extract;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.util.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.jetbrains.idea.maven.dom.MavenDomBundle;
import org.jetbrains.idea.maven.dom.MavenDomUtil;
import org.jetbrains.idea.maven.dom.model.MavenDomDependency;
import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.utils.ComboBoxUtil;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Set;
public class SelectMavenProjectDialog extends DialogWrapper {
private final Set<MavenDomProjectModel> myMavenDomProjectModels;
private final boolean myHasExclusions;
private JComboBox myMavenProjectsComboBox;
private JPanel myMainPanel;
private JCheckBox myReplaceAllCheckBox;
private JCheckBox myExtractExclusions;
private boolean myHasUsagesInProjects = false;
private ItemListener myReplaceAllListener;
private final Function<MavenDomProjectModel, Set<MavenDomDependency>> myOccurrencesCountFunction;
public SelectMavenProjectDialog(@Nonnull Project project,
@Nonnull Set<MavenDomProjectModel> mavenDomProjectModels,
@Nonnull Function<MavenDomProjectModel, Set<MavenDomDependency>> funOccurrences,
@Nonnull boolean hasExclusions) {
super(project, true);
myMavenDomProjectModels = mavenDomProjectModels;
myHasExclusions = hasExclusions;
setTitle(MavenDomBundle.message("choose.project"));
myOccurrencesCountFunction = funOccurrences;
for (MavenDomProjectModel model : myMavenDomProjectModels) {
if (myOccurrencesCountFunction.fun(model).size() > 0) {
myHasUsagesInProjects = true;
break;
}
}
init();
}
@Nonnull
protected Action[] createActions() {
return new Action[]{getOKAction(), getCancelAction()};
}
protected void init() {
super.init();
updateOkStatus();
}
@Override
protected void dispose() {
super.dispose();
if (myReplaceAllCheckBox != null) {
myReplaceAllCheckBox.removeItemListener(myReplaceAllListener);
}
}
@Nullable
public MavenDomProjectModel getSelectedProject() {
return (MavenDomProjectModel)ComboBoxUtil.getSelectedValue((DefaultComboBoxModel)myMavenProjectsComboBox.getModel());
}
public boolean isReplaceAllOccurrences() {
return myReplaceAllCheckBox.isSelected();
}
public boolean isExtractExclusions() {
return myExtractExclusions.isSelected();
}
protected JComponent createCenterPanel() {
ComboBoxUtil.setModel(myMavenProjectsComboBox, new DefaultComboBoxModel(), myMavenDomProjectModels,
new Function<MavenDomProjectModel, Pair<String, ?>>() {
public Pair<String, ?> fun(MavenDomProjectModel model) {
String projectName = model.getName().getStringValue();
MavenProject mavenProject = MavenDomUtil.findProject(model);
if (mavenProject != null) {
projectName = mavenProject.getDisplayName();
}
if (StringUtil.isEmptyOrSpaces(projectName)) {
projectName = "pom.xml";
}
return Pair.create(projectName, model);
}
});
myReplaceAllListener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updateControls();
}
};
myMavenProjectsComboBox.addItemListener(myReplaceAllListener);
myMavenProjectsComboBox.setSelectedItem(0);
myReplaceAllCheckBox.setVisible(myHasUsagesInProjects);
myExtractExclusions.setVisible(myHasExclusions);
updateControls();
return myMainPanel;
}
private void updateControls() {
MavenDomProjectModel project = getSelectedProject();
Integer count = myOccurrencesCountFunction.fun(project).size();
myReplaceAllCheckBox.setText(RefactoringBundle.message("replace.all.occurences", count));
myReplaceAllCheckBox.setEnabled(count != 0);
}
private void updateOkStatus() {
setOKActionEnabled(getSelectedProject() != null);
}
public JComponent getPreferredFocusedComponent() {
return myMavenProjectsComboBox;
}
} | apache-2.0 |
EixoX/Jetfuel-Java | com.eixox/src/main/java/com/eixox/database/DatabaseUpdate.java | 632 | package com.eixox.database;
import java.sql.Connection;
import com.eixox.data.DataUpdate;
public class DatabaseUpdate extends DataUpdate {
public final Database database;
public DatabaseUpdate(Database database, String name) {
super(name);
this.database = database;
}
@Override
public final long execute() {
DatabaseCommand cmd = database.dialect.buildUpdateCommand(this.from, this.values, this.filter);
try {
Connection conn = database.getConnection();
try {
return cmd.executeNonQuery(conn);
} finally {
conn.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
h920526/jaBenDon | src/main/java/controller/OrderUserController.java | 704 | package controller;
import java.util.List;
import model.OrderUser;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
public interface OrderUserController {
public OrderUser createOrderUser(@RequestBody OrderUser orderUser);
public OrderUser findOrderUser(@PathVariable long orderUserKey);
public List<OrderUser> findOrderUsers();
public OrderUser updateOrderUser(@RequestBody OrderUser orderUser);
public void deleteOrderUser(@PathVariable long orderUserKey);
/*
* custom service
*/
public List<OrderUser> findOrderUsersByOrderKey(@PathVariable long orderKey);
public List<String> findAllOrderUserNames();
}
| apache-2.0 |
wenhao/tdd-workshop | 05-taxi2/src/main/java/com/github/wenhao/TaxiCalculator.java | 573 | package com.github.wenhao;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
public class TaxiCalculator {
private final List<FeeCalculator> calculators = Arrays.asList(new StartingFeeCalculator(),
new AdditionalFeeCalculator(),
new LongDistanceCalculator(),
new WaitingTimeCalculator());
public BigDecimal calculate(final Trip trip) {
return calculators.stream()
.map(calculator -> calculator.charge(trip))
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
| apache-2.0 |
ifnul/ums-backend | is-lnu-persistence/src/main/java/org/lnu/is/dao/dao/priority/PriorityDao.java | 1083 | package org.lnu.is.dao.dao.priority;
import org.lnu.is.dao.utils.DaoUtils;
import org.lnu.is.domain.priority.PriorityStat;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class PriorityDao {
private static final String TIME_PERIOD_ID_PLACEHOLDER = "$$TIME_PERIOD_ID$$";
@PersistenceContext
private EntityManager entityManager;
public List<PriorityStat> getPriorityStat(long timePeriodId) {
String sql = DaoUtils.getQuery("priority_stat.sql").replace(TIME_PERIOD_ID_PLACEHOLDER, String.valueOf(timePeriodId));
List<Object[]> destinationEntries = entityManager.createNativeQuery(sql).getResultList();
return destinationEntries.stream()
.map(arr -> new PriorityStat(arr[0] != null ? Integer.parseInt(arr[0].toString()) : 0,
arr[1] != null ? Long.parseLong(arr[1].toString()) : 0))
.collect(Collectors.toList());
}
}
| apache-2.0 |
Dennis-Koch/ambeth | jambeth/jambeth-security/src/main/java/com/koch/ambeth/security/SecurityContextType.java | 744 | package com.koch.ambeth.security;
/*-
* #%L
* jambeth-security
* %%
* Copyright (C) 2017 Koch Softwaredevelopment
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* #L%
*/
public enum SecurityContextType {
AUTHORIZED, AUTHENTICATED, NOT_REQUIRED;
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/waiters/NotebookInstanceDeleted.java | 3664 | /*
* 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.sagemaker.waiters;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.waiters.WaiterAcceptor;
import com.amazonaws.waiters.WaiterState;
import com.amazonaws.waiters.AcceptorPathMatcher;
import com.amazonaws.services.sagemaker.model.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.amazonaws.jmespath.*;
import java.io.IOException;
import javax.annotation.Generated;
@SdkInternalApi
@Generated("com.amazonaws:aws-java-sdk-code-generator")
class NotebookInstanceDeleted {
static class IsValidationExceptionMatcher extends WaiterAcceptor<DescribeNotebookInstanceResult> {
/**
* Takes the response exception and determines whether this exception matches the expected exception, by
* comparing the respective error codes.
*
* @param e
* Response Exception
* @return True if it matches, False otherwise
*/
@Override
public boolean matches(AmazonServiceException e) {
return "ValidationException".equals(e.getErrorCode());
}
/**
* Represents the current waiter state in the case where resource state matches the expected state
*
* @return Corresponding state of the waiter
*/
@Override
public WaiterState getState() {
return WaiterState.SUCCESS;
}
}
static class IsFailedMatcher extends WaiterAcceptor<DescribeNotebookInstanceResult> {
private static final JsonNode expectedResult;
static {
try {
expectedResult = ObjectMapperSingleton.getObjectMapper().readTree("\"Failed\"");
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
private static final JmesPathExpression ast = new JmesPathField("NotebookInstanceStatus");
/**
* Takes the result and determines whether the state of the resource matches the expected state. To determine
* the current state of the resource, JmesPath expression is evaluated and compared against the expected result.
*
* @param result
* Corresponding result of the operation
* @return True if current state of the resource matches the expected state, False otherwise
*/
@Override
public boolean matches(DescribeNotebookInstanceResult result) {
JsonNode queryNode = ObjectMapperSingleton.getObjectMapper().valueToTree(result);
JsonNode finalResult = ast.accept(new JmesPathEvaluationVisitor(), queryNode);
return AcceptorPathMatcher.path(expectedResult, finalResult);
}
/**
* Represents the current waiter state in the case where resource state matches the expected state
*
* @return Corresponding state of the waiter
*/
@Override
public WaiterState getState() {
return WaiterState.FAILURE;
}
}
}
| apache-2.0 |
nssales/Strata | modules/engine/src/test/java/com/opengamma/strata/engine/marketdata/TestId.java | 1059 | /**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.engine.marketdata;
import java.util.Objects;
import com.opengamma.strata.basics.market.MarketDataId;
/**
* MarketDataId implementation used in tests.
*/
public class TestId implements MarketDataId<String> {
private final String value;
public static TestId of(String value) {
return new TestId(value);
}
public TestId(String value) {
this.value = value;
}
@Override
public Class<String> getMarketDataType() {
return String.class;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TestId testId = (TestId) o;
return Objects.equals(value, testId.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return "TestId [value='" + value + "']";
}
}
| apache-2.0 |
jamezp/wildfly-arquillian | container-remote-domain/src/test/java/org/jboss/as/arquillian/container/domain/remote/test/RemoteDomainTestCase.java | 2339 | /*
* Copyright 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.arquillian.container.domain.remote.test;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* For Domain server DeployableContianer implementations, the DeployableContainer will register
* all groups/individual servers it controls as Containers in Arquillians Registry during start.
*
* @author <a href="mailto:aslak@redhat.com">Aslak Knutsen</a>
*/
@RunWith(Arquillian.class)
public class RemoteDomainTestCase {
@ArquillianResource
ContainerController controller;
@Deployment(name = "dep1")
@TargetsContainer("main-server-group")
public static JavaArchive create1() {
return ShrinkWrap.create(JavaArchive.class);
}
@Test
@InSequence(1)
@OperateOnDeployment("dep1")
@TargetsContainer("master:server-one")
public void shouldRunInContainer1() throws Exception {
Assert.assertTrue(controller.isStarted("master:server-one"));
System.out.println("in..container");
}
@Test
@InSequence(2)
@OperateOnDeployment("dep1")
@TargetsContainer("master:server-two")
public void shouldRunInContainer2() throws Exception {
Assert.assertTrue(controller.isStarted("master:server-two"));
}
}
| apache-2.0 |
Tygron/SDK | java/core/src/com/tygron/pub/api/enums/MapType.java | 89 | package com.tygron.pub.api.enums;
public enum MapType {
CURRENT,
MAQUETTE
}
| apache-2.0 |
liangie/chooserTest | app/src/androidTest/java/com/liangei/choosertest/ApplicationTest.java | 366 | package com.liangei.choosertest;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | apache-2.0 |
nano-projects/nano-framework | nano-orm/nano-orm-kafka/src/test/java/org/nanoframework/orm/kafka/KafkaTests.java | 1828 | /*
* Copyright 2015-2017 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.nanoframework.orm.kafka;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.nanoframework.commons.support.logging.Logger;
import org.nanoframework.commons.support.logging.LoggerFactory;
import com.google.inject.Inject;
/**
*
* @author yanghe
* @since 1.4.9
*/
@Ignore
public class KafkaTests extends AbstractTests {
private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTests.class);
@Inject
private Producer<Object, Object> producer;
@Test
public void createProducerTest() {
injects();
Assert.assertNotNull(producer);
}
@Test
public void sendTest() throws InterruptedException, ExecutionException {
injects();
final Future<RecordMetadata> future = producer.send(new ProducerRecord<>("test", "Hello! Kafka"));
final RecordMetadata metadata = future.get();
LOGGER.debug("offset: {}", metadata.offset());
}
}
| apache-2.0 |
PierreLemordant/alien4cloud | alien4cloud-core/src/main/java/alien4cloud/model/components/ImplementationArtifact.java | 1751 | package alien4cloud.model.components;
import lombok.Getter;
import lombok.Setter;
import alien4cloud.ui.form.annotation.FormProperties;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Specifies an implementation artifact for interfaces or operations of a {@link NodeType node type} or {@link RelationshipType relation type}.
*
* @author luc boutier
*/
@Getter
@Setter
@FormProperties({ "interfaceName", "operationName", "artifactType", "artifactRef" })
public class ImplementationArtifact implements IArtifact {
/**
* <p>
* Specifies the type of this artifact.
* </p>
*/
private String artifactType;
/**
* <p>
* Identifies an Artifact Template to be used as implementation artifact. This Artifact Template can be defined in the same Definitions document or in a
* separate, imported document.
* </p>
*
* <p>
* The type of Artifact Template referenced by the artifactRef attribute MUST be the same type or a sub-type of the type specified in the artifactType
* attribute.
* </p>
*
* <p>
* Note: if no Artifact Template is referenced, the artifact type specific content of the ImplementationArtifact element alone is assumed to represent the
* actual artifact. For example, a simple script could be defined in place within the ImplementationArtifact element.
* </p>
*/
private String artifactRef;
/**
* The name of the archive in which the artifact lies.
*/
private String archiveName;
/**
* The version of the archive in which the artifact lies.
*/
private String archiveVersion;
@Override
@JsonIgnore
public String getArtifactRepository() {
return null;
}
} | apache-2.0 |
stalele/uPortal | uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/properties/PropertyToAttributePropertiesManager.java | 8932 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* 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 the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.apereo.portal.portlet.container.properties;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableSet;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apereo.portal.portlet.om.IPortletWindow;
import org.apereo.portal.portlet.om.IPortletWindowId;
import org.apereo.portal.url.IPortalRequestUtils;
import org.apereo.portal.utils.Populator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Portlet property manager that just translates properties to/from the portal request attributes
*/
@Service
public class PropertyToAttributePropertiesManager extends BaseRequestPropertiesManager {
private IPortalRequestUtils portalRequestUtils;
private BiMap<String, String> propertyToAttributeMappings = ImmutableBiMap.of();
private BiMap<String, String> attributeToPropertyMappings = ImmutableBiMap.of();
private Set<String> nonNamespacedProperties = Collections.emptySet();
/**
* Map of portlet property names to attribute names, if the value is null the key will be used
* for both the property and attribute name
*/
@Resource(name = "portletPropertyToAttributeMappings")
public void setPropertyMappings(Map<String, String> propertyMappings) {
this.propertyToAttributeMappings = ImmutableBiMap.copyOf(propertyMappings);
this.attributeToPropertyMappings = this.propertyToAttributeMappings.inverse();
}
/**
* Properties that should not be namespaced with the portlet's windowId when stored as request
* attributes
*/
@Resource(name = "nonNamespacedPortletProperties")
public void setNonNamespacedProperties(Set<String> nonNamespacedProperties) {
this.nonNamespacedProperties = ImmutableSet.copyOf(nonNamespacedProperties);
}
@Autowired
public void setPortalRequestUtils(IPortalRequestUtils portalRequestUtils) {
this.portalRequestUtils = portalRequestUtils;
}
@Override
public boolean addResponseProperty(
HttpServletRequest portletRequest,
IPortletWindow portletWindow,
String property,
String value) {
if (this.propertyToAttributeMappings.isEmpty() && this.nonNamespacedProperties.isEmpty()) {
return false;
}
final HttpServletRequest portalRequest =
this.portalRequestUtils.getOriginalPortalRequest(portletRequest);
final String attributeName = getAttributeName(portletWindow, property);
final Object existingValue = portalRequest.getAttribute(attributeName);
if (!(existingValue instanceof List)) {
this.logger.warn(
"Attribute {} for property {} exists but is NOT a List, it will be replaced",
attributeName,
property);
this.setResponseProperty(portletRequest, portletWindow, property, value);
return true;
}
logger.debug("Adding property {} as attribute {}", property, attributeName);
@SuppressWarnings("unchecked")
final List<String> values = (List<String>) existingValue;
values.add(value);
portalRequest.setAttribute(attributeName, values);
return true;
}
@Override
public boolean setResponseProperty(
HttpServletRequest portletRequest,
IPortletWindow portletWindow,
String property,
String value) {
if (this.propertyToAttributeMappings.isEmpty() && this.nonNamespacedProperties.isEmpty()) {
return false;
}
final HttpServletRequest portalRequest =
this.portalRequestUtils.getOriginalPortalRequest(portletRequest);
final String attributeName = getAttributeName(portletWindow, property);
logger.debug("Setting property {} as attribute {}", property, attributeName);
final List<String> values = new LinkedList<String>();
values.add(value);
portalRequest.setAttribute(attributeName, values);
return true;
}
protected String getAttributeName(IPortletWindow portletWindow, String property) {
final String mappedAttributeName = this.propertyToAttributeMappings.get(property);
final String attributeName;
if (mappedAttributeName == null) {
attributeName = property;
} else {
attributeName = mappedAttributeName;
}
if (this.nonNamespacedProperties.contains(property)) {
return attributeName;
}
final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId();
return portletWindowId.getStringId() + attributeName;
}
@Override
public <P extends Populator<String, String>> void populateRequestProperties(
HttpServletRequest portletRequest,
IPortletWindow portletWindow,
P propertiesPopulator) {
if (this.propertyToAttributeMappings.isEmpty() && this.nonNamespacedProperties.isEmpty()) {
return;
}
final HttpServletRequest portalRequest =
this.portalRequestUtils.getOriginalPortalRequest(portletRequest);
final String windowIdStr = portletWindow.getPortletWindowId().getStringId();
for (@SuppressWarnings("unchecked")
final Enumeration<String> attributeNames = portalRequest.getAttributeNames();
attributeNames.hasMoreElements();
) {
final String fullAttributeName = attributeNames.nextElement();
final String propertyName = getPropertyName(windowIdStr, fullAttributeName);
if (propertyName == null) {
continue;
}
logger.debug(
"Found portal request attribute {} returning as property {}",
fullAttributeName,
propertyName);
final Object value = portalRequest.getAttribute(fullAttributeName);
convertValue(propertyName, value, propertiesPopulator);
}
}
/** Convert a request attribute name to a portlet property name */
private String getPropertyName(final String windowIdStr, final String fullAttributeName) {
final String attributeName;
if (this.nonNamespacedProperties.contains(fullAttributeName)) {
attributeName = fullAttributeName;
} else if (fullAttributeName.startsWith(windowIdStr)) {
attributeName = fullAttributeName.substring(windowIdStr.length());
} else {
return null;
}
final String mappedPropertyName = this.attributeToPropertyMappings.get(attributeName);
if (mappedPropertyName == null) {
logger.warn(
"Attribute {} found that matches the portlet window ID but it is not listed in the propertyMappings or nonNamespacedProperties and will not be returned to the portlet",
attributeName);
return null;
}
return mappedPropertyName;
}
protected <P extends Populator<String, String>> void convertValue(
String name, Object value, P propertiesPopulator) {
if (value == null) {
return;
}
if (value instanceof Collection) {
for (final Object obj : (Collection<?>) value) {
propertiesPopulator.put(name, String.valueOf(obj));
}
return;
}
if (value.getClass().isArray()) {
final int len = Array.getLength(value);
for (int i = 0; i < len; i++) {
propertiesPopulator.put(name, String.valueOf(Array.get(value, i)));
}
return;
}
propertiesPopulator.put(name, String.valueOf(value));
}
}
| apache-2.0 |
jl1955/uPortal5 | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/cache/resource/CachedResource.java | 2060 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* 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 the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.apereo.portal.utils.cache.resource;
import java.io.Serializable;
import java.util.Map;
import org.springframework.core.io.Resource;
/**
* Returned by the {@link CachingResourceLoader}. Represents a IO loaded resource including
* information about when it was last loaded.
*
*/
public interface CachedResource<T> {
/** @return The Resource that was loaded */
public Resource getResource();
/** @return Additional resource files involved with loading */
public Map<Resource, Long> getAdditionalResources();
/** @return The cached resource */
public T getCachedResource();
/** @return The timestamp for when the resource was last loaded. */
public long getLastLoadTime();
/**
* Must be thread safe and follow data visibility rules
*
* @return The timestamp for the last time the resource was checked for modification
*/
public long getLastCheckTime();
/**
* Sets the timestamp for the last time the resource was checked for modification Must be thread
* safe and follow data visibility rules
*/
public void setLastCheckTime(long lastCheckTime);
/** A serializable key that represents the state of the cached resource */
public Serializable getCacheKey();
}
| apache-2.0 |
jack6215/StreamCQL | cql/src/main/java/com/huawei/streaming/cql/semanticanalyzer/parser/CQLParserBaseVisitor.java | 44928 | // Generated from CQLParser.g4 by ANTLR 4.1
package com.huawei.streaming.cql.semanticanalyzer.parser;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
/**
* This class provides an empty implementation of {@link CQLParserVisitor},
* which can be extended to create a visitor which only needs to handle a subset
* of the available methods.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
public class CQLParserBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements CQLParserVisitor<T> {
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitJoinToken(@NotNull CQLParser.JoinTokenContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitUnaryOperator(@NotNull CQLParser.UnaryOperatorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSourceDefine(@NotNull CQLParser.SourceDefineContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitFullJoin(@NotNull CQLParser.FullJoinContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitMultiInsertStatement(@NotNull CQLParser.MultiInsertStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeDay(@NotNull CQLParser.RangeDayContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitInnerClassName(@NotNull CQLParser.InnerClassNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitPath(@NotNull CQLParser.PathContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRightJoin(@NotNull CQLParser.RightJoinContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConstDoubleValue(@NotNull CQLParser.ConstDoubleValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitFieldExpression(@NotNull CQLParser.FieldExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitIfNotExists(@NotNull CQLParser.IfNotExistsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitLogicExpressionOr(@NotNull CQLParser.LogicExpressionOrContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitOrderByClause(@NotNull CQLParser.OrderByClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStreamPropertiesList(@NotNull CQLParser.StreamPropertiesListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDatasourceQuery(@NotNull CQLParser.DatasourceQueryContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitExecStatement(@NotNull CQLParser.ExecStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitInputSchemaStatement(@NotNull CQLParser.InputSchemaStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitKeyValueProperty(@NotNull CQLParser.KeyValuePropertyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitInnerJoin(@NotNull CQLParser.InnerJoinContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitMultialias(@NotNull CQLParser.MultialiasContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitPrecedenceEqualNegatableOperator(@NotNull CQLParser.PrecedenceEqualNegatableOperatorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDistributeClause(@NotNull CQLParser.DistributeClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitColumnNameTypeList(@NotNull CQLParser.ColumnNameTypeListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSubSelectClause(@NotNull CQLParser.SubSelectClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitExpressionWithLaparen(@NotNull CQLParser.ExpressionWithLaparenContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStrValue(@NotNull CQLParser.StrValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitHavingCondition(@NotNull CQLParser.HavingConditionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitOutputSchemaStatement(@NotNull CQLParser.OutputSchemaStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitOnCondition(@NotNull CQLParser.OnConditionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitInsertStatement(@NotNull CQLParser.InsertStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSourceClause(@NotNull CQLParser.SourceClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDatasourceSchema(@NotNull CQLParser.DatasourceSchemaContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCreateInputStreamStatement(@NotNull CQLParser.CreateInputStreamStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitWindowDeterminer(@NotNull CQLParser.WindowDeterminerContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDdlStatement(@NotNull CQLParser.DdlStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitIsNullLikeInExpressions(@NotNull CQLParser.IsNullLikeInExpressionsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitFromSource(@NotNull CQLParser.FromSourceContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSerdeDefine(@NotNull CQLParser.SerdeDefineContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitMultiSelect(@NotNull CQLParser.MultiSelectContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitUserDefinedClassName(@NotNull CQLParser.UserDefinedClassNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStreamNameOrAlias(@NotNull CQLParser.StreamNameOrAliasContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitColumnALias(@NotNull CQLParser.ColumnALiasContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSourceProperties(@NotNull CQLParser.SourcePropertiesContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitNullCondition(@NotNull CQLParser.NullConditionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitArithmeticStarExpression(@NotNull CQLParser.ArithmeticStarExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConstNull(@NotNull CQLParser.ConstNullContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitColumnNameOrder(@NotNull CQLParser.ColumnNameOrderContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConstLongValue(@NotNull CQLParser.ConstLongValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitMultiInsert(@NotNull CQLParser.MultiInsertContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRelationExpression(@NotNull CQLParser.RelationExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitClassName(@NotNull CQLParser.ClassNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitOperatorName(@NotNull CQLParser.OperatorNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitWindowBody(@NotNull CQLParser.WindowBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitExtended(@NotNull CQLParser.ExtendedContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitPackageNameIdentifier(@NotNull CQLParser.PackageNameIdentifierContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitLogicExpressionNot(@NotNull CQLParser.LogicExpressionNotContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConfValue(@NotNull CQLParser.ConfValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConstStingValue(@NotNull CQLParser.ConstStingValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSelectClause(@NotNull CQLParser.SelectClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSetStatement(@NotNull CQLParser.SetStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitAtomExpression(@NotNull CQLParser.AtomExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitColType(@NotNull CQLParser.ColTypeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConstFloatValue(@NotNull CQLParser.ConstFloatValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitUsingStatement(@NotNull CQLParser.UsingStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitIsForce(@NotNull CQLParser.IsForceContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSerdeProperties(@NotNull CQLParser.SerdePropertiesContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSubQueryExpression(@NotNull CQLParser.SubQueryExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitApplicationName(@NotNull CQLParser.ApplicationNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitHavingClause(@NotNull CQLParser.HavingClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitExpression(@NotNull CQLParser.ExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitBitOperator(@NotNull CQLParser.BitOperatorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitFromClause(@NotNull CQLParser.FromClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitWindowSource(@NotNull CQLParser.WindowSourceContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStreamProperties(@NotNull CQLParser.StreamPropertiesContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSearchCondition(@NotNull CQLParser.SearchConditionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSelectItem(@NotNull CQLParser.SelectItemContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCreateOperatorStatement(@NotNull CQLParser.CreateOperatorStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitJoinRigthBody(@NotNull CQLParser.JoinRigthBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitInsertUserOperatorStatement(@NotNull CQLParser.InsertUserOperatorStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDataSourceName(@NotNull CQLParser.DataSourceNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitLogicExpressionAnd(@NotNull CQLParser.LogicExpressionAndContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDatasourceProperties(@NotNull CQLParser.DatasourcePropertiesContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeBound(@NotNull CQLParser.RangeBoundContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitLimitRow(@NotNull CQLParser.LimitRowContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitIfExists(@NotNull CQLParser.IfExistsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSerdeClass(@NotNull CQLParser.SerdeClassContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCreatePipeStreamStatement(@NotNull CQLParser.CreatePipeStreamStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitShowFunctions(@NotNull CQLParser.ShowFunctionsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitEqualRelationExpression(@NotNull CQLParser.EqualRelationExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitWindowProperties(@NotNull CQLParser.WindowPropertiesContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeWindow(@NotNull CQLParser.RangeWindowContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitColumnName(@NotNull CQLParser.ColumnNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitGroupByList(@NotNull CQLParser.GroupByListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeMinutes(@NotNull CQLParser.RangeMinutesContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitWhereClause(@NotNull CQLParser.WhereClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDropFunctionStatement(@NotNull CQLParser.DropFunctionStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConstant(@NotNull CQLParser.ConstantContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStreamBody(@NotNull CQLParser.StreamBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCreateDataSourceStatement(@NotNull CQLParser.CreateDataSourceStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitPartitionbyDeterminer(@NotNull CQLParser.PartitionbyDeterminerContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRelationOperator(@NotNull CQLParser.RelationOperatorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitLimitAll(@NotNull CQLParser.LimitAllContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConfName(@NotNull CQLParser.ConfNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCastExpression(@NotNull CQLParser.CastExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitColumnNameType(@NotNull CQLParser.ColumnNameTypeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitFunction(@NotNull CQLParser.FunctionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitGroupByClause(@NotNull CQLParser.GroupByClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeTime(@NotNull CQLParser.RangeTimeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSelectAlias(@NotNull CQLParser.SelectAliasContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConstIntegerValue(@NotNull CQLParser.ConstIntegerValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitWindowName(@NotNull CQLParser.WindowNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSelectStatement(@NotNull CQLParser.SelectStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSinkClause(@NotNull CQLParser.SinkClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitGetStatement(@NotNull CQLParser.GetStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitIdentifierNot(@NotNull CQLParser.IdentifierNotContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDatasourceBody(@NotNull CQLParser.DatasourceBodyContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitShowApplications(@NotNull CQLParser.ShowApplicationsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitInsertClause(@NotNull CQLParser.InsertClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSubmitApplication(@NotNull CQLParser.SubmitApplicationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitExpressions(@NotNull CQLParser.ExpressionsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitBinaryExpression(@NotNull CQLParser.BinaryExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitExplainStatement(@NotNull CQLParser.ExplainStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCreateFunctionStatement(@NotNull CQLParser.CreateFunctionStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitJoinSource(@NotNull CQLParser.JoinSourceContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDatasourceQueryArguments(@NotNull CQLParser.DatasourceQueryArgumentsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitLeftJoin(@NotNull CQLParser.LeftJoinContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitBooleanValue(@NotNull CQLParser.BooleanValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitUnidirection(@NotNull CQLParser.UnidirectionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitGroupByExpression(@NotNull CQLParser.GroupByExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSourceAlias(@NotNull CQLParser.SourceAliasContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRowsWindow(@NotNull CQLParser.RowsWindowContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitColumnOrder(@NotNull CQLParser.ColumnOrderContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDatasourceArguments(@NotNull CQLParser.DatasourceArgumentsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeUnBound(@NotNull CQLParser.RangeUnBoundContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDistinct(@NotNull CQLParser.DistinctContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStreamSource(@NotNull CQLParser.StreamSourceContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitArithmeticPlusOperator(@NotNull CQLParser.ArithmeticPlusOperatorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSinkProperties(@NotNull CQLParser.SinkPropertiesContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCrossJoin(@NotNull CQLParser.CrossJoinContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSelectExpression(@NotNull CQLParser.SelectExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitNaturalJoin(@NotNull CQLParser.NaturalJoinContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeSeconds(@NotNull CQLParser.RangeSecondsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitColumnNameOrderList(@NotNull CQLParser.ColumnNameOrderListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStatement(@NotNull CQLParser.StatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitAddJARStatement(@NotNull CQLParser.AddJARStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitConstBigDecimalValue(@NotNull CQLParser.ConstBigDecimalValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSubQuerySource(@NotNull CQLParser.SubQuerySourceContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitPrimitiveType(@NotNull CQLParser.PrimitiveTypeContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitAddFileStatement(@NotNull CQLParser.AddFileStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitParallelClause(@NotNull CQLParser.ParallelClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCreateOutputStreamStatement(@NotNull CQLParser.CreateOutputStreamStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitFunctionName(@NotNull CQLParser.FunctionNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitLoadStatement(@NotNull CQLParser.LoadStatementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStreamAlias(@NotNull CQLParser.StreamAliasContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitLimitClause(@NotNull CQLParser.LimitClauseContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeHour(@NotNull CQLParser.RangeHourContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCqlIdentifier(@NotNull CQLParser.CqlIdentifierContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStreamName(@NotNull CQLParser.StreamNameContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitDropApplication(@NotNull CQLParser.DropApplicationContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitArithmeticPlusMinusExpression(@NotNull CQLParser.ArithmeticPlusMinusExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSelectList(@NotNull CQLParser.SelectListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitStreamAllColumns(@NotNull CQLParser.StreamAllColumnsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitCommentString(@NotNull CQLParser.CommentStringContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSingleAlias(@NotNull CQLParser.SingleAliasContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitBitExpression(@NotNull CQLParser.BitExpressionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitRangeMilliSeconds(@NotNull CQLParser.RangeMilliSecondsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitSinkDefine(@NotNull CQLParser.SinkDefineContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitComment(@NotNull CQLParser.CommentContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitFilterBeforeWindow(@NotNull CQLParser.FilterBeforeWindowContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
* <p/>
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override public T visitArithmeticStarOperator(@NotNull CQLParser.ArithmeticStarOperatorContext ctx) { return visitChildren(ctx); }
} | apache-2.0 |
terrancesnyder/solr-analytics | lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/LimitTokenCountFilterFactory.java | 2063 | package org.apache.lucene.analysis.miscellaneous;
/*
* 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.
*/
import java.util.Map;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.miscellaneous.LimitTokenCountFilter;
import org.apache.lucene.analysis.util.TokenFilterFactory;
/**
* Factory for {@link LimitTokenCountFilter}.
* <pre class="prettyprint" >
* <fieldType name="text_lngthcnt" class="solr.TextField" positionIncrementGap="100">
* <analyzer>
* <tokenizer class="solr.WhitespaceTokenizerFactory"/>
* <filter class="solr.LimitTokenCountFilterFactory" maxTokenCount="10"/>
* </analyzer>
* </fieldType></pre>
*
*/
public class LimitTokenCountFilterFactory extends TokenFilterFactory {
int maxTokenCount;
@Override
public void init(Map<String, String> args) {
super.init( args );
String maxTokenCountArg = args.get("maxTokenCount");
if (maxTokenCountArg == null) {
throw new IllegalArgumentException("maxTokenCount is mandatory.");
}
maxTokenCount = Integer.parseInt(args.get(maxTokenCountArg));
}
@Override
public TokenStream create(TokenStream input) {
return new LimitTokenCountFilter(input, maxTokenCount);
}
}
| apache-2.0 |
gabrieltavaresmelo/jsim_app_middle | src/main/java/br/com/gtmf/wsdl/ChangeClientRoomResponse.java | 1458 |
package br.com.gtmf.wsdl;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for changeClientRoomResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="changeClientRoomResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="return" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "changeClientRoomResponse", propOrder = {
"_return"
})
public class ChangeClientRoomResponse {
@XmlElement(name = "return")
protected String _return;
/**
* Gets the value of the return property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReturn() {
return _return;
}
/**
* Sets the value of the return property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReturn(String value) {
this._return = value;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/MotionGraphicsSettings.java | 4115 | /*
* 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.medialive.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* Motion Graphics Settings
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/MotionGraphicsSettings" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MotionGraphicsSettings implements Serializable, Cloneable, StructuredPojo {
private HtmlMotionGraphicsSettings htmlMotionGraphicsSettings;
/**
* @param htmlMotionGraphicsSettings
*/
public void setHtmlMotionGraphicsSettings(HtmlMotionGraphicsSettings htmlMotionGraphicsSettings) {
this.htmlMotionGraphicsSettings = htmlMotionGraphicsSettings;
}
/**
* @return
*/
public HtmlMotionGraphicsSettings getHtmlMotionGraphicsSettings() {
return this.htmlMotionGraphicsSettings;
}
/**
* @param htmlMotionGraphicsSettings
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MotionGraphicsSettings withHtmlMotionGraphicsSettings(HtmlMotionGraphicsSettings htmlMotionGraphicsSettings) {
setHtmlMotionGraphicsSettings(htmlMotionGraphicsSettings);
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 (getHtmlMotionGraphicsSettings() != null)
sb.append("HtmlMotionGraphicsSettings: ").append(getHtmlMotionGraphicsSettings());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof MotionGraphicsSettings == false)
return false;
MotionGraphicsSettings other = (MotionGraphicsSettings) obj;
if (other.getHtmlMotionGraphicsSettings() == null ^ this.getHtmlMotionGraphicsSettings() == null)
return false;
if (other.getHtmlMotionGraphicsSettings() != null && other.getHtmlMotionGraphicsSettings().equals(this.getHtmlMotionGraphicsSettings()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getHtmlMotionGraphicsSettings() == null) ? 0 : getHtmlMotionGraphicsSettings().hashCode());
return hashCode;
}
@Override
public MotionGraphicsSettings clone() {
try {
return (MotionGraphicsSettings) 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.medialive.model.transform.MotionGraphicsSettingsMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |