repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
vespa-engine/vespa
controller-server/src/main/java/com/yahoo/vespa/hosted/controller/dns/CreateRecords.java
2843
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.dns; import com.yahoo.vespa.hosted.controller.api.integration.dns.AliasTarget; import com.yahoo.vespa.hosted.controller.api.integration.dns.NameService; import com.yahoo.vespa.hosted.controller.api.integration.dns.Record; import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordName; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; /** * Create or update multiple records of the same type and name. * * @author mpolden */ public class CreateRecords implements NameServiceRequest { private final RecordName name; private final Record.Type type; private final List<Record> records; /** DO NOT USE. Public for serialization purposes */ public CreateRecords(List<Record> records) { this.name = requireOneOf(Record::name, records); this.type = requireOneOf(Record::type, records); this.records = List.copyOf(Objects.requireNonNull(records, "records must be non-null")); if (type != Record.Type.ALIAS && type != Record.Type.TXT) { throw new IllegalArgumentException("Records of type " + type + "are not supported: " + records); } } public List<Record> records() { return records; } @Override public void dispatchTo(NameService nameService) { switch (type) { case ALIAS: var targets = records.stream().map(Record::data).map(AliasTarget::unpack).collect(Collectors.toSet()); nameService.createAlias(name, targets); break; case TXT: var dataFields = records.stream().map(Record::data).collect(Collectors.toList()); nameService.createTxtRecords(name, dataFields); break; } } @Override public String toString() { return "create records " + records(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CreateRecords that = (CreateRecords) o; return records.equals(that.records); } @Override public int hashCode() { return Objects.hash(records); } /** Find exactly one distinct value of field in given list */ private static <T, V> T requireOneOf(Function<V, T> field, List<V> list) { Set<T> values = list.stream().map(field).collect(Collectors.toSet()); if (values.size() != 1) { throw new IllegalArgumentException("Expected one distinct value, but found " + values + " in " + list); } return values.iterator().next(); } }
apache-2.0
Gugli/Openfire
src/plugins/restAPI/src/java/org/jivesoftware/openfire/plugin/rest/CORSFilter.java
1070
package org.jivesoftware.openfire.plugin.rest; import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerResponseFilter; /** * The Class CORSFilter. */ public class CORSFilter implements ContainerResponseFilter { /* (non-Javadoc) * @see com.sun.jersey.spi.container.ContainerResponseFilter#filter(com.sun.jersey.spi.container.ContainerRequest, com.sun.jersey.spi.container.ContainerResponse) */ @Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { response.getHttpHeaders().add("Access-Control-Allow-Origin", "*"); response.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); return response; } }
apache-2.0
KRMAssociatesInc/eHMP
ehmp/product/production/hmp-main/src/main/java/gov/va/cpe/encounter/EncounterContext.java
292
package gov.va.cpe.encounter; import gov.va.cpe.vpr.Encounter; public interface EncounterContext { String getCurrentEncounterUid(); Encounter getCurrentEncounter(); void setCurrentEncounterUid(String encounterUid); void setCurrentEncounter(Encounter encounter); }
apache-2.0
gxa/gxa
atlas-model/src/main/java/uk/ac/ebi/microarray/atlas/model/bioentity/Software.java
3156
/* * Copyright 2008-2011 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.microarray.atlas.model.bioentity; import javax.persistence.*; /** * User: nsklyar * Date: 04/05/2011 */ @Entity public class Software { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "swSeq") @SequenceGenerator(name = "swSeq", sequenceName = "A2_SOFTWARE_SEQ", allocationSize = 1) private Long softwareid; private String name; private String version; @org.hibernate.annotations.Type(type="true_false") private boolean isActive = false; @org.hibernate.annotations.Type(type="true_false") private boolean legacy = false; Software() { } public Software(Long softwareid, String name, String version) { this.softwareid = softwareid; this.name = name; this.version = version; } public Software(String name, String version) { this.name = name; this.version = version; } public Long getSoftwareid() { return softwareid; } public String getName() { return name; } public String getVersion() { return version; } public boolean isActive() { return isActive; } public void setActive(boolean active) { isActive = active; } public String getFullName(){ StringBuilder sb = new StringBuilder(); sb.append(name).append(" v.").append(version); return sb.toString(); } @Override public String toString() { return "Software{" + "softwareid=" + softwareid + ", name='" + name + '\'' + ", version='" + version + '\'' + ", isActive=" + isActive + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Software software = (Software) o; if (name != null ? !name.equals(software.name) : software.name != null) return false; if (version != null ? !version.equals(software.version) : software.version != null) return false; return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (version != null ? version.hashCode() : 0); return result; } }
apache-2.0
darranl/directory-shared
ldap/model/src/main/java/org/apache/directory/api/ldap/model/schema/syntaxCheckers/CertificateListSyntaxChecker.java
2184
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.api.ldap.model.schema.syntaxCheckers; import org.apache.directory.api.ldap.model.constants.SchemaConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A SyntaxChecker which verifies that a value is a certificateList according to RFC 4523 : * * "Due to changes made to the definition of a CertificateList through time, * no LDAP-specific encoding is defined for this syntax. Values of this * syntax SHOULD be encoded using Distinguished Encoding Rules (DER) * [X.690] and MUST only be transferred using the ;binary transfer * option" * * It has been removed in RFC 4517 * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ @SuppressWarnings("serial") public class CertificateListSyntaxChecker extends BinarySyntaxChecker { /** A logger for this class */ private static final Logger LOG = LoggerFactory.getLogger( CertificateListSyntaxChecker.class ); /** * Creates a new instance of CertificateListSyntaxChecker. */ public CertificateListSyntaxChecker() { super(); setOid( SchemaConstants.CERTIFICATE_LIST_SYNTAX ); } /** * {@inheritDoc} */ public boolean isValidSyntax( Object value ) { LOG.debug( "Syntax valid for '{}'", value ); return true; } }
apache-2.0
masterlittle/Project-Quiz
app/src/main/java/com/project/quiz/database/StorePointsTable.java
1452
package com.project.quiz.database; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.project.quiz.log.Logging; import com.project.quiz.utils.CommonLibs; /** * Created by Shitij on 28/07/15. */ public class StorePointsTable { public static final String TABLE_DATA_TEXT = "table_points"; public static final String TEAM_NUMBER = "team_number"; public static final String CURRENT_SCORE = "current_score"; public static final String CHANGED_SCORE = "changed_score"; public static final String COLUMN_ID = "_id"; // Database creation SQL statement private static final String DATABASE_CREATE = "create table " + TABLE_DATA_TEXT + "(" + COLUMN_ID + " integer primary key autoincrement, " + TEAM_NUMBER + " text not null unique, " + CURRENT_SCORE + " int, " + CHANGED_SCORE + " int " + ");"; public static void onCreate(SQLiteDatabase database) { try { database.execSQL(DATABASE_CREATE); } catch (Exception e){ Logging.logError("StoreDataTable", e.toString(), CommonLibs.Priority.VERY_HIGH); } } public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)throws Exception { database.execSQL("DROP TABLE IF EXISTS " + TABLE_DATA_TEXT); onCreate(database); } }
apache-2.0
benmfaul/XRTB
src/com/xrtb/bidder/DataAssetTypes.java
914
package com.xrtb.bidder; import java.util.HashMap; /** * A list of common asset element types of native advertising. * @author Ben M. Faul * */ public class DataAssetTypes { private static HashMap<Integer,String> types = new HashMap<Integer,String>(); static { add(1,"sponsored"); add(2,"desc"); add(3,"rating"); add(4,"likes"); add(5,"downloads"); add(6,"price"); add(7,"saleprice"); add(8,"phone"); add(9,"address"); add(10,"desc2"); add(11,"displayurl"); add(12,"ctatext"); } /** * Add data asset id to hash * @param a Integer. The data asset id * @param b String. The type. */ static void add(Integer a, String b) { types.put(a,b); } /** * Given the data asset id, return the description. * @param key String. The file suffix. * @return String. The mime type, or null */ public static String substitute(Integer key) { return types.get(key); } }
apache-2.0
liangzonghua/leetcode
src/main/java/cn/hashell/leetcode/zigZagConversion/Solution.java
637
package cn.hashell.leetcode.zigZagConversion; public class Solution { public String convert(String s, int nRows) { if(s == null || nRows <= 1 || nRows >= s.length()){ return s; } StringBuffer buffer = new StringBuffer(s.length()); for(int i=1;i<=nRows;i++){ int start = i-1; boolean isEven = true; while(start<s.length()){ buffer.append(s.charAt(start)); if(i ==1 || i == nRows){ start = start + (nRows-1)*2; } else if(isEven){ start = start + (nRows-i)*2; isEven = false; } else { start = start + (i-1)*2; isEven = true; } } } return buffer.toString(); } }
apache-2.0
wanghuizi/fengduo
bee-model/src/main/java/com/fengduo/bee/model/cons/TeamCountEnum.java
1288
/* * Copyright 2015-2020 Fengduo.co All right reserved. This software is the confidential and proprietary information of * Fengduo.co ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into with Fengduo.co. */ package com.fengduo.bee.model.cons; /** * 团队人数枚举 * * <pre> * 0~50人 * 50~100人 * 100~150人 * 150~200人 * 200人以上 * </pre> * * @author zxc Jun 9, 2015 1:29:15 PM */ public enum TeamCountEnum { // FIFTY(0, "fifty", "0-50"), // HUNDRED(100, "hundred", "50-100"), // HUNDRED_FIFTY(200, "two_hundred", "100-150"), // TWO_HUNDRED(300, "two_hundred", "150-200"), // OTHER(400, "other", " &gt;200"); public int value; public String name; public String desc; private TeamCountEnum(int value, String name, String desc) { this.value = value; this.name = name; this.desc = desc; } public Integer getValue() { return value; } public String getName() { return name; } public String getDesc() { return desc; } public static TeamCountEnum getAction(int value) { for (TeamCountEnum state : values()) { if (value == state.getValue()) return state; } return null; } }
apache-2.0
multi-os-engine/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/networkextension/NEProvider.java
9800
/* Copyright 2014-2016 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apple.networkextension; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCBlock; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; /** * [@interface] NEProvider * <p> * The NEProvider class declares the programmatic interface that is common for all Network Extension providers. * <p> * See the sub classes of NEProvider for more details. Developers of Network Extension providers should create sub classes of the sub classes of NEProvider. * <p> * Instances of this class are thread safe. */ @Generated @Library("NetworkExtension") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class NEProvider extends NSObject { static { NatJ.register(); } @Generated protected NEProvider(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native NEProvider alloc(); @Owned @Generated @Selector("allocWithZone:") public static native NEProvider allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") public static native NEProvider new_objc(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); /** * createTCPConnectionToEndpoint:enableTLS:TLSParameters:delegate: * <p> * This function can be called by subclass implementations to create a TCP connection to a given network endpoint. This function should not be overridden by subclasses. * * @param remoteEndpoint An NWEndpoint object that specifies the remote network endpoint to connect to. * @param enableTLS A flag indicating if a TLS session should be negotiated on the connection. * @param TLSParameters A set of optional TLS parameters. Only valid if enableTLS is YES. If TLSParameters is nil, the default system parameters will be used for TLS negotiation. * @param delegate An object to use as the connections delegate. This object should conform to the NWTCPConnectionAuthenticationDelegate protocol. * @return An NWTCPConnection object. */ @Generated @Selector("createTCPConnectionToEndpoint:enableTLS:TLSParameters:delegate:") public native NWTCPConnection createTCPConnectionToEndpointEnableTLSTLSParametersDelegate(NWEndpoint remoteEndpoint, boolean enableTLS, NWTLSParameters TLSParameters, @Mapped(ObjCObjectMapper.class) Object delegate); /** * createUDPSessionToEndpoint:fromEndpoint: * <p> * This function can be called by subclass implementations to create a UDP session between a local network endpoint and a remote network endpoint. This function should not be overridden by subclasses. * * @param remoteEndpoint An NWEndpoint object that specifies the remote endpoint to which UDP datagrams will be sent by the UDP session. * @param localEndpoint An NWHostEndpoint object that specifies the local IP address endpoint to use as the source endpoint of the UDP session. * @return An NWUDPSession object. */ @Generated @Selector("createUDPSessionToEndpoint:fromEndpoint:") public native NWUDPSession createUDPSessionToEndpointFromEndpoint(NWEndpoint remoteEndpoint, NWHostEndpoint localEndpoint); /** * [@property] defaultPath * <p> * The current default path for connections created by the provider. Use KVO to watch for network changes. */ @Generated @Selector("defaultPath") public native NWPath defaultPath(); /** * displayMessage:completionHandler: * <p> * This method can be called by subclass implementations to display a message to the user. * * @param message The message to be displayed. * @param completionHandler A block that is executed when the user acknowledges the message. If this method is called on a NEFilterDataProvider instance or the message cannot be displayed, then the completion handler block will be executed immediately with success parameter set to NO. If the message was successfully displayed to the user, then the completion handler block is executed with the success parameter set to YES when the user dismisses the message. */ @Generated @Selector("displayMessage:completionHandler:") public native void displayMessageCompletionHandler(String message, @ObjCBlock(name = "call_displayMessageCompletionHandler") Block_displayMessageCompletionHandler completionHandler); @Generated @Selector("init") public native NEProvider init(); /** * sleepWithCompletionHandler: * <p> * This function is called by the framework when the system is about to go to sleep. Subclass developers can override this method to implement custom behavior such as closing connections or pausing some network activity. * * @param completionHandler When the method is finished handling the sleep event it must execute this completion handler. */ @Generated @Selector("sleepWithCompletionHandler:") public native void sleepWithCompletionHandler( @ObjCBlock(name = "call_sleepWithCompletionHandler") Block_sleepWithCompletionHandler completionHandler); /** * wake * <p> * This function is called by the framework immediately after the system wakes up from sleep. Subclass developers can override this method to implement custom behavior such as re-establishing connections or resuming some network activity. */ @Generated @Selector("wake") public native void wake(); @Runtime(ObjCRuntime.class) @Generated public interface Block_displayMessageCompletionHandler { @Generated void call_displayMessageCompletionHandler(boolean success); } @Runtime(ObjCRuntime.class) @Generated public interface Block_sleepWithCompletionHandler { @Generated void call_sleepWithCompletionHandler(); } }
apache-2.0
AlexDoh/WebStore-Spring-JS
src/main/java/com/odmytrenko/spring/dao/AbstractDao.java
103
package com.odmytrenko.spring.dao; public abstract class AbstractDao<T> implements GenericDao<T> { }
apache-2.0
cloudant/sync-android
cloudant-sync-datastore-core/src/test/java/com/cloudant/sync/internal/replication/ChangesResultWrapperTest.java
3714
/* * Copyright © 2017 IBM Corp. All rights reserved. * * Copyright © 2013 Cloudant, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.cloudant.sync.internal.replication; import com.cloudant.sync.internal.mazha.ChangesResult; import com.cloudant.sync.internal.util.JSONUtils; import com.cloudant.sync.util.TestUtils; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; public class ChangesResultWrapperTest { @Before public void setUp() throws IOException { } @Test public void load_data_from_file_with_really_long_last_sequence() throws Exception { String expectedLastSeq = "7-g1AAAADfeJzLYWBgYMlgTmGQS0lKzi9KdUhJMjTUyyrNSS3QS87JL01JzCvRy0styQGqY0pkSLL___9_ViIbmg5jXDqSHIBkUj1YEwOx1uSxAEmGBiAF1LcfU6MJfo0HIBqBNjJmAQBtaklG"; ChangesResult changes = getChangeResultFromFile(TestUtils.loadFixture("fixture/change_feed_0.json")); Assert.assertNotNull(changes); Assert.assertEquals(3, changes.size()); Assert.assertEquals(expectedLastSeq, changes.getLastSeq()); } @Test public void test_load_data_from_file() throws Exception { ChangesResult changes = getChangeResultFromFile(TestUtils.loadFixture("fixture/change_feed_1.json")); Assert.assertNotNull(changes); Assert.assertEquals(2, changes.size()); } @Test public void openRevisions_twoRows() throws Exception { ChangesResult data = getChangeResultFromFile(TestUtils.loadFixture("fixture/change_feed_0.json")); ChangesResultWrapper changes = new ChangesResultWrapper(data); Map<String, List<String>> openRevisionsList1 = changes.openRevisions(0, 1); Assert.assertEquals(1, openRevisionsList1.size()); Map<String, List<String>> openRevisionsList2 = changes.openRevisions(0, 2); Assert.assertEquals(2, openRevisionsList2.size()); } @Test(expected = IllegalArgumentException.class) public void openRevisions_invalidIndexMinusOne_exception() throws Exception { ChangesResult data = getChangeResultFromFile(TestUtils.loadFixture("fixture/change_feed_0.json")); ChangesResultWrapper changes = new ChangesResultWrapper(data); changes.openRevisions(-1, 2); } private ChangesResult getChangeResultFromFile(File file) throws IOException { byte[] data = FileUtils.readFileToByteArray(file); return JSONUtils.deserialize(data, ChangesResult.class); } @Test public void size() throws IOException { ChangesResult data = getChangeResultFromFile(TestUtils.loadFixture("fixture/change_feed_1.json")); ChangesResultWrapper changes = new ChangesResultWrapper(data); Assert.assertEquals(2, changes.size()); } @Test public void tenK_changesRow() throws IOException { ChangesResult data = getChangeResultFromFile(TestUtils.loadFixture("fixture/10K_changes_feeds.json")); ChangesResultWrapper changes = new ChangesResultWrapper(data); Assert.assertEquals(10000, changes.size()); } }
apache-2.0
Orange-OpenSource/fiware-ngsi-api
ngsi-server/src/main/java/com/orange/ngsi/server/NgsiValidation.java
11599
/* * Copyright (C) 2015 Orange * * 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.orange.ngsi.server; import com.orange.ngsi.exception.MismatchIdException; import com.orange.ngsi.exception.MissingRequestParameterException; import com.orange.ngsi.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.net.URI; import java.util.List; /** * Created by pborscia on 07/08/2015. */ @Component public class NgsiValidation { private static Logger logger = LoggerFactory.getLogger(NgsiValidation.class); public void checkUpdateContext(UpdateContext updateContext) throws MissingRequestParameterException { if (updateContext.getUpdateAction() == null) { throw new MissingRequestParameterException("updateAction", "string"); } if (nullOrEmpty(updateContext.getContextElements())) { throw new MissingRequestParameterException("contextElements", "List<ContextElement>"); } for (ContextElement contextElement : updateContext.getContextElements()) { checkContextElement(contextElement); } } public void checkNotifyContext(NotifyContext notifyContext) throws MissingRequestParameterException { if (nullOrEmpty(notifyContext.getSubscriptionId())) { throw new MissingRequestParameterException("subscriptionId", "string"); } if (nullOrEmpty(notifyContext.getOriginator())){ throw new MissingRequestParameterException("originator", "URI"); } if (nullOrEmpty(notifyContext.getContextElementResponseList())) { throw new MissingRequestParameterException("contextElementResponse", "List<ContextElementResponse>"); } for (ContextElementResponse contextElementResponse : notifyContext.getContextElementResponseList()) { checkContextElementResponse(contextElementResponse); } } public void checkRegisterContext(RegisterContext registerContext) throws MissingRequestParameterException { if (nullOrEmpty(registerContext.getContextRegistrationList())) { throw new MissingRequestParameterException("contextRegistrations", "List<ContextRegistration>"); } for (ContextRegistration contextRegistration : registerContext.getContextRegistrationList()) { checkContextRegistration(contextRegistration); } } public void checkSubscribeContext(SubscribeContext subscribeContext) throws MissingRequestParameterException { if (nullOrEmpty(subscribeContext.getEntityIdList())) { throw new MissingRequestParameterException("entities", "List<EntityId>"); } for(EntityId entityId: subscribeContext.getEntityIdList()) { checkEntityId(entityId); } if (nullOrEmpty(subscribeContext.getReference())){ throw new MissingRequestParameterException("reference", "URI"); } if (subscribeContext.getRestriction() != null) { if (nullOrEmpty(subscribeContext.getRestriction().getAttributeExpression()) && nullOrEmpty(subscribeContext.getRestriction().getScopes())) { throw new MissingRequestParameterException("attributeExpression or scopes", "string"); } } } public void checkUpdateContextSubscription(UpdateContextSubscription updateContextSubscription) throws MissingRequestParameterException { if (nullOrEmpty(updateContextSubscription.getSubscriptionId())){ throw new MissingRequestParameterException("subscriptionId", "String"); } if (updateContextSubscription.getRestriction() != null) { if (nullOrEmpty(updateContextSubscription.getRestriction().getAttributeExpression()) && nullOrEmpty(updateContextSubscription.getRestriction().getScopes())) { throw new MissingRequestParameterException("attributeExpression or scopes", "string"); } } } public void checkUnsubscribeContext(UnsubscribeContext unsubscribeContext) throws MissingRequestParameterException { if (nullOrEmpty(unsubscribeContext.getSubscriptionId())){ throw new MissingRequestParameterException("subscriptionId", "String"); } } public void checkQueryContext(QueryContext queryContext) throws MissingRequestParameterException { if (nullOrEmpty(queryContext.getEntityIdList())) { throw new MissingRequestParameterException("entities", "List<EntityId>"); } for(EntityId entityId : queryContext.getEntityIdList()) { checkEntityId(entityId); } if (queryContext.getRestriction() != null) { if (nullOrEmpty(queryContext.getRestriction().getAttributeExpression())) { throw new MissingRequestParameterException("attributeExpression", "string"); } } } public void checkAppendContextElement(AppendContextElement appendContextElement) throws MissingRequestParameterException { if (nullOrEmpty(appendContextElement.getAttributeList())) { throw new MissingRequestParameterException("contextAttributes", "List<ContextAttribute>"); } } public void checkUpdateContextElement(UpdateContextElement updateContextElement) throws MissingRequestParameterException { if (nullOrEmpty(updateContextElement.getContextAttributes())) { throw new MissingRequestParameterException("contextAttributes", "List<ContextAttribute>"); } } public void checkUpdateContextAttribute(String entityID, String attributeName, String valueID, UpdateContextAttribute updateContextAttribute) throws MissingRequestParameterException, MismatchIdException { if (nullOrEmpty(entityID)) { throw new MissingRequestParameterException("entityID", "string"); } if (nullOrEmpty(attributeName)) { throw new MissingRequestParameterException("attributeName", "string"); } if (updateContextAttribute == null || updateContextAttribute.getAttribute() == null) { throw new MissingRequestParameterException("attribute", "ContextAttribute"); } // Check attribute name matching if (!attributeName.equals(updateContextAttribute.getAttribute().getName())) { throw new MismatchIdException(attributeName, updateContextAttribute.getAttribute().getName()); } // Check optional valueID matching if (valueID != null) { if (nullOrEmpty(valueID)) { // tests just emptiness throw new MissingRequestParameterException("valueID", "string"); } if (updateContextAttribute.getAttribute().getMetadata() == null) { throw new MissingRequestParameterException("metadata", "Metadata"); } // Check Metadata ID exists and equals valueID for (ContextMetadata metadata : updateContextAttribute.getAttribute().getMetadata()) { if ("ID".equals(metadata.getName())) { if (valueID.equals(metadata.getValue())) { return; // ! \\ Early return ! } throw new MismatchIdException(valueID, String.valueOf(metadata.getValue())); } } throw new MissingRequestParameterException("ID", "Metadata ID"); } } public void checkUpdateSubscription(String subscriptionID, UpdateContextSubscription updateContextSubscription) throws MissingRequestParameterException, MismatchIdException { checkUpdateContextSubscription(updateContextSubscription); // Check that subscriptionID parameter is equal to the one given in the message body if (!subscriptionID.equals(updateContextSubscription.getSubscriptionId())) { throw new MismatchIdException(subscriptionID, updateContextSubscription.getSubscriptionId()); } } private void checkContextElementResponse(ContextElementResponse contextElementResponse) throws MissingRequestParameterException { if (contextElementResponse.getStatusCode() == null) { throw new MissingRequestParameterException("statusCode", "StatusCode"); } if (contextElementResponse.getContextElement() == null) { throw new MissingRequestParameterException("contextElement", "ContextElement"); } checkContextElement(contextElementResponse.getContextElement()); } private void checkContextElement(ContextElement contextElement) throws MissingRequestParameterException { if (contextElement.getEntityId() == null) { throw new MissingRequestParameterException("entityId", "EntityId"); } checkEntityId(contextElement.getEntityId()); if (nullOrEmpty(contextElement.getContextAttributeList())) { throw new MissingRequestParameterException("contextAttributes", "List<ContextAttribute>"); } } private void checkEntityId(EntityId entityId) throws MissingRequestParameterException { if (nullOrEmpty(entityId.getId())) { throw new MissingRequestParameterException("id", "string"); } if (nullOrEmpty(entityId.getType())) { throw new MissingRequestParameterException("type", "string"); } if (entityId.getIsPattern() == null) { entityId.setIsPattern(false); } } private void checkContextRegistration(ContextRegistration contextRegistration) throws MissingRequestParameterException { if (nullOrEmpty(contextRegistration.getProvidingApplication())){ throw new MissingRequestParameterException("providingApplication", "URI"); } if (contextRegistration.getEntityIdList() != null) { for(EntityId entityId: contextRegistration.getEntityIdList()) { checkEntityId(entityId); } } if (contextRegistration.getContextRegistrationAttributeList() != null) { for(ContextRegistrationAttribute attribute: contextRegistration.getContextRegistrationAttributeList()) { checkContextRegistrationAttribute(attribute); } } } private void checkContextRegistrationAttribute(ContextRegistrationAttribute attribute) throws MissingRequestParameterException { if ((attribute.getName() == null) || (attribute.getName().isEmpty())) { throw new MissingRequestParameterException("name", "string"); } if (attribute.getIsDomain() == null) { throw new MissingRequestParameterException("isDomain", "boolean"); } } private static boolean nullOrEmpty(URI e) { return e == null || e.toString().isEmpty(); } private static boolean nullOrEmpty(String e) { return e == null || e.isEmpty(); } private static boolean nullOrEmpty(List e) { return e == null || e.isEmpty(); } }
apache-2.0
SxdsF/Whoosh
whoosh/src/main/java/com/sxdsf/whoosh/info/Destination.java
410
package com.sxdsf.whoosh.info; import java.util.UUID; /** * com.sxdsf.whoosh.info.Destination * * @author 孙博闻 * @date 2015/12/17 23:39 * @desc 目的地接口 */ public interface Destination { /** * 返回目的地的名称 * * @return */ String getDestinationName(); /** * 返回目的地的唯一Id * * @return */ UUID getUniqueId(); }
apache-2.0
atomashpolskiy/bt
bt-core/src/main/java/bt/net/Peer.java
1629
/* * Copyright (c) 2016—2021 Andrei Tomashpolskiy and 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 bt.net; import bt.peer.PeerOptions; import java.net.InetAddress; import java.util.Optional; /** * Represents a peer, accessible on the Internet. * * @since 1.0 */ public interface Peer { /** * @return Peer Internet address. * @since 1.0 */ InetAddress getInetAddress(); /** * @return true, if the peer's listening port is not known yet * @see #getPort() * @since 1.9 */ boolean isPortUnknown(); /** * @return Peer's listening port or {@link InetPeer#UNKNOWN_PORT}, if it's not known yet * (e.g. when the connection is incoming and the remote side hasn't * yet communicated to us its' listening port via extended handshake) * @since 1.0 */ int getPort(); /** * @return Optional peer ID * @since 1.0 */ Optional<PeerId> getPeerId(); /** * @return Peer options and preferences * @since 1.2 */ PeerOptions getOptions(); }
apache-2.0
GaneshSPatil/gocd
server/src/test-fast/java/com/thoughtworks/go/server/service/plugins/processor/serverhealth/ServerHealthRequestProcessorTest.java
4528
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.service.plugins.processor.serverhealth; import com.google.gson.Gson; import com.thoughtworks.go.plugin.api.request.DefaultGoApiRequest; import com.thoughtworks.go.plugin.api.response.GoApiResponse; import com.thoughtworks.go.plugin.infra.PluginRequestProcessorRegistry; import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor; import com.thoughtworks.go.serverhealth.HealthStateScope; import com.thoughtworks.go.serverhealth.ServerHealthService; import com.thoughtworks.go.serverhealth.ServerHealthState; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import java.util.Map; import static com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse.INTERNAL_ERROR; import static com.thoughtworks.go.plugin.api.response.DefaultGoApiResponse.SUCCESS_RESPONSE_CODE; import static com.thoughtworks.go.server.service.plugins.processor.serverhealth.ServerHealthRequestProcessor.ADD_SERVER_HEALTH_MESSAGES; import static com.thoughtworks.go.util.DataStructureUtils.m; import static java.util.Arrays.asList; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.*; public class ServerHealthRequestProcessorTest { private static final String PLUGIN_ID = "plugin-id-1"; private ServerHealthService serverHealthService; private PluginRequestProcessorRegistry requestProcessorRegistry; private ServerHealthRequestProcessor processor; private GoPluginDescriptor descriptor; @BeforeEach public void setUp() { serverHealthService = mock(ServerHealthService.class); requestProcessorRegistry = mock(PluginRequestProcessorRegistry.class); descriptor = GoPluginDescriptor.builder().id(PLUGIN_ID).build(); processor = new ServerHealthRequestProcessor(requestProcessorRegistry, serverHealthService); } @Test public void shouldRemoveServerHealthMessagesForThePluginBeforeAddingNewOnes() { processor.process(descriptor, createRequest("1.0", "[]")); verify(serverHealthService).removeByScope(HealthStateScope.fromPlugin(PLUGIN_ID)); } @Test public void shouldAddDeserializedServerHealthMessages() { String requestBody = new Gson().toJson(asList( new PluginHealthMessage("warning", "message 1"), new PluginHealthMessage("error", "message 2") )); GoApiResponse response = processor.process(descriptor, createRequest("1.0", requestBody)); assertThat(response.responseCode()).isEqualTo(SUCCESS_RESPONSE_CODE); ArgumentCaptor<ServerHealthState> argumentCaptor = ArgumentCaptor.forClass(ServerHealthState.class); InOrder inOrder = inOrder(serverHealthService); inOrder.verify(serverHealthService, times(1)).removeByScope(HealthStateScope.fromPlugin(PLUGIN_ID)); inOrder.verify(serverHealthService, times(2)).update(argumentCaptor.capture()); assertThat(argumentCaptor.getAllValues().get(0).getDescription()).isEqualTo("message 1"); assertThat(argumentCaptor.getAllValues().get(1).getDescription()).isEqualTo("message 2"); } @Test public void shouldRespondWithAFailedResponseCodeAndMessageIfSomethingGoesWrong() { GoApiResponse response = processor.process(descriptor, createRequest("1.0", "INVALID_JSON")); assertThat(response.responseCode()).isEqualTo(INTERNAL_ERROR); assertThat(new Gson().fromJson(response.responseBody(), Map.class)).isEqualTo(m("message", "Failed to deserialize message from plugin: INVALID_JSON")); } private DefaultGoApiRequest createRequest(String apiVersion, String requestBody) { DefaultGoApiRequest request = new DefaultGoApiRequest(ADD_SERVER_HEALTH_MESSAGES, apiVersion, null); request.setRequestBody(requestBody); return request; } }
apache-2.0
gcvt/siebog
siebog/src/siebog/utils/ExecutorService.java
3822
/** * 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 siebog.utils; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Resource; import javax.ejb.LocalBean; import javax.ejb.Singleton; import javax.enterprise.concurrent.ManagedExecutorService; import javax.enterprise.concurrent.ManagedScheduledExecutorService; import siebog.agents.AID; import siebog.agents.HeartbeatMessage; /** * Wrapper around (managed) executor services. * * @author <a href="mitrovic.dejan@gmail.com">Dejan Mitrovic</a> */ @Singleton @LocalBean public class ExecutorService { @Resource(lookup = "java:jboss/ee/concurrency/executor/default") private ManagedExecutorService executor; @Resource(lookup = "java:jboss/ee/concurrency/scheduler/default") private ManagedScheduledExecutorService scheduler; private AtomicLong hbCounter = new AtomicLong(); private Map<Long, HeartbeatMessage> heartbeats = Collections.synchronizedMap(new HashMap<Long, HeartbeatMessage>()); public Future<?> execute(Runnable task) { return executor.submit(task); } public <T> Future<?> execute(final RunnableWithParam<T> task, final T param) { return execute(new Runnable() { @Override public void run() { task.run(param); } }); } public ScheduledFuture<?> execute(Runnable task, long delayMillis) { return scheduler.schedule(task, delayMillis, TimeUnit.MILLISECONDS); } public <T> ScheduledFuture<?> execute(final RunnableWithParam<T> task, long delayMillis, final T param) { return execute(new Runnable() { @Override public void run() { task.run(param); } }, delayMillis); } public ScheduledFuture<?> schedule(Runnable task, long initialDelayMillis, long periodMillis) { return scheduler.scheduleAtFixedRate(task, initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS); } public <T> ScheduledFuture<?> schedule(final RunnableWithParam<T> task, long initialDelayMillis, long periodMillis, final T param) { return schedule(new Runnable() { @Override public void run() { task.run(param); } }, initialDelayMillis, periodMillis); } public long registerHeartbeat(AID aid, long delayMilliseconds, String content) { long handle = hbCounter.incrementAndGet(); HeartbeatMessage msg = new HeartbeatMessage(aid, handle); msg.content = content; heartbeats.put(handle, msg); signalHeartbeat(handle); return handle; } public boolean signalHeartbeat(long handle) { final HeartbeatMessage msg = heartbeats.get(handle); if (msg != null) { execute(new Runnable() { @Override public void run() { ObjectFactory.getMessageManager().post(msg); } }); return true; } return false; } public boolean isValidHeartbeatHandle(long handle) { return heartbeats.containsKey(handle); } public void cancelHeartbeat(long handle) { heartbeats.remove(handle); } }
apache-2.0
pdrados/cas
support/cas-server-support-u2f/src/test/java/org/apereo/cas/adaptors/u2f/web/flow/U2FMultifactorWebflowConfigurerTests.java
1225
package org.apereo.cas.adaptors.u2f.web.flow; import org.apereo.cas.web.flow.configurer.BaseMultifactorWebflowConfigurerTests; import lombok.Getter; import org.junit.jupiter.api.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.webflow.definition.registry.FlowDefinitionRegistry; /** * This is {@link U2FMultifactorWebflowConfigurerTests}. * * @author Misagh Moayyed * @since 6.3.0 */ @SpringBootTest(classes = { BaseU2FWebflowActionTests.U2FTestConfiguration.class, BaseU2FWebflowActionTests.SharedTestConfiguration.class }, properties = { "cas.authn.mfa.u2f.trusted-device-enabled=true", "cas.authn.mfa.trusted.device-registration-enabled=true" }) @Tag("WebflowConfig") @Getter public class U2FMultifactorWebflowConfigurerTests extends BaseMultifactorWebflowConfigurerTests { @Autowired @Qualifier("u2fFlowRegistry") private FlowDefinitionRegistry multifactorFlowDefinitionRegistry; @Override protected String getMultifactorEventId() { return U2FMultifactorWebflowConfigurer.MFA_U2F_EVENT_ID; } }
apache-2.0
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-middleware/it/ksb/src/test/java/org/kuali/rice/ksb/messaging/MessageFetcherTest.java
5766
/** * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.ksb.messaging; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; import javax.xml.namespace.QName; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.kuali.rice.core.api.config.property.ConfigContext; import org.kuali.rice.ksb.api.KsbApiServiceLocator; import org.kuali.rice.ksb.messaging.remotedservices.TestHarnessSharedTopic; import org.kuali.rice.ksb.messaging.service.KSBJavaService; import org.kuali.rice.ksb.service.KSBServiceLocator; import org.kuali.rice.ksb.test.KSBTestCase; import org.kuali.rice.ksb.util.KSBConstants; /** * Tests {@link MessageFetcher}. Turn messaging off but leave persistence on. * this will result in messages being persisted to db but not delivered. from * there we start up the {@link MessageFetcher} and make sure he does his job. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ public class MessageFetcherTest extends KSBTestCase { @Before @Override public void setUp() throws Exception { super.setUp(); ConfigContext.getCurrentContextConfig().putProperty(KSBConstants.Config.MESSAGING_OFF, "true"); TestHarnessSharedTopic.CALL_COUNT = 0; TestHarnessSharedTopic.CALL_COUNT_NOTIFICATION_THRESHOLD = 0; } @After @Override public void tearDown() throws Exception { TestHarnessSharedTopic.CALL_COUNT = 0; } @Test public void testRequeueMessages() throws Exception { List<PersistedMessageBO> messages = KSBServiceLocator.getMessageQueueService().getNextDocuments(null); assertEquals("Should have no messages in the queue.", 0, messages.size()); // this number is way over the top but we're going to see if it works in // an overworked CI env. TestHarnessSharedTopic.CALL_COUNT_NOTIFICATION_THRESHOLD = 500; for (int i = 0; i < TestHarnessSharedTopic.CALL_COUNT_NOTIFICATION_THRESHOLD; i++) { sendMessage(); } // make sure all async calls land in the db Thread.sleep(5000); messages = KSBServiceLocator.getMessageQueueService().getNextDocuments(null); assertEquals("Should have 500 messages in the queue.", 500, messages.size()); turnOnMessaging(); new MessageFetcher((Integer) null).run(); synchronized (TestHarnessSharedTopic.LOCK) { TestHarnessSharedTopic.LOCK.wait(5 * 60 * 1000); } // sleep here for half a second because the notify above is executed from inside the database transaction in TestHarnessSharedTopic, // we need to give that transaction time to be fully committed. Thread.sleep(500); assertEquals("Service not called by message fetcher", TestHarnessSharedTopic.CALL_COUNT, TestHarnessSharedTopic.CALL_COUNT_NOTIFICATION_THRESHOLD); messages = KSBServiceLocator.getMessageQueueService().getNextDocuments(null); assertEquals("Should still have no messages in the queue.", 0, messages.size()); } private void sendMessage() { QName serviceName = QName.valueOf("{testAppsSharedTopic}sharedTopic"); KSBJavaService testJavaAsyncService = (KSBJavaService) KsbApiServiceLocator.getMessageHelper().getServiceAsynchronously(serviceName); testJavaAsyncService.invoke(new ClientAppServiceSharedPayloadObj("message content", false)); } private void turnOnMessaging() { ConfigContext.getCurrentContextConfig().putProperty(KSBConstants.Config.MESSAGING_OFF, "false"); } @Test public void testRequeueSingleMessage() throws Exception { TestHarnessSharedTopic.CALL_COUNT_NOTIFICATION_THRESHOLD = 1; // record two messages sendMessage(); sendMessage(); List<PersistedMessageBO> messages = KSBServiceLocator.getMessageQueueService().getNextDocuments(null); assertEquals(2, messages.size()); assertNotNull("message should have been persisted", messages.get(0)); turnOnMessaging(); // fetch and deliver one message new MessageFetcher(messages.get(0).getRouteQueueId()).run(); synchronized (TestHarnessSharedTopic.LOCK) { TestHarnessSharedTopic.LOCK.wait(3 * 1000); } // sleep here for half a second because the notify above is executed from inside the database transaction in TestHarnessSharedTopic, // we need to give that transaction time to be fully committed. Thread.sleep(500); assertEquals("Service not called by message fetcher correct number of times", 1, TestHarnessSharedTopic.CALL_COUNT); for (int i = 0; i < 10; i++) { if (KSBServiceLocator.getMessageQueueService().getNextDocuments(null).size() == 1) { break; } Thread.sleep(1000); } assertEquals("Message Queue should have a single remaining message because only single message was resent", 1, KSBServiceLocator.getMessageQueueService().getNextDocuments(null).size()); } }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Features/Base/src/main/java/ghidra/app/cmd/function/CreateFunctionDefinitionCmd.java
3017
/* ### * IP: GHIDRA * * 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 ghidra.app.cmd.function; import ghidra.app.services.DataTypeManagerService; import ghidra.framework.cmd.Command; import ghidra.framework.model.DomainObject; import ghidra.framework.plugintool.ServiceProvider; import ghidra.framework.store.FileSystem; import ghidra.program.model.address.Address; import ghidra.program.model.data.*; import ghidra.program.model.listing.*; /** * Command for creating a function definition data type based on the * function signature for a function at an address. */ public class CreateFunctionDefinitionCmd implements Command { private Address entry; private final ServiceProvider serviceProvider; private String statusMsg = ""; /** * Constructs a new command for creating a function definition. * @param entry entry point address for the function whose signature is to * be used to create the function defintion data type. */ public CreateFunctionDefinitionCmd(Address entry, ServiceProvider serviceProvider) { this.entry = entry; this.serviceProvider = serviceProvider; } /** * * @see ghidra.framework.cmd.Command#getName() */ @Override public String getName() { return "Create Function Definition"; } /** * * @see ghidra.framework.cmd.Command#applyTo(ghidra.framework.model.DomainObject) */ @Override public boolean applyTo(DomainObject obj) { Program program = (Program) obj; // save off the function signature // get the body, comment, stack, return type Listing listing = program.getListing(); DataTypeManager dtm = listing.getDataTypeManager(); Function func = listing.getFunctionAt(entry); if (func == null) { return false; } FunctionSignature sig; try { sig = func.getSignature(true); } catch (IllegalArgumentException e) { if (func.getName().indexOf(FileSystem.SEPARATOR_CHAR) >= 0) { statusMsg = "Datatype names can not contain a '" + FileSystem.SEPARATOR_CHAR + "'"; } else { statusMsg = e.getMessage(); } return false; } FunctionDefinitionDataType functionDef = new FunctionDefinitionDataType(sig); DataType newType = dtm.resolve(functionDef, null); DataTypeManagerService service = serviceProvider.getService(DataTypeManagerService.class); if (service != null) { service.setDataTypeSelected(newType); } return true; } /** * @see ghidra.framework.cmd.Command#getStatusMsg() */ @Override public String getStatusMsg() { return statusMsg; } }
apache-2.0
rapidoid/rapidoid
rapidoid-http-server/src/main/java/org/rapidoid/http/Headers.java
2588
/*- * #%L * rapidoid-http-server * %% * Copyright (C) 2014 - 2020 Nikolche Mihajlovski and 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. * #L% */ package org.rapidoid.http; import org.rapidoid.RapidoidThing; import org.rapidoid.annotation.Authors; import org.rapidoid.annotation.Since; @Authors("Nikolche Mihajlovski") @Since("5.1.0") public class Headers extends RapidoidThing { public static final String CONTENT_TYPE = "Content-Type"; public static final String CONTENT_DISPOSITION = "Content-Disposition"; public static final String CACHE_CONTROL = "Cache-Control"; public static final String LOCATION = "Location"; public static final String REFERER = "Referer"; public static final String USER_AGENT = "User-Agent"; public static final String X_FORWARDED_FOR = "X-Forwarded-For"; public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto"; public static final String X_FORWARDED_HOST = "X-Forwarded-Host"; public static final String ACCEPT_CHARSET = "Accept-Charset"; public static final String ACCEPT_ENCODING = "Accept-Encoding"; public static final String ACCEPT_DATETIME = "Accept-Datetime"; public static final String AUTHORIZATION = "Authorization"; public static final String CONNECTION = "Connection"; public static final String EXPECT = "Expect"; public static final String FORWARDED = "Forwarded"; public static final String FROM = "From"; public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; public static final String IF_RANGE = "If-Range"; public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; public static final String VIA = "Via"; public static final String WARNING = "Warning"; public static final String FRONT_END_HTTPS = "Front-End-Https"; public static final String CF_CONNECTING_IP = "CF-Connecting-IP"; public static final String CF_IPCOUNTRY = "CF-Ipcountry"; public static final String CF_VISITOR = "Cf-Visitor"; public static final String CF_RAY = "CF-Ray"; }
apache-2.0
apache/incubator-tinkerpop
gremlin-test/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/OrderabilityTest.java
23585
/* * 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.tinkerpop.gremlin.process.traversal.step; import org.apache.tinkerpop.gremlin.FeatureRequirement; import org.apache.tinkerpop.gremlin.LoadGraphWith; import org.apache.tinkerpop.gremlin.process.AbstractGremlinProcessTest; import org.apache.tinkerpop.gremlin.process.GremlinProcessRunner; import org.apache.tinkerpop.gremlin.process.traversal.Order; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Test; import org.junit.runner.RunWith; import static org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData.MODERN; import static org.apache.tinkerpop.gremlin.structure.Graph.Features.EdgeFeatures; import static org.apache.tinkerpop.gremlin.structure.Graph.Features.GraphFeatures; import static org.apache.tinkerpop.gremlin.structure.Graph.Features.VertexFeatures; import static org.apache.tinkerpop.gremlin.structure.Graph.Features.VertexPropertyFeatures; import java.util.Arrays; import java.util.Date; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; @RunWith(GremlinProcessRunner.class) public abstract class OrderabilityTest extends AbstractGremlinProcessTest { private interface Constants { UUID uuid = UUID.randomUUID(); Date date = new Date(); List list1 = Arrays.asList(1, 2, 3); List list2 = Arrays.asList(1, 2, 3, 4); Set set1 = new LinkedHashSet(list1); Set set2 = new LinkedHashSet(list2); Map map1 = new LinkedHashMap() {{ put(1, 11); put(2, 22); put(3, false); put(4, 44); }}; Map map2 = new LinkedHashMap() {{ put(1, 11); put(2, 22); put(3, 33); }}; Object[] unordered = { map2, 1, map1, "foo", null, list1, date, set1, list2, true, uuid, "bar", 2.0, false, set2 }; } public abstract Traversal<Vertex, Object> get_g_V_values_order(); public abstract Traversal<Vertex, ? extends Property> get_g_V_properties_order(); public abstract Traversal<Edge, Object> get_g_E_properties_order_value(); public abstract Traversal<Edge, Object> get_g_E_properties_order_byXdescX_value(); public abstract Traversal<Object, Object> get_g_inject_order(); // order asc by vertex: v[3], v[5] public abstract Traversal<Vertex, Vertex> get_g_V_out_out_order_byXascX(); // order asc by vertex in path: v[3], v[5] public abstract Traversal<Vertex, Vertex> get_g_V_out_out_asXheadX_path_order_byXascX_selectXheadX(); // order asc by edge: e[10], v[e11] public abstract Traversal<Vertex, Edge> get_g_V_out_outE_order_byXascX(); // order asc by edge in path: e[10], e[11] public abstract Traversal<Vertex, Edge> get_g_V_out_outE_asXheadX_path_order_byXascX_selectXheadX(); // order asc by vertex and then vertex property id in path. public abstract Traversal<Vertex, Object> get_g_V_out_out_properties_asXheadX_path_order_byXascX_selectXheadX_value(); // order asc by vertex and then vertex property value in path. public abstract Traversal<Vertex, Object> get_g_V_out_out_values_asXheadX_path_order_byXascX_selectXheadX(); // order desc by vertex: v[3], v[5] public abstract Traversal<Vertex, Vertex> get_g_V_out_out_order_byXdescX(); // order desc by vertex in path: v[3], v[5] public abstract Traversal<Vertex, Vertex> get_g_V_out_out_asXheadX_path_order_byXdescX_selectXheadX(); // order desc by edge: e[10], v[e11] public abstract Traversal<Vertex, Edge> get_g_V_out_outE_order_byXdescX(); // order desc by edge in path: e[10], e[11] public abstract Traversal<Vertex, Edge> get_g_V_out_outE_asXheadX_path_order_byXdescX_selectXheadX(); // order desc by vertex and then vertex property id in path. public abstract Traversal<Vertex, Object> get_g_V_out_out_properties_asXheadX_path_order_byXdescX_selectXheadX_value(); // order desc by vertex and then vertex property value in path. public abstract Traversal<Vertex, Object> get_g_V_out_out_values_asXheadX_path_order_byXdescX_selectXheadX(); /** * Order by property value (mixed types). */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) public void g_V_values_order() { final Traversal<Vertex, Object> traversal = get_g_V_values_order(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( 27, 29, 32, 35, "java", "java", "josh", "lop", "marko", "peter", "ripple", "vadas" ), traversal); } /** * Order by vertex property (orders by id). */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_properties_order() { final Traversal traversal = get_g_V_properties_order(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToVertexProperty("marko", "name", "marko"), // vpid = 0 convertToVertexProperty("marko", "age", 29), // vpid = 1 convertToVertexProperty("vadas", "name", "vadas"), // vpid = 2 convertToVertexProperty("vadas", "age", 27), // vpid = 3 convertToVertexProperty("lop", "name", "lop"), // vpid = 4 convertToVertexProperty("lop", "lang", "java"), // vpid = 5 convertToVertexProperty("josh", "name", "josh"), // vpid = 6 convertToVertexProperty("josh", "age", 32), // vpid = 7 convertToVertexProperty("ripple", "name", "ripple"), // vpid = 8 convertToVertexProperty("ripple", "lang", "java"), // vpid = 9 convertToVertexProperty("peter", "name", "peter"), // vpid = 10 convertToVertexProperty("peter", "age", 35) // vpid = 11 ), traversal); } /** * Order by edge property (orders by key, then value). */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = EdgeFeatures.class, feature = EdgeFeatures.FEATURE_ADD_PROPERTY) public void g_E_properties_order_value() { { // add some more edge properties final AtomicInteger a = new AtomicInteger(); g.E().forEachRemaining(e -> e.property("a", a.getAndIncrement())); } final Traversal asc = get_g_E_properties_order_value(); printTraversalForm(asc); checkOrderedResults(Arrays.asList( 0, 1, 2, 3, 4, 5, 0.2, 0.4, 0.4, 0.5, 1.0, 1.0 ), asc); final Traversal desc = get_g_E_properties_order_byXdescX_value(); printTraversalForm(desc); checkOrderedResults(Arrays.asList( 1.0, 1.0, 0.5, 0.4, 0.4, 0.2, 5, 4, 3, 2, 1, 0 ), desc); } /** * Mixed type values including list, set, map, uuid, date, boolean, numeric, string, null. */ @Test @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) public void g_inject_order() { final Traversal traversal = get_g_inject_order(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( null, false, true, 1, 2.0, Constants.date, "bar", "foo", Constants.uuid, Constants.set1, Constants.set2, Constants.list1, Constants.list2, Constants.map1, Constants.map2 ), traversal); } /** * More mixed type values including a Java Object (unknown type). */ @Test @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) public void g_inject_order_with_unknown_type() { final Object unknown = new Object(); final Object[] unordered = new Object[Constants.unordered.length+1]; unordered[0] = unknown; System.arraycopy(Constants.unordered, 0, unordered, 1, Constants.unordered.length); final Traversal traversal = g.inject(unordered).order(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( null, false, true, 1, 2.0, Constants.date, "bar", "foo", Constants.uuid, Constants.set1, Constants.set2, Constants.list1, Constants.list2, Constants.map1, Constants.map2, unknown ), traversal); } /** * Order asc by vertex: v[3], v[5] */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexFeatures.class, feature = VertexFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_out_order_byXascX() { final Traversal traversal = get_g_V_out_out_order_byXascX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToVertex("lop"), // vid = 3 convertToVertex("ripple") // vid = 5 ), traversal); } /** * Order asc by vertex in path: v[3], v[5] */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexFeatures.class, feature = VertexFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_out_asXheadX_path_order_byXascX_selectXheadX() { final Traversal traversal = get_g_V_out_out_asXheadX_path_order_byXascX_selectXheadX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToVertex("lop"), // vid = 3 convertToVertex("ripple") // vid = 5 ), traversal); } /** * Order asc by edge: e[10], v[e11] */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = EdgeFeatures.class, feature = EdgeFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_outE_order_byXascX() { final Traversal traversal = get_g_V_out_outE_order_byXascX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToEdge("josh", "created", "ripple"), // eid = 10 convertToEdge("josh", "created", "lop") // eid = 11 ), traversal); } /** * Order asc by edge in path: e[10], e[11] */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = EdgeFeatures.class, feature = EdgeFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_outE_asXheadX_path_order_byXascX_selectXheadX() { final Traversal traversal = get_g_V_out_outE_asXheadX_path_order_byXascX_selectXheadX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToEdge("josh", "created", "ripple"), // eid = 10 convertToEdge("josh", "created", "lop") // eid = 11 ), traversal); } /** * Order asc by vertex and then vertex property id in path. */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexFeatures.class, feature = VertexFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_out_properties_asXheadX_path_order_byXascX_selectXheadX_value() { final Traversal traversal = get_g_V_out_out_properties_asXheadX_path_order_byXascX_selectXheadX_value(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( "lop", // vid = 3, vpid = 4 "java", // vid = 3, vpid = 5 "ripple", // vid = 5, vpid = 8 "java" // vid = 5, vpid = 9 ), traversal); } /** * Order asc by vertex and then vertex property value in path. */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexFeatures.class, feature = VertexFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_out_values_asXheadX_path_order_byXascX_selectXheadX() { final Traversal traversal = get_g_V_out_out_values_asXheadX_path_order_byXascX_selectXheadX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( "java", // vid = 3, val = "java" "lop", // vid = 3, val = "lop" "java", // vid = 5, val = "java" "ripple" // vid = 5, val = "ripple" ), traversal); } /** * Order desc by vertex: v[5], v[3] */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexFeatures.class, feature = VertexFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_out_order_byXdescX() { final Traversal traversal = get_g_V_out_out_order_byXdescX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToVertex("ripple"), // vid = 5 convertToVertex("lop") // vid = 3 ), traversal); } /** * Order desc by vertex in path: v[5], v[3] */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexFeatures.class, feature = VertexFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_out_asXheadX_path_order_byXdescX_selectXheadX() { final Traversal traversal = get_g_V_out_out_asXheadX_path_order_byXdescX_selectXheadX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToVertex("ripple"), // vid = 5 convertToVertex("lop") // vid = 3 ), traversal); } /** * Order desc by edge: e[11], v[e10] */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = EdgeFeatures.class, feature = EdgeFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_outE_order_byXdescX() { final Traversal traversal = get_g_V_out_outE_order_byXdescX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToEdge("josh", "created", "lop"), // eid = 11 convertToEdge("josh", "created", "ripple") // eid = 10 ), traversal); } /** * Order desc by edge in path: e[11], e[10] */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = EdgeFeatures.class, feature = EdgeFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_outE_asXheadX_path_order_byXdescX_selectXheadX() { final Traversal traversal = get_g_V_out_outE_asXheadX_path_order_byXdescX_selectXheadX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( convertToEdge("josh", "created", "lop"), // eid = 11 convertToEdge("josh", "created", "ripple") // eid = 10 ), traversal); } /** * Order desc by vertex and then vertex property id in path. */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexFeatures.class, feature = VertexFeatures.FEATURE_USER_SUPPLIED_IDS) @FeatureRequirement(featureClass = VertexPropertyFeatures.class, feature = VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_out_properties_asXheadX_path_order_byXdescX_selectXheadX_value() { final Traversal traversal = get_g_V_out_out_properties_asXheadX_path_order_byXdescX_selectXheadX_value(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( "java", // vid = 5, vpid = 9 "ripple", // vid = 5, vpid = 8 "java", // vid = 3, vpid = 5 "lop" // vid = 3, vpid = 4 ), traversal); } /** * Order desc by vertex and then vertex property value in path. */ @Test @LoadGraphWith(MODERN) @FeatureRequirement(featureClass = GraphFeatures.class, feature = GraphFeatures.FEATURE_ORDERABILITY_SEMANTICS) @FeatureRequirement(featureClass = VertexFeatures.class, feature = VertexFeatures.FEATURE_USER_SUPPLIED_IDS) public void g_V_out_out_values_asXheadX_path_order_byXdescX_selectXheadX() { final Traversal traversal = get_g_V_out_out_values_asXheadX_path_order_byXdescX_selectXheadX(); printTraversalForm(traversal); checkOrderedResults(Arrays.asList( "ripple", // vid = 5, val = "ripple" "java", // vid = 5, val = "java" "lop", // vid = 3, val = "lop" "java" // vid = 3, val = "java" ), traversal); } public static class Traversals extends OrderabilityTest implements Constants { @Override public Traversal<Vertex, Object> get_g_V_values_order() { return g.V().values().order(); } @Override public Traversal<Vertex, ? extends Property> get_g_V_properties_order() { return g.V().properties().order(); } @Override public Traversal<Edge, Object> get_g_E_properties_order_value() { return g.E().properties().order().value(); } @Override public Traversal<Edge, Object> get_g_E_properties_order_byXdescX_value() { return g.E().properties().order().by(Order.desc).value(); } @Override public Traversal<Object, Object> get_g_inject_order() { return g.inject(unordered).order(); } // order asc by vertex: v[3], v[5] @Override public Traversal<Vertex, Vertex> get_g_V_out_out_order_byXascX() { return g.V().out().out().order().by(Order.asc); } // order asc by vertex in path: v[3], v[5] @Override public Traversal<Vertex, Vertex> get_g_V_out_out_asXheadX_path_order_byXascX_selectXheadX() { return g.V().out().out().as("head").path().order().by(Order.asc).select("head"); } // order asc by edge: e[10], v[e11] @Override public Traversal<Vertex, Edge> get_g_V_out_outE_order_byXascX() { return g.V().out().outE().order().by(Order.asc); } // order asc by edge in path: e[10], e[11] @Override public Traversal<Vertex, Edge> get_g_V_out_outE_asXheadX_path_order_byXascX_selectXheadX() { return g.V().out().outE().as("head").path().order().by(Order.asc).select("head"); } // order asc by vertex and then vertex property id in path. @Override public Traversal<Vertex, Object> get_g_V_out_out_properties_asXheadX_path_order_byXascX_selectXheadX_value() { return g.V().out().out().properties().as("head").path().order().by(Order.asc).select("head").value(); } // order asc by vertex and then vertex property value in path. @Override public Traversal<Vertex, Object> get_g_V_out_out_values_asXheadX_path_order_byXascX_selectXheadX() { return g.V().out().out().values().as("head").path().order().by(Order.asc).select("head"); } // order desc by vertex: v[5], v[3] @Override public Traversal<Vertex, Vertex> get_g_V_out_out_order_byXdescX() { return g.V().out().out().order().by(Order.desc); } // order desc by vertex in path: v[5], v[3] @Override public Traversal<Vertex, Vertex> get_g_V_out_out_asXheadX_path_order_byXdescX_selectXheadX() { return g.V().out().out().as("head").path().order().by(Order.desc).select("head"); } // order desc by edge: e[11], v[e10] @Override public Traversal<Vertex, Edge> get_g_V_out_outE_order_byXdescX() { return g.V().out().outE().order().by(Order.desc); } // order desc by edge in path: e[11], e[10] @Override public Traversal<Vertex, Edge> get_g_V_out_outE_asXheadX_path_order_byXdescX_selectXheadX() { return g.V().out().outE().as("head").path().order().by(Order.desc).select("head"); } // order desc by vertex and then vertex property id in path. @Override public Traversal<Vertex, Object> get_g_V_out_out_properties_asXheadX_path_order_byXdescX_selectXheadX_value() { return g.V().out().out().properties().as("head").path().order().by(Order.desc).select("head").value(); } // order desc by vertex and then vertex property value in path. @Override public Traversal<Vertex, Object> get_g_V_out_out_values_asXheadX_path_order_byXdescX_selectXheadX() { return g.V().out().out().values().as("head").path().order().by(Order.desc).select("head"); } } }
apache-2.0
allthemdankmemes/Pasta-master
app/src/main/java/com/fabian/pasta/ActivityPositive.java
1173
package com.fabian.pasta; import android.app.Activity; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatDelegate; import android.view.View; import android.widget.Toast; /** * Created by fabian on 28.08.16. */ public class ActivityPositive extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_theme); } public void appThemeNight(View view) { setNightMode(AppCompatDelegate.MODE_NIGHT_YES); Toast.makeText(getApplicationContext(), getString(R.string.nightThemeApplied), Toast.LENGTH_SHORT).show(); } public void appThemeDay(View view) { setNightMode(AppCompatDelegate.MODE_NIGHT_NO); Toast.makeText(getApplicationContext(), getString(R.string.dayThemeApplied), Toast.LENGTH_SHORT).show(); } private void setNightMode(@AppCompatDelegate.NightMode int nightMode) { AppCompatDelegate.setDefaultNightMode(nightMode); if (Build.VERSION.SDK_INT >= 11) { recreate(); } } }
apache-2.0
EvilMcJerkface/crate
server/src/main/java/io/crate/expression/reference/sys/check/node/DiskWatermarkNodesSysCheck.java
2704
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.expression.reference.sys.check.node; import org.elasticsearch.cluster.DiskUsage; import org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.monitor.fs.FsService; abstract class DiskWatermarkNodesSysCheck extends AbstractSysNodeCheck { private final FsService fsService; final DiskThresholdSettings diskThresholdSettings; DiskWatermarkNodesSysCheck(int id, String description, Severity severity, ClusterService clusterService, FsService fsService, Settings settings) { super(id, description, severity); this.fsService = fsService; this.diskThresholdSettings = new DiskThresholdSettings(settings, clusterService.getClusterSettings()); } @Override public boolean isValid() { if (!diskThresholdSettings.isEnabled()) { return true; } DiskUsage leastDiskEstimate = fsService.stats().getLeastDiskEstimate(); if (leastDiskEstimate == null) { // DiskUsage can be unavailable during cluster start-up return true; } return isValid(leastDiskEstimate.getFreeBytes(), leastDiskEstimate.getTotalBytes()); } protected abstract boolean isValid(long free, long total); static double getFreeDiskAsPercentage(long free, long total) { if (total == 0) { return 100.0; } return 100.0 * ((double) free / total); } }
apache-2.0
googleapis/java-dialogflow
google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2beta1/SessionsClient.java
18961
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.cloud.dialogflow.v2beta1; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.rpc.BidiStreamingCallable; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.dialogflow.v2beta1.stub.SessionsStub; import com.google.cloud.dialogflow.v2beta1.stub.SessionsStubSettings; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: A service used for session interactions. * * <p>For more information, see the [API interactions * guide](https://cloud.google.com/dialogflow/docs/api-overview). * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * try (SessionsClient sessionsClient = SessionsClient.create()) { * SessionName session = SessionName.ofProjectSessionName("[PROJECT]", "[SESSION]"); * QueryInput queryInput = QueryInput.newBuilder().build(); * DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput); * } * }</pre> * * <p>Note: close() needs to be called on the SessionsClient object to clean up resources such as * threads. In the example above, try-with-resources is used, which automatically calls close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li>A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li>A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li>A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of SessionsSettings to create(). * For example: * * <p>To customize credentials: * * <pre>{@code * SessionsSettings sessionsSettings = * SessionsSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * SessionsClient sessionsClient = SessionsClient.create(sessionsSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * SessionsSettings sessionsSettings = * SessionsSettings.newBuilder().setEndpoint(myEndpoint).build(); * SessionsClient sessionsClient = SessionsClient.create(sessionsSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @BetaApi @Generated("by gapic-generator-java") public class SessionsClient implements BackgroundResource { private final SessionsSettings settings; private final SessionsStub stub; /** Constructs an instance of SessionsClient with default settings. */ public static final SessionsClient create() throws IOException { return create(SessionsSettings.newBuilder().build()); } /** * Constructs an instance of SessionsClient, using the given settings. The channels are created * based on the settings passed in, or defaults for any settings that are not set. */ public static final SessionsClient create(SessionsSettings settings) throws IOException { return new SessionsClient(settings); } /** * Constructs an instance of SessionsClient, using the given stub for making calls. This is for * advanced usage - prefer using create(SessionsSettings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final SessionsClient create(SessionsStub stub) { return new SessionsClient(stub); } /** * Constructs an instance of SessionsClient, using the given settings. This is protected so that * it is easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected SessionsClient(SessionsSettings settings) throws IOException { this.settings = settings; this.stub = ((SessionsStubSettings) settings.getStubSettings()).createStub(); } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") protected SessionsClient(SessionsStub stub) { this.settings = null; this.stub = stub; } public final SessionsSettings getSettings() { return settings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public SessionsStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Processes a natural language query and returns structured, actionable data as a result. This * method is not idempotent, because it may cause contexts and session entity types to be updated, * which in turn might affect results of future queries. * * <p>If you might use [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa) or other CCAI * products now or in the future, consider using * [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] instead of * `DetectIntent`. `AnalyzeContent` has additional functionality for Agent Assist and other CCAI * products. * * <p>Note: Always use agent versions for production traffic. See [Versions and * environments](https://cloud.google.com/dialogflow/es/docs/agents-versions). * * <p>Sample code: * * <pre>{@code * try (SessionsClient sessionsClient = SessionsClient.create()) { * SessionName session = SessionName.ofProjectSessionName("[PROJECT]", "[SESSION]"); * QueryInput queryInput = QueryInput.newBuilder().build(); * DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput); * } * }</pre> * * @param session Required. The name of the session this query is sent to. Supported formats: - * `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;, - `projects/&lt;Project * ID&gt;/locations/&lt;Location ID&gt;/agent/sessions/&lt;Session ID&gt;`, - * `projects/&lt;Project ID&gt;/agent/environments/&lt;Environment ID&gt;/users/&lt;User * ID&gt;/sessions/&lt;Session ID&gt;`, - `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/agent/environments/&lt;Environment ID&gt;/users/&lt;User ID&gt;/sessions/&lt;Session * ID&gt;`, * <p>If `Location ID` is not specified we assume default 'us' location. If `Environment ID` * is not specified, we assume default 'draft' environment (`Environment ID` might be referred * to as environment name at some places). If `User ID` is not specified, we are using "-". * It's up to the API caller to choose an appropriate `Session ID` and `User Id`. They can be * a random number or some type of user and session identifiers (preferably hashed). The * length of the `Session ID` and `User ID` must not exceed 36 characters. For more * information, see the [API interactions * guide](https://cloud.google.com/dialogflow/docs/api-overview). * <p>Note: Always use agent versions for production traffic. See [Versions and * environments](https://cloud.google.com/dialogflow/es/docs/agents-versions). * @param queryInput Required. The input specification. It can be set to: * <p>1. an audio config which instructs the speech recognizer how to process the speech * audio, * <p>2. a conversational query in the form of text, or * <p>3. an event that specifies which intent to trigger. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final DetectIntentResponse detectIntent(SessionName session, QueryInput queryInput) { DetectIntentRequest request = DetectIntentRequest.newBuilder() .setSession(session == null ? null : session.toString()) .setQueryInput(queryInput) .build(); return detectIntent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Processes a natural language query and returns structured, actionable data as a result. This * method is not idempotent, because it may cause contexts and session entity types to be updated, * which in turn might affect results of future queries. * * <p>If you might use [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa) or other CCAI * products now or in the future, consider using * [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] instead of * `DetectIntent`. `AnalyzeContent` has additional functionality for Agent Assist and other CCAI * products. * * <p>Note: Always use agent versions for production traffic. See [Versions and * environments](https://cloud.google.com/dialogflow/es/docs/agents-versions). * * <p>Sample code: * * <pre>{@code * try (SessionsClient sessionsClient = SessionsClient.create()) { * String session = SessionName.ofProjectSessionName("[PROJECT]", "[SESSION]").toString(); * QueryInput queryInput = QueryInput.newBuilder().build(); * DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput); * } * }</pre> * * @param session Required. The name of the session this query is sent to. Supported formats: - * `projects/&lt;Project ID&gt;/agent/sessions/&lt;Session ID&gt;, - `projects/&lt;Project * ID&gt;/locations/&lt;Location ID&gt;/agent/sessions/&lt;Session ID&gt;`, - * `projects/&lt;Project ID&gt;/agent/environments/&lt;Environment ID&gt;/users/&lt;User * ID&gt;/sessions/&lt;Session ID&gt;`, - `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/agent/environments/&lt;Environment ID&gt;/users/&lt;User ID&gt;/sessions/&lt;Session * ID&gt;`, * <p>If `Location ID` is not specified we assume default 'us' location. If `Environment ID` * is not specified, we assume default 'draft' environment (`Environment ID` might be referred * to as environment name at some places). If `User ID` is not specified, we are using "-". * It's up to the API caller to choose an appropriate `Session ID` and `User Id`. They can be * a random number or some type of user and session identifiers (preferably hashed). The * length of the `Session ID` and `User ID` must not exceed 36 characters. For more * information, see the [API interactions * guide](https://cloud.google.com/dialogflow/docs/api-overview). * <p>Note: Always use agent versions for production traffic. See [Versions and * environments](https://cloud.google.com/dialogflow/es/docs/agents-versions). * @param queryInput Required. The input specification. It can be set to: * <p>1. an audio config which instructs the speech recognizer how to process the speech * audio, * <p>2. a conversational query in the form of text, or * <p>3. an event that specifies which intent to trigger. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final DetectIntentResponse detectIntent(String session, QueryInput queryInput) { DetectIntentRequest request = DetectIntentRequest.newBuilder().setSession(session).setQueryInput(queryInput).build(); return detectIntent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Processes a natural language query and returns structured, actionable data as a result. This * method is not idempotent, because it may cause contexts and session entity types to be updated, * which in turn might affect results of future queries. * * <p>If you might use [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa) or other CCAI * products now or in the future, consider using * [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] instead of * `DetectIntent`. `AnalyzeContent` has additional functionality for Agent Assist and other CCAI * products. * * <p>Note: Always use agent versions for production traffic. See [Versions and * environments](https://cloud.google.com/dialogflow/es/docs/agents-versions). * * <p>Sample code: * * <pre>{@code * try (SessionsClient sessionsClient = SessionsClient.create()) { * DetectIntentRequest request = * DetectIntentRequest.newBuilder() * .setSession(SessionName.ofProjectSessionName("[PROJECT]", "[SESSION]").toString()) * .setQueryParams(QueryParameters.newBuilder().build()) * .setQueryInput(QueryInput.newBuilder().build()) * .setOutputAudioConfig(OutputAudioConfig.newBuilder().build()) * .setOutputAudioConfigMask(FieldMask.newBuilder().build()) * .setInputAudio(ByteString.EMPTY) * .build(); * DetectIntentResponse response = sessionsClient.detectIntent(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final DetectIntentResponse detectIntent(DetectIntentRequest request) { return detectIntentCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Processes a natural language query and returns structured, actionable data as a result. This * method is not idempotent, because it may cause contexts and session entity types to be updated, * which in turn might affect results of future queries. * * <p>If you might use [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa) or other CCAI * products now or in the future, consider using * [AnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.AnalyzeContent] instead of * `DetectIntent`. `AnalyzeContent` has additional functionality for Agent Assist and other CCAI * products. * * <p>Note: Always use agent versions for production traffic. See [Versions and * environments](https://cloud.google.com/dialogflow/es/docs/agents-versions). * * <p>Sample code: * * <pre>{@code * try (SessionsClient sessionsClient = SessionsClient.create()) { * DetectIntentRequest request = * DetectIntentRequest.newBuilder() * .setSession(SessionName.ofProjectSessionName("[PROJECT]", "[SESSION]").toString()) * .setQueryParams(QueryParameters.newBuilder().build()) * .setQueryInput(QueryInput.newBuilder().build()) * .setOutputAudioConfig(OutputAudioConfig.newBuilder().build()) * .setOutputAudioConfigMask(FieldMask.newBuilder().build()) * .setInputAudio(ByteString.EMPTY) * .build(); * ApiFuture<DetectIntentResponse> future = * sessionsClient.detectIntentCallable().futureCall(request); * // Do something. * DetectIntentResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<DetectIntentRequest, DetectIntentResponse> detectIntentCallable() { return stub.detectIntentCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Processes a natural language query in audio format in a streaming fashion and returns * structured, actionable data as a result. This method is only available via the gRPC API (not * REST). * * <p>If you might use [Agent Assist](https://cloud.google.com/dialogflow/docs/#aa) or other CCAI * products now or in the future, consider using * [StreamingAnalyzeContent][google.cloud.dialogflow.v2beta1.Participants.StreamingAnalyzeContent] * instead of `StreamingDetectIntent`. `StreamingAnalyzeContent` has additional functionality for * Agent Assist and other CCAI products. * * <p>Note: Always use agent versions for production traffic. See [Versions and * environments](https://cloud.google.com/dialogflow/es/docs/agents-versions). * * <p>Sample code: * * <pre>{@code * try (SessionsClient sessionsClient = SessionsClient.create()) { * BidiStream<StreamingDetectIntentRequest, StreamingDetectIntentResponse> bidiStream = * sessionsClient.streamingDetectIntentCallable().call(); * StreamingDetectIntentRequest request = * StreamingDetectIntentRequest.newBuilder() * .setSession(SessionName.ofProjectSessionName("[PROJECT]", "[SESSION]").toString()) * .setQueryParams(QueryParameters.newBuilder().build()) * .setQueryInput(QueryInput.newBuilder().build()) * .setSingleUtterance(true) * .setOutputAudioConfig(OutputAudioConfig.newBuilder().build()) * .setOutputAudioConfigMask(FieldMask.newBuilder().build()) * .setInputAudio(ByteString.EMPTY) * .build(); * bidiStream.send(request); * for (StreamingDetectIntentResponse response : bidiStream) { * // Do something when a response is received. * } * } * }</pre> */ public final BidiStreamingCallable<StreamingDetectIntentRequest, StreamingDetectIntentResponse> streamingDetectIntentCallable() { return stub.streamingDetectIntentCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } }
apache-2.0
coderplay/supersonic-java
src/main/java/com/alibaba/supersonic/utils/exception/FailureOrs.java
2576
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.supersonic.utils.exception; import com.alibaba.supersonic.base.exception.SupersonicException; /** * Propagators to support 'exception-like' error propagation. Allow to attach * exception information to any object passed by value. Intended themselves to * be passed by value. * * Usage pattern: * * class Data { ... }; * * FailureOr<Data> GetSomeData() { * if (error detected) { * return Failure(new Exception(...)); // Abrupt completion. * } else { * Data data = ...; * return Success(data); // Normal completion. * } * } * * FailureOr<Data> result = GetSomeData(); * if (result.is_failure()) { // Catch. * HandleException(result.exception()); * } else { * HandleResult(result.get()); * } * * Propagation: * FailureOr<ManipulatedData> ManipulateSomeData() { * FailureOr<Data> data = GetSomeData(); // some function that can fail. * if (data.is_failure()) { * return Failure(data.release_exception()); * } * ... * * @author Min Zhou (coderplay@gmail.com) * */ public class FailureOrs { public static <RESULT> FailureOr<RESULT> failure(SupersonicException exception) { return new FailureOr<RESULT>(new FailurePropagator(exception)); } public static <RESULT> FailureOr<RESULT> success(RESULT result) { return new FailureOr<RESULT>(new ReferencePropagator<RESULT>(result)); } public static FailureOrVoid voidFailure(SupersonicException exception) { return new FailureOrVoid(new FailurePropagator(exception)); } /** * Creates an indication of success, with no result. Can be implicitly converted * to {@link FailureOrVoid}. * @return */ public static FailureOrVoid voidSuccess() { return new FailureOrVoid(); } }
apache-2.0
AlexanderYastrebov/catwatch
catwatch-backend/src/test/java/org/zalando/catwatch/backend/util/ContributorStatsTest.java
3641
package org.zalando.catwatch.backend.util; import org.junit.Test; import org.zalando.catwatch.backend.model.Contributor; import org.zalando.catwatch.backend.repo.builder.ContributorBuilder; import static org.zalando.catwatch.backend.repo.builder.BuilderUtil.freshId; import java.util.LinkedList; import java.util.List; import java.util.Date; import static org.junit.Assert.*; /** * Created by nwang on 13/08/15. */ public class ContributorStatsTest{ @Test public void checkContributorStats(){ // Generate a list of contributors LinkedList<Contributor> contributors = new LinkedList<>(); String gitHub = "https://github.com/"; contributors.add(new ContributorBuilder().name("elephant").url(gitHub+"elephant").organizationId(freshId()) .organizationName("bob").snapshotDate(new Date(0)) .orgCommits(40).persCommits(30).orgProjects(20).persProjects(10).create()); contributors.add(new ContributorBuilder().name("elephant").url(gitHub+"elephant").organizationId(freshId()) .organizationName("bob").snapshotDate(new Date(1)) .orgCommits(40).persCommits(30).orgProjects(20).persProjects(10).create()); contributors.add(new ContributorBuilder().name("elephant").url(gitHub + "elephant").organizationId(freshId()) .organizationName("bob").snapshotDate(new Date(2)) .orgCommits(40).persCommits(30).orgProjects(20).persProjects(10).create()); contributors.add(new ContributorBuilder().name("snake").url(gitHub + "snake").organizationId(freshId()) .organizationName("bob").snapshotDate(new Date(0)) .orgCommits(40).persCommits(30).orgProjects(20).persProjects(10).create()); contributors.add(new ContributorBuilder().name("snake").url(gitHub + "snake").organizationId(freshId()) .organizationName("bob").snapshotDate(new Date(2)) .orgCommits(40).persCommits(30).orgProjects(20).persProjects(10).create()); contributors.add(new ContributorBuilder().name("snake").url(gitHub + "snake").organizationId(freshId()) .organizationName("bob").snapshotDate(new Date(3)) .orgCommits(40).persCommits(30).orgProjects(20).persProjects(10).create()); // Construct a ContributorStats object List<ContributorStats> stats = ContributorStats.buildStats(contributors); assertEquals(2, stats.size()); assertEquals("snake", stats.get(0).getName()); assertEquals("bob", stats.get(0).getOrganizationName().get(0)); assertArrayEquals(new Integer[] {40, 40, 40}, stats.get(0).getOrganizationalCommitsCounts().toArray()); assertArrayEquals(new Integer[] {30, 30, 30}, stats.get(0).getPersonalCommitsCounts().toArray()); assertArrayEquals(new Integer[] {20, 20, 20}, stats.get(0).getOrganizationalProjectsCounts().toArray()); assertArrayEquals(new Integer[] {10, 10, 10}, stats.get(0).getPersonalProjectsCounts().toArray()); stats.get(0).getSnapshotDates().toArray(); } @Test public void checkLoginId() { Contributor c = new ContributorBuilder().name("elephant").organizationId(freshId()) .organizationName("bob").snapshotDate(new Date(0)) .orgCommits(40).persCommits(30).orgProjects(20).persProjects(10).create(); c.setUrl(null); assertEquals("", c.getLoginId()); c.setUrl("notGoodStart"); assertEquals("", c.getLoginId()); c.setUrl("https://github.com/zalando"); assertEquals("zalando", c.getLoginId()); } }
apache-2.0
igd-geo/osgi-util
src/main/java/de/fhg/igd/osgi/util/MultiServiceTracker.java
3022
// Fraunhofer Institute for Computer Graphics Research (IGD) // Department Spatial Information Management (GEO) // // Copyright (c) 2008-2014 Fraunhofer IGD // // This file is part of osgi-util. // // 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 de.fhg.igd.osgi.util; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.osgi.framework.ServiceReference; /** * <p>Title: MultiServiceTracker</p> * <p>Description: Tracks service instances</p> * @author Simon Templer * @param <T> the service type */ public class MultiServiceTracker<T> extends ServiceTracker<T> { private final Map<ServiceReference<T>, T> services = new HashMap<ServiceReference<T>, T>(); private final Set<MultiServiceListener<T>> listeners = new HashSet<MultiServiceListener<T>>(); /** * Constructor * * @param serviceClass the service type to track */ public MultiServiceTracker(Class<T> serviceClass) { super(serviceClass); } /** * @see ServiceTracker#deregister(ServiceReference) */ @Override protected void deregister(ServiceReference<T> service) { T serviceInstance; synchronized (services) { serviceInstance = services.get(service); if (serviceInstance == null) { return; } else { services.remove(service); } } for (MultiServiceListener<T> listener : listeners) { listener.serviceRemoved(serviceInstance); } } /** * @see ServiceTracker#register(ServiceReference) */ @Override protected void register(ServiceReference<T> service) { T serviceInstance = getContext().getService(service); if (serviceInstance != null) { synchronized (services) { services.put(service, serviceInstance); } for (MultiServiceListener<T> listener : listeners) { listener.serviceAdded(serviceInstance); } } } /** * Get the currently available service instances * * @return the set of currently available service instances */ public Set<T> getServices() { Set<T> result; synchronized (services) { result = new HashSet<T>(services.values()); } return result; } /** * Adds a {@link MultiServiceListener} * * @param listener the listener to add */ public void addListener(MultiServiceListener<T> listener) { listeners.add(listener); } /** * Removes a {@link MultiServiceListener} * * @param listener the listener to remove */ public void removeListener(MultiServiceListener<T> listener) { listeners.remove(listener); } }
apache-2.0
pennatula/reactome2gpml-converter
src/org/gk/gpml/CLIConverter.java
7540
/* * This command line interface is used to convert a pathway that has a diagram inside the reactome * database to GPML format. */ package org.gk.gpml; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.gk.model.GKInstance; import org.gk.model.ReactomeJavaConstants; import org.gk.persistence.MySQLAdaptor; import org.gk.schema.SchemaAttribute; import org.gk.schema.SchemaClass; import org.reactome.convert.common.AbstractConverterFromReactome; public class CLIConverter { public static void main(String[] args) throws Exception { if (args.length < 6) { // printUsage(); System.err .println("Please provide the following parameters in order: dbhost dbName dbUser dbPwd dbPort outputDir"); System.exit(1); } MySQLAdaptor adaptor = new MySQLAdaptor(args[0], args[1], args[2], args[3], Integer.parseInt(args[4])); File dir = new File(args[5]); dir.mkdirs(); CLIConverter converter = new CLIConverter(adaptor); /* * Boolean true to save ATXML files */ converter.convertReactomeToGPMLByID((long) 69620, dir, false); // converter.convertReactomeToGPMLByID((long) 73857, dir, false); // converter.convertReactomeToGPMLByID((long) 2032785, dir, false); // converter.dumpHumanPathwayDiagrams(dir, false); // converter.convertPlantPathwayDiagrams(dir, false); // converter.getSpeciesDbID(); } private static void printUsage() throws Exception { System.out .println("Usage: java org.gk.gpml.CLIConverter dbhost dbName user pwd port DB_ID [outputfile]"); System.out.println(); System.out .println("DB_ID is the Reactome ID of a pathway that has a diagram inside the database."); } private final MySQLAdaptor adaptor; private final ReactometoGPML2013 r2g3Converter; private final Map<Long, String> notRenderable; private final Map<Long, String> Renderable; private CLIConverter(MySQLAdaptor adaptor) { this(adaptor, new ReactometoGPML2013()); } private CLIConverter(MySQLAdaptor adaptor, ReactometoGPML2013 r2g3Converter) { notRenderable = new HashMap<Long, String>(); Renderable = new HashMap<Long, String>(); this.adaptor = adaptor; this.r2g3Converter = r2g3Converter; this.r2g3Converter.setMySQLAdaptor(adaptor); } private void convertPlantPathwayDiagrams(File dir, boolean saveatxml) { Collection<?> diagrams; try { diagrams = adaptor .fetchInstancesByClass(ReactomeJavaConstants.PathwayDiagram); SchemaClass cls = adaptor.fetchSchema().getClassByName( ReactomeJavaConstants.PathwayDiagram); SchemaAttribute att = cls .getAttribute(ReactomeJavaConstants.representedPathway); adaptor.loadInstanceAttributeValues(diagrams, att); // Group all human pathways for (Object name : diagrams) { GKInstance diagram = (GKInstance) name; GKInstance pathway = (GKInstance) diagram .getAttributeValue(ReactomeJavaConstants.representedPathway); GKInstance species = (GKInstance) pathway .getAttributeValue(ReactomeJavaConstants.species); if (species == null) { continue; } else { try { String fileName = AbstractConverterFromReactome .getFileName(pathway); if (saveatxml) { File atxmlfile = new File(dir, fileName + ".atxml"); atxmlfile.createNewFile(); r2g3Converter.queryATXML(pathway, atxmlfile); } File gpmlfile = new File(dir, fileName + ".gpml"); gpmlfile.createNewFile(); convertReactomeToGPML(pathway, gpmlfile); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } private void convertReactomeToGPML(GKInstance pathway, File gpmlfilename) { Long dbID = pathway.getDBID(); System.out.println("converting pathway #" + dbID + " " + pathway.getDisplayName() + "..."); if (!r2g3Converter.convertPathway(pathway, gpmlfilename)) { notRenderable.put(dbID, pathway.getDisplayName()); } else { Renderable.put(dbID, pathway.getDisplayName()); } System.out.println("Not Rendered " + notRenderable); System.out.println("Rendered " + Renderable); } /** * Convert Reactome pathways using their IDs * * @param dbID * Stable ID of the pathway * @param dir * Directory to save converted gpml file * @param saveatxml * Boolean true if atxml files should be saved as well */ public void convertReactomeToGPMLByID(Long dbID, File dir, Boolean saveatxml) { GKInstance pathway; try { pathway = adaptor.fetchInstance(dbID); String fileName = AbstractConverterFromReactome .getFileName(pathway); if (saveatxml) { File atxmlfile = new File(dir, fileName + ".atxml"); atxmlfile.createNewFile(); r2g3Converter.queryATXML(pathway, atxmlfile); } File gpmlfile = new File(dir, fileName + ".gpml"); gpmlfile.createNewFile(); convertReactomeToGPML(pathway, gpmlfile); } catch (Exception e) { e.printStackTrace(); } } public void dumpHumanPathwayDiagrams(File dir, Boolean saveatxml) { notRenderable.clear(); Collection<?> diagrams; try { diagrams = adaptor .fetchInstancesByClass(ReactomeJavaConstants.PathwayDiagram); SchemaClass cls = adaptor.fetchSchema().getClassByName( ReactomeJavaConstants.PathwayDiagram); SchemaAttribute att = cls .getAttribute(ReactomeJavaConstants.representedPathway); adaptor.loadInstanceAttributeValues(diagrams, att); // Group all human pathways for (Object name : diagrams) { GKInstance diagram = (GKInstance) name; GKInstance pathway = (GKInstance) diagram .getAttributeValue(ReactomeJavaConstants.representedPathway); GKInstance species = (GKInstance) pathway .getAttributeValue(ReactomeJavaConstants.species); if (species == null) { continue; } // for (int i = 0; i <= 5; i++) { if (species.getDBID().equals(48887L)) { String fileName = AbstractConverterFromReactome .getFileName(pathway); String gpmlfile = fileName + ".gpml"; File[] listOfFiles = dir.listFiles(); boolean convert = true; for (File listOfFile : listOfFiles) if (gpmlfile.equalsIgnoreCase(listOfFile.getName())) { convert = false; } if (convert) { Long id = pathway.getDBID(); convertReactomeToGPMLByID(id, dir, saveatxml); } } } // } } catch (Exception e) { e.printStackTrace(); } System.out.println("Not rendered" + notRenderable); } /** * This method gets the DB id for the species * * @throws Exception */ public void getSpeciesDbID() { Collection<?> diagrams; try { diagrams = adaptor .fetchInstancesByClass(ReactomeJavaConstants.PathwayDiagram); SchemaClass cls = adaptor.fetchSchema().getClassByName( ReactomeJavaConstants.PathwayDiagram); SchemaAttribute att = cls .getAttribute(ReactomeJavaConstants.representedPathway); adaptor.loadInstanceAttributeValues(diagrams, att); // Group all human pathways for (Object name : diagrams) { GKInstance diagram = (GKInstance) name; GKInstance pathway = (GKInstance) diagram .getAttributeValue(ReactomeJavaConstants.representedPathway); GKInstance species = (GKInstance) pathway .getAttributeValue(ReactomeJavaConstants.species); if (species == null) { continue; } else { System.out.println(species.getDBID() + "\t" + species.getDisplayName()); } } } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
AdaptiveMe/adaptive-arp-api-lib-java
src/main/java/me/adaptive/arp/api/ICapabilitiesSensorAdapter.java
3127
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:carlos@adaptive.me> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:ferran.vila.conesa@gmail.com> * See source code files for contributors. Release: * @version v2.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ package me.adaptive.arp.api; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.io.Serializable; /** ICapabilitiesSensor custom serializer/deserializer. */ public class ICapabilitiesSensorAdapter implements JsonDeserializer<ICapabilitiesSensor>, JsonSerializer<ICapabilitiesSensor>, Serializable { /** Java serialization support. @since 2.2.13 */ private static final long serialVersionUID = 100389874L; @Override public ICapabilitiesSensor deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String value = null; try { value = json.getAsJsonObject().get("value").getAsString(); } catch(Exception ex) { ex.printStackTrace(); } if (value==null) { value = "Unknown"; } return ICapabilitiesSensor.valueOf(ICapabilitiesSensor.class, value); } @Override public JsonElement serialize(ICapabilitiesSensor src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); if (src != null) { jsonObject.add("value", new JsonPrimitive(src.name())); } else { jsonObject.add("value", new JsonPrimitive("Unknown")); } return jsonObject; } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
atsolakid/jena-examples
src/main/java/org/apache/jena/examples/temperature.java
2567
/** * 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.jena.examples; import java.util.List; import com.hp.hpl.jena.query.QueryBuildException; import com.hp.hpl.jena.sparql.expr.ExprEvalException; import com.hp.hpl.jena.sparql.expr.ExprList; import com.hp.hpl.jena.sparql.expr.NodeValue; import com.hp.hpl.jena.sparql.function.FunctionBase; public class temperature extends FunctionBase { public static final double fahrenheitToCelsiusConstant = 5.0 / 9.0 ; public static final double rankineToCelsiusConstant = 5.0 / 9.0 ; public temperature() { super() ; } @Override public void checkBuild(String uri, ExprList args) { if ( args.size() != 1 ) throw new QueryBuildException("Function '"+com.hp.hpl.jena.sparql.util.Utils.className(this)+"' takes one argument") ; } @Override public NodeValue exec(List<NodeValue> args) { if ( args.size() > 1 ) throw new ExprEvalException("replace: Wrong number of arguments: "+args.size()+" : [wanted 1]") ; NodeValue v1 = args.get(0) ; return convert(v1) ; } private static NodeValue convert(NodeValue nv) { if ( nv.getNode().getLiteralDatatype() instanceof TemperatureFahrenheit ) { return NodeValue.makeDouble((nv.getDouble() - 32.0) * fahrenheitToCelsiusConstant); } else if ( nv.getNode().getLiteralDatatype() instanceof TemperatureKelvin ) { return NodeValue.makeDouble(nv.getDouble() - 273.15); } else if ( nv.getNode().getLiteralDatatype() instanceof TemperatureRankine ) { return NodeValue.makeDouble((nv.getDouble() - 491.67) * rankineToCelsiusConstant); } else { return nv ; } } }
apache-2.0
pesse/gwt-jsinterop-threejs
jsinterop-threejs/src/main/java/de/pesse/gwt/jsinterop/threeJs/scenes/Scene.java
510
package de.pesse.gwt.jsinterop.threeJs.scenes; import jsinterop.annotations.JsType; import de.pesse.gwt.jsinterop.threeJs.ThreeJsStatics; import de.pesse.gwt.jsinterop.threeJs.core.Object3D; import de.pesse.gwt.jsinterop.threeJs.materials.Material; @JsType( namespace=ThreeJsStatics.PACKAGE_NAME, isNative=true) public class Scene extends Object3D { public Object background; public Fog fog; public Material overrideMaterial; public boolean autoUpdate; public native Object toJSON( Object meta ); }
apache-2.0
taochaoqiang/druid
extensions-contrib/time-min-max/src/test/java/io/druid/query/aggregation/TimestampAggregationSelectTest.java
5231
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.query.aggregation; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.io.Resources; import io.druid.java.util.common.DateTimes; import io.druid.java.util.common.granularity.Granularities; import io.druid.java.util.common.guava.Sequence; import io.druid.query.Result; import io.druid.query.select.SelectResultValue; import io.druid.segment.ColumnSelectorFactory; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.annotation.Nullable; import java.io.File; import java.sql.Timestamp; import java.util.List; import java.util.zip.ZipFile; @RunWith(Parameterized.class) public class TimestampAggregationSelectTest { private AggregationTestHelper helper; @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private ColumnSelectorFactory selectorFactory; private TestObjectColumnSelector selector; private Timestamp[] values = new Timestamp[10]; @Parameterized.Parameters(name = "{index}: Test for {0}") public static Iterable<Object[]> constructorFeeder() { return Iterables.transform( ImmutableList.of( ImmutableList.of("timeMin", "tmin", DateTimes.of("2011-01-12T01:00:00.000Z").getMillis()), ImmutableList.of("timeMax", "tmax", DateTimes.of("2011-01-31T01:00:00.000Z").getMillis()) ), new Function<List<?>, Object[]>() { @Nullable @Override public Object[] apply(List<?> input) { return input.toArray(); } } ); } private String aggType; private String aggField; private Long expected; public TimestampAggregationSelectTest(String aggType, String aggField, Long expected) { this.aggType = aggType; this.aggField = aggField; this.expected = expected; } @Before public void setup() { helper = AggregationTestHelper.createSelectQueryAggregationTestHelper( new TimestampMinMaxModule().getJacksonModules(), temporaryFolder ); selector = new TestObjectColumnSelector<>(values); selectorFactory = EasyMock.createMock(ColumnSelectorFactory.class); EasyMock.expect(selectorFactory.makeColumnValueSelector("test")).andReturn(selector); EasyMock.replay(selectorFactory); } @Test public void testSimpleDataIngestionAndSelectTest() throws Exception { String recordParser = "{\n" + " \"type\": \"string\",\n" + " \"parseSpec\": {\n" + " \"format\": \"tsv\",\n" + " \"timestampSpec\": {\n" + " \"column\": \"timestamp\",\n" + " \"format\": \"auto\"\n" + " },\n" + " \"dimensionsSpec\": {\n" + " \"dimensions\": [\n" + " \"product\"\n" + " ],\n" + " \"dimensionExclusions\": [],\n" + " \"spatialDimensions\": []\n" + " },\n" + " \"columns\": [\n" + " \"timestamp\",\n" + " \"cat\",\n" + " \"product\",\n" + " \"prefer\",\n" + " \"prefer2\",\n" + " \"pty_country\"\n" + " ]\n" + " }\n" + "}"; String aggregator = "[\n" + " {\n" + " \"type\": \"" + aggType + "\",\n" + " \"name\": \"" + aggField + "\",\n" + " \"fieldName\": \"timestamp\"\n" + " }\n" + "]"; ZipFile zip = new ZipFile(new File(this.getClass().getClassLoader().getResource("druid.sample.tsv.zip").toURI())); Sequence<?> seq = helper.createIndexAndRunQueryOnSegment( zip.getInputStream(zip.getEntry("druid.sample.tsv")), recordParser, aggregator, 0, Granularities.MONTH, 100, Resources.toString(Resources.getResource("select.json"), Charsets.UTF_8) ); Result<SelectResultValue> result = (Result<SelectResultValue>) Iterables.getOnlyElement(seq.toList()); Assert.assertEquals(36, result.getValue().getEvents().size()); Assert.assertEquals(expected, result.getValue().getEvents().get(0).getEvent().get(aggField)); } }
apache-2.0
NiteshKant/ReactiveLab
reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/GeoCommand.java
1974
package io.reactivex.lab.gateway.clients; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.GeoCommand.GeoIP; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.lab.gateway.loadbalancer.DiscoveryAndLoadBalancer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.List; import java.util.Map; public class GeoCommand extends HystrixObservableCommand<GeoIP> { private final List<String> ips; private static final LoadBalancer<HttpClientHolder<ByteBuf, ServerSentEvent>> loadBalancer = DiscoveryAndLoadBalancer.getFactory().forVip("reactive-lab-geo-service"); public GeoCommand(List<String> ips) { super(HystrixCommandGroupKey.Factory.asKey("GeoIP")); this.ips = ips; } @Override protected Observable<GeoIP> run() { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/geo?" + UrlGenerator.generate("ip", ips)); return loadBalancer.choose() .map(holder -> holder.getClient()) .<GeoIP>flatMap(client -> client.submit(request) .flatMap(r -> r.getContent() .map((ServerSentEvent sse) -> GeoIP.fromJson(sse.contentAsString())))) .retry(1); } public static class GeoIP { private final Map<String, Object> data; private GeoIP(Map<String, Object> data) { this.data = data; } public static GeoIP fromJson(String json) { return new GeoIP(SimpleJson.jsonToMap(json)); } } }
apache-2.0
MOBX/Foundation
src/main/java/com/lamfire/utils/Printers.java
663
package com.lamfire.utils; import java.util.Collection; import java.util.Map; public class Printers { public static void print(Object object) { System.out.println(object); } public static void print(Collection<?> col) { for (Object o : col) { print(o); } } public static void print(Map<?, ?> map) { for (Map.Entry<?, ?> e : map.entrySet()) { System.out.println(e.getKey() + "=" + e.getValue()); } } public static void print(Object[] objects) { for (Object obj : objects) { System.out.println(obj); } } }
apache-2.0
krevelen/coala
coala-core/src/main/java/io/coala/random/RandomNumberStreamID.java
1526
/* $Id$ * $URL: https://dev.almende.com/svn/abms/coala-common/src/main/java/com/almende/coala/random/RandomNumberStreamID.java $ * * Part of the EU project Adapt4EE, see http://www.adapt4ee.eu/ * * @license * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * Copyright (c) 2010-2014 Almende B.V. */ package io.coala.random; import io.coala.name.AbstractIdentifier; import javax.inject.Inject; /** * {@link RandomNumberStreamID} * * @version $Revision: 296 $ * @author <a href="mailto:Rick@almende.org">Rick</a> * */ public class RandomNumberStreamID extends AbstractIdentifier<String> { /** */ private static final long serialVersionUID = 1L; /** * {@link AbstractIdentifier} zero-arg bean constructor */ protected RandomNumberStreamID() { // } /** * {@link AbstractIdentifier} constructor * * @param value the (unique) {@link T} value of this * {@link AbstractIdentifier} object */ @Inject public RandomNumberStreamID(final String value) { super(value); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-mediapackage/src/main/java/com/amazonaws/services/mediapackage/model/transform/HlsManifestMarshaller.java
4224
/* * 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.mediapackage.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.mediapackage.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * HlsManifestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class HlsManifestMarshaller { private static final MarshallingInfo<String> ADMARKERS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("adMarkers").build(); private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("id").build(); private static final MarshallingInfo<Boolean> INCLUDEIFRAMEONLYSTREAM_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("includeIframeOnlyStream").build(); private static final MarshallingInfo<String> MANIFESTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("manifestName").build(); private static final MarshallingInfo<String> PLAYLISTTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("playlistType").build(); private static final MarshallingInfo<Integer> PLAYLISTWINDOWSECONDS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("playlistWindowSeconds").build(); private static final MarshallingInfo<Integer> PROGRAMDATETIMEINTERVALSECONDS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("programDateTimeIntervalSeconds").build(); private static final MarshallingInfo<String> URL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("url").build(); private static final HlsManifestMarshaller instance = new HlsManifestMarshaller(); public static HlsManifestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(HlsManifest hlsManifest, ProtocolMarshaller protocolMarshaller) { if (hlsManifest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(hlsManifest.getAdMarkers(), ADMARKERS_BINDING); protocolMarshaller.marshall(hlsManifest.getId(), ID_BINDING); protocolMarshaller.marshall(hlsManifest.getIncludeIframeOnlyStream(), INCLUDEIFRAMEONLYSTREAM_BINDING); protocolMarshaller.marshall(hlsManifest.getManifestName(), MANIFESTNAME_BINDING); protocolMarshaller.marshall(hlsManifest.getPlaylistType(), PLAYLISTTYPE_BINDING); protocolMarshaller.marshall(hlsManifest.getPlaylistWindowSeconds(), PLAYLISTWINDOWSECONDS_BINDING); protocolMarshaller.marshall(hlsManifest.getProgramDateTimeIntervalSeconds(), PROGRAMDATETIMEINTERVALSECONDS_BINDING); protocolMarshaller.marshall(hlsManifest.getUrl(), URL_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
kazuki43zoo/spring-security
acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java
6862
/* * Copyright 2004, 2005, 2006, 2017 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.acls.jdbc; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; import org.springframework.security.acls.model.NotFoundException; import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Sid; import org.springframework.util.Assert; /** * Simple JDBC-based implementation of <code>AclService</code>. * <p> * Requires the "dirty" flags in {@link org.springframework.security.acls.domain.AclImpl} * and {@link org.springframework.security.acls.domain.AccessControlEntryImpl} to be set, * so that the implementation can detect changed parameters easily. * * @author Ben Alex */ public class JdbcAclService implements AclService { // ~ Static fields/initializers // ===================================================================================== protected static final Log log = LogFactory.getLog(JdbcAclService.class); private static final String DEFAULT_SELECT_ACL_CLASS_COLUMNS = "class.class as class"; private static final String DEFAULT_SELECT_ACL_CLASS_COLUMNS_WITH_ID_TYPE = DEFAULT_SELECT_ACL_CLASS_COLUMNS + ", class.class_id_type as class_id_type"; private static final String DEFAULT_SELECT_ACL_WITH_PARENT_SQL = "select obj.object_id_identity as obj_id, " + DEFAULT_SELECT_ACL_CLASS_COLUMNS + " from acl_object_identity obj, acl_object_identity parent, acl_class class " + "where obj.parent_object = parent.id and obj.object_id_class = class.id " + "and parent.object_id_identity = ? and parent.object_id_class = (" + "select id FROM acl_class where acl_class.class = ?)"; private static final String DEFAULT_SELECT_ACL_WITH_PARENT_SQL_WITH_CLASS_ID_TYPE = "select obj.object_id_identity as obj_id, " + DEFAULT_SELECT_ACL_CLASS_COLUMNS_WITH_ID_TYPE + " from acl_object_identity obj, acl_object_identity parent, acl_class class " + "where obj.parent_object = parent.id and obj.object_id_class = class.id " + "and parent.object_id_identity = ? and parent.object_id_class = (" + "select id FROM acl_class where acl_class.class = ?)"; // ~ Instance fields // ================================================================================================ protected final JdbcTemplate jdbcTemplate; private final LookupStrategy lookupStrategy; private boolean aclClassIdSupported; private String findChildrenSql = DEFAULT_SELECT_ACL_WITH_PARENT_SQL; private AclClassIdUtils aclClassIdUtils; // ~ Constructors // =================================================================================================== public JdbcAclService(DataSource dataSource, LookupStrategy lookupStrategy) { Assert.notNull(dataSource, "DataSource required"); Assert.notNull(lookupStrategy, "LookupStrategy required"); this.jdbcTemplate = new JdbcTemplate(dataSource); this.lookupStrategy = lookupStrategy; this.aclClassIdUtils = new AclClassIdUtils(); } // ~ Methods // ======================================================================================================== public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) { Object[] args = { parentIdentity.getIdentifier(), parentIdentity.getType() }; List<ObjectIdentity> objects = jdbcTemplate.query(findChildrenSql, args, new RowMapper<ObjectIdentity>() { public ObjectIdentity mapRow(ResultSet rs, int rowNum) throws SQLException { String javaType = rs.getString("class"); Serializable identifier = (Serializable) rs.getObject("obj_id"); identifier = aclClassIdUtils.identifierFrom(identifier, rs); return new ObjectIdentityImpl(javaType, identifier); } }); if (objects.size() == 0) { return null; } return objects; } public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException { Map<ObjectIdentity, Acl> map = readAclsById(Arrays.asList(object), sids); Assert.isTrue(map.containsKey(object), () -> "There should have been an Acl entry for ObjectIdentity " + object); return (Acl) map.get(object); } public Acl readAclById(ObjectIdentity object) throws NotFoundException { return readAclById(object, null); } public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException { return readAclsById(objects, null); } public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException { Map<ObjectIdentity, Acl> result = lookupStrategy.readAclsById(objects, sids); // Check every requested object identity was found (throw NotFoundException if // needed) for (ObjectIdentity oid : objects) { if (!result.containsKey(oid)) { throw new NotFoundException( "Unable to find ACL information for object identity '" + oid + "'"); } } return result; } /** * Allows customization of the SQL query used to find child object identities. * * @param findChildrenSql */ public void setFindChildrenQuery(String findChildrenSql) { this.findChildrenSql = findChildrenSql; } public void setAclClassIdSupported(boolean aclClassIdSupported) { this.aclClassIdSupported = aclClassIdSupported; if (aclClassIdSupported) { // Change the default insert if it hasn't been overridden if (this.findChildrenSql.equals(DEFAULT_SELECT_ACL_WITH_PARENT_SQL)) { this.findChildrenSql = DEFAULT_SELECT_ACL_WITH_PARENT_SQL_WITH_CLASS_ID_TYPE; } else { log.debug("Find children statement has already been overridden, so not overridding the default"); } } } public void setAclClassIdUtils(AclClassIdUtils aclClassIdUtils) { this.aclClassIdUtils = aclClassIdUtils; } protected boolean isAclClassIdSupported() { return aclClassIdSupported; } }
apache-2.0
moosbusch/xbCDWALite
src/edu/getty/cdwa/cdwaLite/ResourceWrapDocument.java
12042
/* * Copyright 2013 Gunnar Kappei. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.getty.cdwa.cdwaLite; /** * A document containing one resourceWrap(@http://www.getty.edu/CDWA/CDWALite) element. * * This is a complex type. */ public interface ResourceWrapDocument extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ResourceWrapDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s1F643FAF4399D1206A04583D585DB128").resolveHandle("resourcewrap6cf7doctype"); /** * Gets the "resourceWrap" element */ edu.getty.cdwa.cdwaLite.ResourceWrapDocument.ResourceWrap getResourceWrap(); /** * Sets the "resourceWrap" element */ void setResourceWrap(edu.getty.cdwa.cdwaLite.ResourceWrapDocument.ResourceWrap resourceWrap); /** * Appends and returns a new empty "resourceWrap" element */ edu.getty.cdwa.cdwaLite.ResourceWrapDocument.ResourceWrap addNewResourceWrap(); /** * An XML resourceWrap(@http://www.getty.edu/CDWA/CDWALite). * * This is a complex type. */ public interface ResourceWrap extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ResourceWrap.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s1F643FAF4399D1206A04583D585DB128").resolveHandle("resourcewrap760belemtype"); /** * Gets a List of "resourceSet" elements */ java.util.List<edu.getty.cdwa.cdwaLite.ResourceSetDocument.ResourceSet> getResourceSetList(); /** * Gets array of all "resourceSet" elements * @deprecated */ @Deprecated edu.getty.cdwa.cdwaLite.ResourceSetDocument.ResourceSet[] getResourceSetArray(); /** * Gets ith "resourceSet" element */ edu.getty.cdwa.cdwaLite.ResourceSetDocument.ResourceSet getResourceSetArray(int i); /** * Returns number of "resourceSet" element */ int sizeOfResourceSetArray(); /** * Sets array of all "resourceSet" element */ void setResourceSetArray(edu.getty.cdwa.cdwaLite.ResourceSetDocument.ResourceSet[] resourceSetArray); /** * Sets ith "resourceSet" element */ void setResourceSetArray(int i, edu.getty.cdwa.cdwaLite.ResourceSetDocument.ResourceSet resourceSet); /** * Inserts and returns a new empty value (as xml) as the ith "resourceSet" element */ edu.getty.cdwa.cdwaLite.ResourceSetDocument.ResourceSet insertNewResourceSet(int i); /** * Appends and returns a new empty value (as xml) as the last "resourceSet" element */ edu.getty.cdwa.cdwaLite.ResourceSetDocument.ResourceSet addNewResourceSet(); /** * Removes the ith "resourceSet" element */ void removeResourceSet(int i); /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument.ResourceWrap newInstance() { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument.ResourceWrap) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument.ResourceWrap newInstance(org.apache.xmlbeans.XmlOptions options) { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument.ResourceWrap) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } private Factory() { } // No instance of this class allowed } } /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument newInstance() { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument newInstance(org.apache.xmlbeans.XmlOptions options) { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } /** @param xmlAsString the string value to parse */ public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); } /** @param file the file from which to load an xml document */ public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); } public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static edu.getty.cdwa.cdwaLite.ResourceWrapDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (edu.getty.cdwa.cdwaLite.ResourceWrapDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } private Factory() { } // No instance of this class allowed } }
apache-2.0
minji-kim/calcite
core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
205227
/* * 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.calcite.sql.validate; import org.apache.calcite.config.NullCollation; import org.apache.calcite.jdbc.CalciteSchema; import org.apache.calcite.linq4j.Ord; import org.apache.calcite.linq4j.function.Function2; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.prepare.Prepare; import org.apache.calcite.rel.type.DynamicRecordType; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.rel.type.RelDataTypeSystem; import org.apache.calcite.rel.type.RelRecordType; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexNode; import org.apache.calcite.runtime.CalciteContextException; import org.apache.calcite.runtime.CalciteException; import org.apache.calcite.runtime.Feature; import org.apache.calcite.runtime.Resources; import org.apache.calcite.schema.Table; import org.apache.calcite.schema.impl.ModifiableViewTable; import org.apache.calcite.sql.JoinConditionType; import org.apache.calcite.sql.JoinType; import org.apache.calcite.sql.SqlAccessEnum; import org.apache.calcite.sql.SqlAccessType; import org.apache.calcite.sql.SqlBasicCall; import org.apache.calcite.sql.SqlCall; import org.apache.calcite.sql.SqlCallBinding; import org.apache.calcite.sql.SqlDataTypeSpec; import org.apache.calcite.sql.SqlDelete; import org.apache.calcite.sql.SqlDynamicParam; import org.apache.calcite.sql.SqlExplain; import org.apache.calcite.sql.SqlFunction; import org.apache.calcite.sql.SqlFunctionCategory; import org.apache.calcite.sql.SqlIdentifier; import org.apache.calcite.sql.SqlInsert; import org.apache.calcite.sql.SqlIntervalLiteral; import org.apache.calcite.sql.SqlIntervalQualifier; import org.apache.calcite.sql.SqlJoin; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlLiteral; import org.apache.calcite.sql.SqlMatchRecognize; import org.apache.calcite.sql.SqlMerge; import org.apache.calcite.sql.SqlNode; import org.apache.calcite.sql.SqlNodeList; import org.apache.calcite.sql.SqlOperator; import org.apache.calcite.sql.SqlOperatorTable; import org.apache.calcite.sql.SqlOrderBy; import org.apache.calcite.sql.SqlSampleSpec; import org.apache.calcite.sql.SqlSelect; import org.apache.calcite.sql.SqlSelectKeyword; import org.apache.calcite.sql.SqlSyntax; import org.apache.calcite.sql.SqlUnresolvedFunction; import org.apache.calcite.sql.SqlUpdate; import org.apache.calcite.sql.SqlUtil; import org.apache.calcite.sql.SqlWindow; import org.apache.calcite.sql.SqlWith; import org.apache.calcite.sql.SqlWithItem; import org.apache.calcite.sql.fun.SqlCase; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.sql.type.AssignableOperandTypeChecker; import org.apache.calcite.sql.type.ReturnTypes; import org.apache.calcite.sql.type.SqlOperandTypeInference; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.calcite.sql.type.SqlTypeUtil; import org.apache.calcite.sql.util.SqlBasicVisitor; import org.apache.calcite.sql.util.SqlShuttle; import org.apache.calcite.sql.util.SqlVisitor; import org.apache.calcite.sql2rel.InitializerContext; import org.apache.calcite.util.BitString; import org.apache.calcite.util.Bug; import org.apache.calcite.util.ImmutableBitSet; import org.apache.calcite.util.ImmutableNullableList; import org.apache.calcite.util.Litmus; import org.apache.calcite.util.Pair; import org.apache.calcite.util.Static; import org.apache.calcite.util.Util; import org.apache.calcite.util.trace.CalciteTrace; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.slf4j.Logger; import java.math.BigDecimal; import java.math.BigInteger; import java.util.AbstractList; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static org.apache.calcite.sql.SqlUtil.stripAs; import static org.apache.calcite.util.Static.RESOURCE; /** * Default implementation of {@link SqlValidator}. */ public class SqlValidatorImpl implements SqlValidatorWithHints { //~ Static fields/initializers --------------------------------------------- public static final Logger TRACER = CalciteTrace.PARSER_LOGGER; /** * Alias generated for the source table when rewriting UPDATE to MERGE. */ public static final String UPDATE_SRC_ALIAS = "SYS$SRC"; /** * Alias generated for the target table when rewriting UPDATE to MERGE if no * alias was specified by the user. */ public static final String UPDATE_TGT_ALIAS = "SYS$TGT"; /** * Alias prefix generated for source columns when rewriting UPDATE to MERGE. */ public static final String UPDATE_ANON_PREFIX = "SYS$ANON"; //~ Instance fields -------------------------------------------------------- private final SqlOperatorTable opTab; final SqlValidatorCatalogReader catalogReader; /** * Maps ParsePosition strings to the {@link SqlIdentifier} identifier * objects at these positions */ protected final Map<String, IdInfo> idPositions = new HashMap<>(); /** * Maps {@link SqlNode query node} objects to the {@link SqlValidatorScope} * scope created from them. */ protected final Map<SqlNode, SqlValidatorScope> scopes = new IdentityHashMap<>(); /** * Maps a {@link SqlSelect} node to the scope used by its WHERE and HAVING * clauses. */ private final Map<SqlSelect, SqlValidatorScope> whereScopes = new IdentityHashMap<>(); /** * Maps a {@link SqlSelect} node to the scope used by its GROUP BY clause. */ private final Map<SqlSelect, SqlValidatorScope> groupByScopes = new IdentityHashMap<>(); /** * Maps a {@link SqlSelect} node to the scope used by its SELECT and HAVING * clauses. */ private final Map<SqlSelect, SqlValidatorScope> selectScopes = new IdentityHashMap<>(); /** * Maps a {@link SqlSelect} node to the scope used by its ORDER BY clause. */ private final Map<SqlSelect, SqlValidatorScope> orderScopes = new IdentityHashMap<>(); /** * Maps a {@link SqlSelect} node that is the argument to a CURSOR * constructor to the scope of the result of that select node */ private final Map<SqlSelect, SqlValidatorScope> cursorScopes = new IdentityHashMap<>(); /** * The name-resolution scope of a LATERAL TABLE clause. */ private TableScope tableScope = null; /** * Maps a {@link SqlNode node} to the * {@link SqlValidatorNamespace namespace} which describes what columns they * contain. */ protected final Map<SqlNode, SqlValidatorNamespace> namespaces = new IdentityHashMap<>(); /** * Set of select expressions used as cursor definitions. In standard SQL, * only the top-level SELECT is a cursor; Calcite extends this with * cursors as inputs to table functions. */ private final Set<SqlNode> cursorSet = Sets.newIdentityHashSet(); /** * Stack of objects that maintain information about function calls. A stack * is needed to handle nested function calls. The function call currently * being validated is at the top of the stack. */ protected final Deque<FunctionParamInfo> functionCallStack = new ArrayDeque<>(); private int nextGeneratedId; protected final RelDataTypeFactory typeFactory; /** The type of dynamic parameters until a type is imposed on them. */ protected final RelDataType unknownType; private final RelDataType booleanType; /** * Map of derived RelDataType for each node. This is an IdentityHashMap * since in some cases (such as null literals) we need to discriminate by * instance. */ private final Map<SqlNode, RelDataType> nodeToTypeMap = new IdentityHashMap<>(); private final AggFinder aggFinder; private final AggFinder aggOrOverFinder; private final AggFinder aggOrOverOrGroupFinder; private final AggFinder groupFinder; private final AggFinder overFinder; private final SqlConformance conformance; private final Map<SqlNode, SqlNode> originalExprs = new HashMap<>(); private SqlNode top; // REVIEW jvs 30-June-2006: subclasses may override shouldExpandIdentifiers // in a way that ignores this; we should probably get rid of the protected // method and always use this variable (or better, move preferences like // this to a separate "parameter" class) protected boolean expandIdentifiers; protected boolean expandColumnReferences; private boolean rewriteCalls; private NullCollation nullCollation = NullCollation.HIGH; // TODO jvs 11-Dec-2008: make this local to performUnconditionalRewrites // if it's OK to expand the signature of that method. private boolean validatingSqlMerge; private boolean inWindow; // Allow nested aggregates private final SqlValidatorImpl.ValidationErrorFunction validationErrorFunction = new SqlValidatorImpl.ValidationErrorFunction(); //~ Constructors ----------------------------------------------------------- /** * Creates a validator. * * @param opTab Operator table * @param catalogReader Catalog reader * @param typeFactory Type factory * @param conformance Compatibility mode */ protected SqlValidatorImpl( SqlOperatorTable opTab, SqlValidatorCatalogReader catalogReader, RelDataTypeFactory typeFactory, SqlConformance conformance) { this.opTab = Preconditions.checkNotNull(opTab); this.catalogReader = Preconditions.checkNotNull(catalogReader); this.typeFactory = Preconditions.checkNotNull(typeFactory); this.conformance = Preconditions.checkNotNull(conformance); unknownType = typeFactory.createUnknownType(); booleanType = typeFactory.createSqlType(SqlTypeName.BOOLEAN); rewriteCalls = true; expandColumnReferences = true; aggFinder = new AggFinder(opTab, false, true, false, null); aggOrOverFinder = new AggFinder(opTab, true, true, false, null); overFinder = new AggFinder(opTab, true, false, false, aggOrOverFinder); groupFinder = new AggFinder(opTab, false, false, true, null); aggOrOverOrGroupFinder = new AggFinder(opTab, true, true, true, null); } //~ Methods ---------------------------------------------------------------- public SqlConformance getConformance() { return conformance; } public SqlValidatorCatalogReader getCatalogReader() { return catalogReader; } public SqlOperatorTable getOperatorTable() { return opTab; } public RelDataTypeFactory getTypeFactory() { return typeFactory; } public RelDataType getUnknownType() { return unknownType; } public SqlNodeList expandStar( SqlNodeList selectList, SqlSelect select, boolean includeSystemVars) { final List<SqlNode> list = new ArrayList<>(); final List<Map.Entry<String, RelDataType>> types = new ArrayList<>(); for (int i = 0; i < selectList.size(); i++) { final SqlNode selectItem = selectList.get(i); expandSelectItem( selectItem, select, unknownType, list, catalogReader.nameMatcher().isCaseSensitive() ? new LinkedHashSet<String>() : new TreeSet<>(String.CASE_INSENSITIVE_ORDER), types, includeSystemVars); } getRawSelectScope(select).setExpandedSelectList(list); return new SqlNodeList(list, SqlParserPos.ZERO); } // implement SqlValidator public void declareCursor(SqlSelect select, SqlValidatorScope parentScope) { cursorSet.add(select); // add the cursor to a map that maps the cursor to its select based on // the position of the cursor relative to other cursors in that call FunctionParamInfo funcParamInfo = functionCallStack.peek(); Map<Integer, SqlSelect> cursorMap = funcParamInfo.cursorPosToSelectMap; int numCursors = cursorMap.size(); cursorMap.put(numCursors, select); // create a namespace associated with the result of the select // that is the argument to the cursor constructor; register it // with a scope corresponding to the cursor SelectScope cursorScope = new SelectScope(parentScope, null, select); cursorScopes.put(select, cursorScope); final SelectNamespace selectNs = createSelectNamespace(select, select); String alias = deriveAlias(select, nextGeneratedId++); registerNamespace(cursorScope, alias, selectNs, false); } // implement SqlValidator public void pushFunctionCall() { FunctionParamInfo funcInfo = new FunctionParamInfo(); functionCallStack.push(funcInfo); } // implement SqlValidator public void popFunctionCall() { functionCallStack.pop(); } // implement SqlValidator public String getParentCursor(String columnListParamName) { FunctionParamInfo funcParamInfo = functionCallStack.peek(); Map<String, String> parentCursorMap = funcParamInfo.columnListParamToParentCursorMap; return parentCursorMap.get(columnListParamName); } /** * If <code>selectItem</code> is "*" or "TABLE.*", expands it and returns * true; otherwise writes the unexpanded item. * * @param selectItem Select-list item * @param select Containing select clause * @param selectItems List that expanded items are written to * @param aliases Set of aliases * @param types List of data types in alias order * @param includeSystemVars If true include system vars in lists * @return Whether the node was expanded */ private boolean expandSelectItem( final SqlNode selectItem, SqlSelect select, RelDataType targetType, List<SqlNode> selectItems, Set<String> aliases, List<Map.Entry<String, RelDataType>> types, final boolean includeSystemVars) { final SelectScope scope = (SelectScope) getWhereScope(select); if (expandStar(selectItems, aliases, types, includeSystemVars, scope, selectItem)) { return true; } // Expand the select item: fully-qualify columns, and convert // parentheses-free functions such as LOCALTIME into explicit function // calls. SqlNode expanded = expand(selectItem, scope); final String alias = deriveAlias( selectItem, aliases.size()); // If expansion has altered the natural alias, supply an explicit 'AS'. final SqlValidatorScope selectScope = getSelectScope(select); if (expanded != selectItem) { String newAlias = deriveAlias( expanded, aliases.size()); if (!newAlias.equals(alias)) { expanded = SqlStdOperatorTable.AS.createCall( selectItem.getParserPosition(), expanded, new SqlIdentifier(alias, SqlParserPos.ZERO)); deriveTypeImpl(selectScope, expanded); } } selectItems.add(expanded); aliases.add(alias); inferUnknownTypes(targetType, scope, expanded); final RelDataType type = deriveType(selectScope, expanded); setValidatedNodeType(expanded, type); types.add(Pair.of(alias, type)); return false; } private boolean expandStar(List<SqlNode> selectItems, Set<String> aliases, List<Map.Entry<String, RelDataType>> types, boolean includeSystemVars, SelectScope scope, SqlNode node) { if (!(node instanceof SqlIdentifier)) { return false; } final SqlIdentifier identifier = (SqlIdentifier) node; if (!identifier.isStar()) { return false; } final SqlParserPos startPosition = identifier.getParserPosition(); switch (identifier.names.size()) { case 1: for (ScopeChild child : scope.children) { final int before = types.size(); if (child.namespace.getRowType().isDynamicStruct()) { // don't expand star if the underneath table is dynamic. // Treat this star as a special field in validation/conversion and // wait until execution time to expand this star. final SqlNode exp = new SqlIdentifier( ImmutableList.of(child.name, DynamicRecordType.DYNAMIC_STAR_PREFIX), startPosition); addToSelectList( selectItems, aliases, types, exp, scope, includeSystemVars); } else { final SqlNode from = child.namespace.getNode(); final SqlValidatorNamespace fromNs = getNamespace(from, scope); assert fromNs != null; final RelDataType rowType = fromNs.getRowType(); for (RelDataTypeField field : rowType.getFieldList()) { String columnName = field.getName(); // TODO: do real implicit collation here final SqlIdentifier exp = new SqlIdentifier( ImmutableList.of(child.name, columnName), startPosition); // Don't add expanded rolled up columns if (!isRolledUpColumn(exp, scope)) { addOrExpandField( selectItems, aliases, types, includeSystemVars, scope, exp, field); } } } if (child.nullable) { for (int i = before; i < types.size(); i++) { final Map.Entry<String, RelDataType> entry = types.get(i); final RelDataType type = entry.getValue(); if (!type.isNullable()) { types.set(i, Pair.of(entry.getKey(), typeFactory.createTypeWithNullability(type, true))); } } } } return true; default: final SqlIdentifier prefixId = identifier.skipLast(1); final SqlValidatorScope.ResolvedImpl resolved = new SqlValidatorScope.ResolvedImpl(); final SqlNameMatcher nameMatcher = scope.validator.catalogReader.nameMatcher(); scope.resolve(prefixId.names, nameMatcher, true, resolved); if (resolved.count() == 0) { // e.g. "select s.t.* from e" // or "select r.* from e" throw newValidationError(prefixId, RESOURCE.unknownIdentifier(prefixId.toString())); } final RelDataType rowType = resolved.only().rowType(); if (rowType.isDynamicStruct()) { // don't expand star if the underneath table is dynamic. addToSelectList( selectItems, aliases, types, prefixId.plus(DynamicRecordType.DYNAMIC_STAR_PREFIX, startPosition), scope, includeSystemVars); } else if (rowType.isStruct()) { for (RelDataTypeField field : rowType.getFieldList()) { String columnName = field.getName(); // TODO: do real implicit collation here addOrExpandField( selectItems, aliases, types, includeSystemVars, scope, prefixId.plus(columnName, startPosition), field); } } else { throw newValidationError(prefixId, RESOURCE.starRequiresRecordType()); } return true; } } private boolean addOrExpandField(List<SqlNode> selectItems, Set<String> aliases, List<Map.Entry<String, RelDataType>> types, boolean includeSystemVars, SelectScope scope, SqlIdentifier id, RelDataTypeField field) { switch (field.getType().getStructKind()) { case PEEK_FIELDS: case PEEK_FIELDS_DEFAULT: final SqlNode starExp = id.plusStar(); expandStar( selectItems, aliases, types, includeSystemVars, scope, starExp); return true; default: addToSelectList( selectItems, aliases, types, id, scope, includeSystemVars); } return false; } public SqlNode validate(SqlNode topNode) { SqlValidatorScope scope = new EmptyScope(this); scope = new CatalogScope(scope, ImmutableList.of("CATALOG")); final SqlNode topNode2 = validateScopedExpression(topNode, scope); final RelDataType type = getValidatedNodeType(topNode2); Util.discard(type); return topNode2; } public List<SqlMoniker> lookupHints(SqlNode topNode, SqlParserPos pos) { SqlValidatorScope scope = new EmptyScope(this); SqlNode outermostNode = performUnconditionalRewrites(topNode, false); cursorSet.add(outermostNode); if (outermostNode.isA(SqlKind.TOP_LEVEL)) { registerQuery( scope, null, outermostNode, outermostNode, null, false); } final SqlValidatorNamespace ns = getNamespace(outermostNode); if (ns == null) { throw new AssertionError("Not a query: " + outermostNode); } Collection<SqlMoniker> hintList = Sets.newTreeSet(SqlMoniker.COMPARATOR); lookupSelectHints(ns, pos, hintList); return ImmutableList.copyOf(hintList); } public SqlMoniker lookupQualifiedName(SqlNode topNode, SqlParserPos pos) { final String posString = pos.toString(); IdInfo info = idPositions.get(posString); if (info != null) { final SqlQualified qualified = info.scope.fullyQualify(info.id); return new SqlIdentifierMoniker(qualified.identifier); } else { return null; } } /** * Looks up completion hints for a syntactically correct select SQL that has * been parsed into an expression tree. * * @param select the Select node of the parsed expression tree * @param pos indicates the position in the sql statement we want to get * completion hints for * @param hintList list of {@link SqlMoniker} (sql identifiers) that can * fill in at the indicated position */ void lookupSelectHints( SqlSelect select, SqlParserPos pos, Collection<SqlMoniker> hintList) { IdInfo info = idPositions.get(pos.toString()); if ((info == null) || (info.scope == null)) { SqlNode fromNode = select.getFrom(); final SqlValidatorScope fromScope = getFromScope(select); lookupFromHints(fromNode, fromScope, pos, hintList); } else { lookupNameCompletionHints(info.scope, info.id.names, info.id.getParserPosition(), hintList); } } private void lookupSelectHints( SqlValidatorNamespace ns, SqlParserPos pos, Collection<SqlMoniker> hintList) { final SqlNode node = ns.getNode(); if (node instanceof SqlSelect) { lookupSelectHints((SqlSelect) node, pos, hintList); } } private void lookupFromHints( SqlNode node, SqlValidatorScope scope, SqlParserPos pos, Collection<SqlMoniker> hintList) { final SqlValidatorNamespace ns = getNamespace(node); if (ns.isWrapperFor(IdentifierNamespace.class)) { IdentifierNamespace idNs = ns.unwrap(IdentifierNamespace.class); final SqlIdentifier id = idNs.getId(); for (int i = 0; i < id.names.size(); i++) { if (pos.toString().equals( id.getComponent(i).getParserPosition().toString())) { final List<SqlMoniker> objNames = new ArrayList<>(); SqlValidatorUtil.getSchemaObjectMonikers( getCatalogReader(), id.names.subList(0, i + 1), objNames); for (SqlMoniker objName : objNames) { if (objName.getType() != SqlMonikerType.FUNCTION) { hintList.add(objName); } } return; } } } switch (node.getKind()) { case JOIN: lookupJoinHints((SqlJoin) node, scope, pos, hintList); break; default: lookupSelectHints(ns, pos, hintList); break; } } private void lookupJoinHints( SqlJoin join, SqlValidatorScope scope, SqlParserPos pos, Collection<SqlMoniker> hintList) { SqlNode left = join.getLeft(); SqlNode right = join.getRight(); SqlNode condition = join.getCondition(); lookupFromHints(left, scope, pos, hintList); if (hintList.size() > 0) { return; } lookupFromHints(right, scope, pos, hintList); if (hintList.size() > 0) { return; } final JoinConditionType conditionType = join.getConditionType(); final SqlValidatorScope joinScope = scopes.get(join); switch (conditionType) { case ON: condition.findValidOptions(this, joinScope, pos, hintList); return; default: // No suggestions. // Not supporting hints for other types such as 'Using' yet. return; } } /** * Populates a list of all the valid alternatives for an identifier. * * @param scope Validation scope * @param names Components of the identifier * @param pos position * @param hintList a list of valid options */ public final void lookupNameCompletionHints( SqlValidatorScope scope, List<String> names, SqlParserPos pos, Collection<SqlMoniker> hintList) { // Remove the last part of name - it is a dummy List<String> subNames = Util.skipLast(names); if (subNames.size() > 0) { // If there's a prefix, resolve it to a namespace. SqlValidatorNamespace ns = null; for (String name : subNames) { if (ns == null) { final SqlValidatorScope.ResolvedImpl resolved = new SqlValidatorScope.ResolvedImpl(); final SqlNameMatcher nameMatcher = catalogReader.nameMatcher(); scope.resolve(ImmutableList.of(name), nameMatcher, false, resolved); if (resolved.count() == 1) { ns = resolved.only().namespace; } } else { ns = ns.lookupChild(name); } if (ns == null) { break; } } if (ns != null) { RelDataType rowType = ns.getRowType(); for (RelDataTypeField field : rowType.getFieldList()) { hintList.add( new SqlMonikerImpl( field.getName(), SqlMonikerType.COLUMN)); } } // builtin function names are valid completion hints when the // identifier has only 1 name part findAllValidFunctionNames(names, this, hintList, pos); } else { // No prefix; use the children of the current scope (that is, // the aliases in the FROM clause) scope.findAliases(hintList); // If there's only one alias, add all child columns SelectScope selectScope = SqlValidatorUtil.getEnclosingSelectScope(scope); if ((selectScope != null) && (selectScope.getChildren().size() == 1)) { RelDataType rowType = selectScope.getChildren().get(0).getRowType(); for (RelDataTypeField field : rowType.getFieldList()) { hintList.add( new SqlMonikerImpl( field.getName(), SqlMonikerType.COLUMN)); } } } findAllValidUdfNames(names, this, hintList); } private static void findAllValidUdfNames( List<String> names, SqlValidator validator, Collection<SqlMoniker> result) { final List<SqlMoniker> objNames = new ArrayList<>(); SqlValidatorUtil.getSchemaObjectMonikers( validator.getCatalogReader(), names, objNames); for (SqlMoniker objName : objNames) { if (objName.getType() == SqlMonikerType.FUNCTION) { result.add(objName); } } } private static void findAllValidFunctionNames( List<String> names, SqlValidator validator, Collection<SqlMoniker> result, SqlParserPos pos) { // a function name can only be 1 part if (names.size() > 1) { return; } for (SqlOperator op : validator.getOperatorTable().getOperatorList()) { SqlIdentifier curOpId = new SqlIdentifier( op.getName(), pos); final SqlCall call = SqlUtil.makeCall( validator.getOperatorTable(), curOpId); if (call != null) { result.add( new SqlMonikerImpl( op.getName(), SqlMonikerType.FUNCTION)); } else { if ((op.getSyntax() == SqlSyntax.FUNCTION) || (op.getSyntax() == SqlSyntax.PREFIX)) { if (op.getOperandTypeChecker() != null) { String sig = op.getAllowedSignatures(); sig = sig.replaceAll("'", ""); result.add( new SqlMonikerImpl( sig, SqlMonikerType.FUNCTION)); continue; } result.add( new SqlMonikerImpl( op.getName(), SqlMonikerType.FUNCTION)); } } } } public SqlNode validateParameterizedExpression( SqlNode topNode, final Map<String, RelDataType> nameToTypeMap) { SqlValidatorScope scope = new ParameterScope(this, nameToTypeMap); return validateScopedExpression(topNode, scope); } private SqlNode validateScopedExpression( SqlNode topNode, SqlValidatorScope scope) { SqlNode outermostNode = performUnconditionalRewrites(topNode, false); cursorSet.add(outermostNode); top = outermostNode; TRACER.trace("After unconditional rewrite: {}", outermostNode); if (outermostNode.isA(SqlKind.TOP_LEVEL)) { registerQuery(scope, null, outermostNode, outermostNode, null, false); } outermostNode.validate(this, scope); if (!outermostNode.isA(SqlKind.TOP_LEVEL)) { // force type derivation so that we can provide it to the // caller later without needing the scope deriveType(scope, outermostNode); } TRACER.trace("After validation: {}", outermostNode); return outermostNode; } public void validateQuery(SqlNode node, SqlValidatorScope scope, RelDataType targetRowType) { final SqlValidatorNamespace ns = getNamespace(node, scope); if (node.getKind() == SqlKind.TABLESAMPLE) { List<SqlNode> operands = ((SqlCall) node).getOperandList(); SqlSampleSpec sampleSpec = SqlLiteral.sampleValue(operands.get(1)); if (sampleSpec instanceof SqlSampleSpec.SqlTableSampleSpec) { validateFeature(RESOURCE.sQLFeature_T613(), node.getParserPosition()); } else if (sampleSpec instanceof SqlSampleSpec.SqlSubstitutionSampleSpec) { validateFeature(RESOURCE.sQLFeatureExt_T613_Substitution(), node.getParserPosition()); } } validateNamespace(ns, targetRowType); if (node == top) { validateModality(node); } validateAccess( node, ns.getTable(), SqlAccessEnum.SELECT); } /** * Validates a namespace. * * @param namespace Namespace * @param targetRowType Desired row type, must not be null, may be the data * type 'unknown'. */ protected void validateNamespace(final SqlValidatorNamespace namespace, RelDataType targetRowType) { namespace.validate(targetRowType); if (namespace.getNode() != null) { setValidatedNodeType(namespace.getNode(), namespace.getType()); } } @VisibleForTesting public SqlValidatorScope getEmptyScope() { return new EmptyScope(this); } public SqlValidatorScope getCursorScope(SqlSelect select) { return cursorScopes.get(select); } public SqlValidatorScope getWhereScope(SqlSelect select) { return whereScopes.get(select); } public SqlValidatorScope getSelectScope(SqlSelect select) { return selectScopes.get(select); } public SelectScope getRawSelectScope(SqlSelect select) { SqlValidatorScope scope = getSelectScope(select); if (scope instanceof AggregatingSelectScope) { scope = ((AggregatingSelectScope) scope).getParent(); } return (SelectScope) scope; } public SqlValidatorScope getHavingScope(SqlSelect select) { // Yes, it's the same as getSelectScope return selectScopes.get(select); } public SqlValidatorScope getGroupScope(SqlSelect select) { // Yes, it's the same as getWhereScope return groupByScopes.get(select); } public SqlValidatorScope getFromScope(SqlSelect select) { return scopes.get(select); } public SqlValidatorScope getOrderScope(SqlSelect select) { return orderScopes.get(select); } public SqlValidatorScope getMatchRecognizeScope(SqlMatchRecognize node) { return scopes.get(node); } public SqlValidatorScope getJoinScope(SqlNode node) { return scopes.get(stripAs(node)); } public SqlValidatorScope getOverScope(SqlNode node) { return scopes.get(node); } private SqlValidatorNamespace getNamespace(SqlNode node, SqlValidatorScope scope) { if (node instanceof SqlIdentifier && scope instanceof DelegatingScope) { final SqlIdentifier id = (SqlIdentifier) node; final DelegatingScope idScope = (DelegatingScope) ((DelegatingScope) scope).getParent(); return getNamespace(id, idScope); } else if (node instanceof SqlCall) { // Handle extended identifiers. final SqlCall call = (SqlCall) node; switch (call.getOperator().getKind()) { case EXTEND: final SqlIdentifier id = (SqlIdentifier) call.getOperandList().get(0); final DelegatingScope idScope = (DelegatingScope) scope; return getNamespace(id, idScope); case AS: final SqlNode nested = call.getOperandList().get(0); switch (nested.getKind()) { case EXTEND: return getNamespace(nested, scope); } break; } } return getNamespace(node); } private SqlValidatorNamespace getNamespace(SqlIdentifier id, DelegatingScope scope) { if (id.isSimple()) { final SqlNameMatcher nameMatcher = catalogReader.nameMatcher(); final SqlValidatorScope.ResolvedImpl resolved = new SqlValidatorScope.ResolvedImpl(); scope.resolve(id.names, nameMatcher, false, resolved); if (resolved.count() == 1) { return resolved.only().namespace; } } return getNamespace(id); } public SqlValidatorNamespace getNamespace(SqlNode node) { switch (node.getKind()) { case AS: // AS has a namespace if it has a column list 'AS t (c1, c2, ...)' final SqlValidatorNamespace ns = namespaces.get(node); if (ns != null) { return ns; } // fall through case OVER: case COLLECTION_TABLE: case ORDER_BY: case TABLESAMPLE: return getNamespace(((SqlCall) node).operand(0)); default: return namespaces.get(node); } } /** * Performs expression rewrites which are always used unconditionally. These * rewrites massage the expression tree into a standard form so that the * rest of the validation logic can be simpler. * * @param node expression to be rewritten * @param underFrom whether node appears directly under a FROM clause * @return rewritten expression */ protected SqlNode performUnconditionalRewrites( SqlNode node, boolean underFrom) { if (node == null) { return node; } SqlNode newOperand; // first transform operands and invoke generic call rewrite if (node instanceof SqlCall) { if (node instanceof SqlMerge) { validatingSqlMerge = true; } SqlCall call = (SqlCall) node; final SqlKind kind = call.getKind(); final List<SqlNode> operands = call.getOperandList(); for (int i = 0; i < operands.size(); i++) { SqlNode operand = operands.get(i); boolean childUnderFrom; if (kind == SqlKind.SELECT) { childUnderFrom = i == SqlSelect.FROM_OPERAND; } else if (kind == SqlKind.AS && (i == 0)) { // for an aliased expression, it is under FROM if // the AS expression is under FROM childUnderFrom = underFrom; } else { childUnderFrom = false; } newOperand = performUnconditionalRewrites(operand, childUnderFrom); if (newOperand != null && newOperand != operand) { call.setOperand(i, newOperand); } } if (call.getOperator() instanceof SqlUnresolvedFunction) { assert call instanceof SqlBasicCall; final SqlUnresolvedFunction function = (SqlUnresolvedFunction) call.getOperator(); // This function hasn't been resolved yet. Perform // a half-hearted resolution now in case it's a // builtin function requiring special casing. If it's // not, we'll handle it later during overload resolution. final List<SqlOperator> overloads = new ArrayList<>(); opTab.lookupOperatorOverloads(function.getNameAsId(), function.getFunctionType(), SqlSyntax.FUNCTION, overloads); if (overloads.size() == 1) { ((SqlBasicCall) call).setOperator(overloads.get(0)); } } if (rewriteCalls) { node = call.getOperator().rewriteCall(this, call); } } else if (node instanceof SqlNodeList) { SqlNodeList list = (SqlNodeList) node; for (int i = 0, count = list.size(); i < count; i++) { SqlNode operand = list.get(i); newOperand = performUnconditionalRewrites( operand, false); if (newOperand != null) { list.getList().set(i, newOperand); } } } // now transform node itself final SqlKind kind = node.getKind(); switch (kind) { case VALUES: // CHECKSTYLE: IGNORE 1 if (underFrom || true) { // leave FROM (VALUES(...)) [ AS alias ] clauses alone, // otherwise they grow cancerously if this rewrite is invoked // over and over return node; } else { final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO); selectList.add(SqlIdentifier.star(SqlParserPos.ZERO)); return new SqlSelect(node.getParserPosition(), null, selectList, node, null, null, null, null, null, null, null); } case ORDER_BY: { SqlOrderBy orderBy = (SqlOrderBy) node; if (orderBy.query instanceof SqlSelect) { SqlSelect select = (SqlSelect) orderBy.query; // Don't clobber existing ORDER BY. It may be needed for // an order-sensitive function like RANK. if (select.getOrderList() == null) { // push ORDER BY into existing select select.setOrderBy(orderBy.orderList); select.setOffset(orderBy.offset); select.setFetch(orderBy.fetch); return select; } } if (orderBy.query instanceof SqlWith && ((SqlWith) orderBy.query).body instanceof SqlSelect) { SqlWith with = (SqlWith) orderBy.query; SqlSelect select = (SqlSelect) with.body; // Don't clobber existing ORDER BY. It may be needed for // an order-sensitive function like RANK. if (select.getOrderList() == null) { // push ORDER BY into existing select select.setOrderBy(orderBy.orderList); select.setOffset(orderBy.offset); select.setFetch(orderBy.fetch); return with; } } final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO); selectList.add(SqlIdentifier.star(SqlParserPos.ZERO)); final SqlNodeList orderList; if (getInnerSelect(node) != null && isAggregate(getInnerSelect(node))) { orderList = orderBy.orderList.clone(orderBy.orderList.getParserPosition()); // We assume that ORDER BY item does not have ASC etc. // We assume that ORDER BY item is present in SELECT list. for (int i = 0; i < orderList.size(); i++) { SqlNode sqlNode = orderList.get(i); SqlNodeList selectList2 = getInnerSelect(node).getSelectList(); for (Ord<SqlNode> sel : Ord.zip(selectList2)) { if (stripAs(sel.e).equalsDeep(sqlNode, Litmus.IGNORE)) { orderList.set(i, SqlLiteral.createExactNumeric(Integer.toString(sel.i + 1), SqlParserPos.ZERO)); } } } } else { orderList = orderBy.orderList; } return new SqlSelect(SqlParserPos.ZERO, null, selectList, orderBy.query, null, null, null, null, orderList, orderBy.offset, orderBy.fetch); } case EXPLICIT_TABLE: { // (TABLE t) is equivalent to (SELECT * FROM t) SqlCall call = (SqlCall) node; final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO); selectList.add(SqlIdentifier.star(SqlParserPos.ZERO)); return new SqlSelect(SqlParserPos.ZERO, null, selectList, call.operand(0), null, null, null, null, null, null, null); } case DELETE: { SqlDelete call = (SqlDelete) node; SqlSelect select = createSourceSelectForDelete(call); call.setSourceSelect(select); break; } case UPDATE: { SqlUpdate call = (SqlUpdate) node; SqlSelect select = createSourceSelectForUpdate(call); call.setSourceSelect(select); // See if we're supposed to rewrite UPDATE to MERGE // (unless this is the UPDATE clause of a MERGE, // in which case leave it alone). if (!validatingSqlMerge) { SqlNode selfJoinSrcExpr = getSelfJoinExprForUpdate( call.getTargetTable(), UPDATE_SRC_ALIAS); if (selfJoinSrcExpr != null) { node = rewriteUpdateToMerge(call, selfJoinSrcExpr); } } break; } case MERGE: { SqlMerge call = (SqlMerge) node; rewriteMerge(call); break; } } return node; } private SqlSelect getInnerSelect(SqlNode node) { for (;;) { if (node instanceof SqlSelect) { return (SqlSelect) node; } else if (node instanceof SqlOrderBy) { node = ((SqlOrderBy) node).query; } else if (node instanceof SqlWith) { node = ((SqlWith) node).body; } else { return null; } } } private void rewriteMerge(SqlMerge call) { SqlNodeList selectList; SqlUpdate updateStmt = call.getUpdateCall(); if (updateStmt != null) { // if we have an update statement, just clone the select list // from the update statement's source since it's the same as // what we want for the select list of the merge source -- '*' // followed by the update set expressions selectList = (SqlNodeList) updateStmt.getSourceSelect().getSelectList() .clone(); } else { // otherwise, just use select * selectList = new SqlNodeList(SqlParserPos.ZERO); selectList.add(SqlIdentifier.star(SqlParserPos.ZERO)); } SqlNode targetTable = call.getTargetTable(); if (call.getAlias() != null) { targetTable = SqlValidatorUtil.addAlias( targetTable, call.getAlias().getSimple()); } // Provided there is an insert substatement, the source select for // the merge is a left outer join between the source in the USING // clause and the target table; otherwise, the join is just an // inner join. Need to clone the source table reference in order // for validation to work SqlNode sourceTableRef = call.getSourceTableRef(); SqlInsert insertCall = call.getInsertCall(); JoinType joinType = (insertCall == null) ? JoinType.INNER : JoinType.LEFT; SqlNode leftJoinTerm = (SqlNode) sourceTableRef.clone(); SqlNode outerJoin = new SqlJoin(SqlParserPos.ZERO, leftJoinTerm, SqlLiteral.createBoolean(false, SqlParserPos.ZERO), joinType.symbol(SqlParserPos.ZERO), targetTable, JoinConditionType.ON.symbol(SqlParserPos.ZERO), call.getCondition()); SqlSelect select = new SqlSelect(SqlParserPos.ZERO, null, selectList, outerJoin, null, null, null, null, null, null, null); call.setSourceSelect(select); // Source for the insert call is a select of the source table // reference with the select list being the value expressions; // note that the values clause has already been converted to a // select on the values row constructor; so we need to extract // that via the from clause on the select if (insertCall != null) { SqlCall valuesCall = (SqlCall) insertCall.getSource(); SqlCall rowCall = valuesCall.operand(0); selectList = new SqlNodeList( rowCall.getOperandList(), SqlParserPos.ZERO); SqlNode insertSource = (SqlNode) sourceTableRef.clone(); select = new SqlSelect(SqlParserPos.ZERO, null, selectList, insertSource, null, null, null, null, null, null, null); insertCall.setSource(select); } } private SqlNode rewriteUpdateToMerge( SqlUpdate updateCall, SqlNode selfJoinSrcExpr) { // Make sure target has an alias. if (updateCall.getAlias() == null) { updateCall.setAlias( new SqlIdentifier(UPDATE_TGT_ALIAS, SqlParserPos.ZERO)); } SqlNode selfJoinTgtExpr = getSelfJoinExprForUpdate( updateCall.getTargetTable(), updateCall.getAlias().getSimple()); assert selfJoinTgtExpr != null; // Create join condition between source and target exprs, // creating a conjunction with the user-level WHERE // clause if one was supplied SqlNode condition = updateCall.getCondition(); SqlNode selfJoinCond = SqlStdOperatorTable.EQUALS.createCall( SqlParserPos.ZERO, selfJoinSrcExpr, selfJoinTgtExpr); if (condition == null) { condition = selfJoinCond; } else { condition = SqlStdOperatorTable.AND.createCall( SqlParserPos.ZERO, selfJoinCond, condition); } SqlNode target = updateCall.getTargetTable().clone(SqlParserPos.ZERO); // For the source, we need to anonymize the fields, so // that for a statement like UPDATE T SET I = I + 1, // there's no ambiguity for the "I" in "I + 1"; // this is OK because the source and target have // identical values due to the self-join. // Note that we anonymize the source rather than the // target because downstream, the optimizer rules // don't want to see any projection on top of the target. IdentifierNamespace ns = new IdentifierNamespace(this, target, null, null); RelDataType rowType = ns.getRowType(); SqlNode source = updateCall.getTargetTable().clone(SqlParserPos.ZERO); final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO); int i = 1; for (RelDataTypeField field : rowType.getFieldList()) { SqlIdentifier col = new SqlIdentifier( field.getName(), SqlParserPos.ZERO); selectList.add( SqlValidatorUtil.addAlias(col, UPDATE_ANON_PREFIX + i)); ++i; } source = new SqlSelect(SqlParserPos.ZERO, null, selectList, source, null, null, null, null, null, null, null); source = SqlValidatorUtil.addAlias(source, UPDATE_SRC_ALIAS); SqlMerge mergeCall = new SqlMerge(updateCall.getParserPosition(), target, condition, source, updateCall, null, null, updateCall.getAlias()); rewriteMerge(mergeCall); return mergeCall; } /** * Allows a subclass to provide information about how to convert an UPDATE * into a MERGE via self-join. If this method returns null, then no such * conversion takes place. Otherwise, this method should return a suitable * unique identifier expression for the given table. * * @param table identifier for table being updated * @param alias alias to use for qualifying columns in expression, or null * for unqualified references; if this is equal to * {@value #UPDATE_SRC_ALIAS}, then column references have been * anonymized to "SYS$ANONx", where x is the 1-based column * number. * @return expression for unique identifier, or null to prevent conversion */ protected SqlNode getSelfJoinExprForUpdate( SqlNode table, String alias) { return null; } /** * Creates the SELECT statement that putatively feeds rows into an UPDATE * statement to be updated. * * @param call Call to the UPDATE operator * @return select statement */ protected SqlSelect createSourceSelectForUpdate(SqlUpdate call) { final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO); selectList.add(SqlIdentifier.star(SqlParserPos.ZERO)); int ordinal = 0; for (SqlNode exp : call.getSourceExpressionList()) { // Force unique aliases to avoid a duplicate for Y with // SET X=Y String alias = SqlUtil.deriveAliasFromOrdinal(ordinal); selectList.add(SqlValidatorUtil.addAlias(exp, alias)); ++ordinal; } SqlNode sourceTable = call.getTargetTable(); if (call.getAlias() != null) { sourceTable = SqlValidatorUtil.addAlias( sourceTable, call.getAlias().getSimple()); } return new SqlSelect(SqlParserPos.ZERO, null, selectList, sourceTable, call.getCondition(), null, null, null, null, null, null); } /** * Creates the SELECT statement that putatively feeds rows into a DELETE * statement to be deleted. * * @param call Call to the DELETE operator * @return select statement */ protected SqlSelect createSourceSelectForDelete(SqlDelete call) { final SqlNodeList selectList = new SqlNodeList(SqlParserPos.ZERO); selectList.add(SqlIdentifier.star(SqlParserPos.ZERO)); SqlNode sourceTable = call.getTargetTable(); if (call.getAlias() != null) { sourceTable = SqlValidatorUtil.addAlias( sourceTable, call.getAlias().getSimple()); } return new SqlSelect(SqlParserPos.ZERO, null, selectList, sourceTable, call.getCondition(), null, null, null, null, null, null); } /** * Returns null if there is no common type. E.g. if the rows have a * different number of columns. */ RelDataType getTableConstructorRowType( SqlCall values, SqlValidatorScope scope) { final List<SqlNode> rows = values.getOperandList(); assert rows.size() >= 1; final List<RelDataType> rowTypes = new ArrayList<>(); for (final SqlNode row : rows) { assert row.getKind() == SqlKind.ROW; SqlCall rowConstructor = (SqlCall) row; // REVIEW jvs 10-Sept-2003: Once we support single-row queries as // rows, need to infer aliases from there. final List<String> aliasList = new ArrayList<>(); final List<RelDataType> typeList = new ArrayList<>(); for (Ord<SqlNode> column : Ord.zip(rowConstructor.getOperandList())) { final String alias = deriveAlias(column.e, column.i); aliasList.add(alias); final RelDataType type = deriveType(scope, column.e); typeList.add(type); } rowTypes.add(typeFactory.createStructType(typeList, aliasList)); } if (rows.size() == 1) { // TODO jvs 10-Oct-2005: get rid of this workaround once // leastRestrictive can handle all cases return rowTypes.get(0); } return typeFactory.leastRestrictive(rowTypes); } public RelDataType getValidatedNodeType(SqlNode node) { RelDataType type = getValidatedNodeTypeIfKnown(node); if (type == null) { throw Util.needToImplement(node); } else { return type; } } public RelDataType getValidatedNodeTypeIfKnown(SqlNode node) { final RelDataType type = nodeToTypeMap.get(node); if (type != null) { return type; } final SqlValidatorNamespace ns = getNamespace(node); if (ns != null) { return ns.getType(); } final SqlNode original = originalExprs.get(node); if (original != null && original != node) { return getValidatedNodeType(original); } return null; } /** * Saves the type of a {@link SqlNode}, now that it has been validated. * * <p>Unlike the base class method, this method is not deprecated. * It is available from within Calcite, but is not part of the public API. * * @param node A SQL parse tree node, never null * @param type Its type; must not be null */ @SuppressWarnings("deprecation") public final void setValidatedNodeType(SqlNode node, RelDataType type) { Preconditions.checkNotNull(type); Preconditions.checkNotNull(node); if (type.equals(unknownType)) { // don't set anything until we know what it is, and don't overwrite // a known type with the unknown type return; } nodeToTypeMap.put(node, type); } public void removeValidatedNodeType(SqlNode node) { nodeToTypeMap.remove(node); } public RelDataType deriveType( SqlValidatorScope scope, SqlNode expr) { Preconditions.checkNotNull(scope); Preconditions.checkNotNull(expr); // if we already know the type, no need to re-derive RelDataType type = nodeToTypeMap.get(expr); if (type != null) { return type; } final SqlValidatorNamespace ns = getNamespace(expr); if (ns != null) { return ns.getType(); } type = deriveTypeImpl(scope, expr); Preconditions.checkArgument( type != null, "SqlValidator.deriveTypeInternal returned null"); setValidatedNodeType(expr, type); return type; } /** * Derives the type of a node, never null. */ RelDataType deriveTypeImpl( SqlValidatorScope scope, SqlNode operand) { DeriveTypeVisitor v = new DeriveTypeVisitor(scope); final RelDataType type = operand.accept(v); // After Guava 17, use Verify.verifyNotNull for Preconditions.checkNotNull Bug.upgrade("guava-17"); return Preconditions.checkNotNull(scope.nullifyType(operand, type)); } public RelDataType deriveConstructorType( SqlValidatorScope scope, SqlCall call, SqlFunction unresolvedConstructor, SqlFunction resolvedConstructor, List<RelDataType> argTypes) { SqlIdentifier sqlIdentifier = unresolvedConstructor.getSqlIdentifier(); assert sqlIdentifier != null; RelDataType type = catalogReader.getNamedType(sqlIdentifier); if (type == null) { // TODO jvs 12-Feb-2005: proper type name formatting throw newValidationError(sqlIdentifier, RESOURCE.unknownDatatypeName(sqlIdentifier.toString())); } if (resolvedConstructor == null) { if (call.operandCount() > 0) { // This is not a default constructor invocation, and // no user-defined constructor could be found throw handleUnresolvedFunction(call, unresolvedConstructor, argTypes, null); } } else { SqlCall testCall = resolvedConstructor.createCall( call.getParserPosition(), call.getOperandList()); RelDataType returnType = resolvedConstructor.validateOperands( this, scope, testCall); assert type == returnType; } if (shouldExpandIdentifiers()) { if (resolvedConstructor != null) { ((SqlBasicCall) call).setOperator(resolvedConstructor); } else { // fake a fully-qualified call to the default constructor ((SqlBasicCall) call).setOperator( new SqlFunction( type.getSqlIdentifier(), ReturnTypes.explicit(type), null, null, null, SqlFunctionCategory.USER_DEFINED_CONSTRUCTOR)); } } return type; } public CalciteException handleUnresolvedFunction(SqlCall call, SqlFunction unresolvedFunction, List<RelDataType> argTypes, List<String> argNames) { // For builtins, we can give a better error message final List<SqlOperator> overloads = new ArrayList<>(); opTab.lookupOperatorOverloads(unresolvedFunction.getNameAsId(), null, SqlSyntax.FUNCTION, overloads); if (overloads.size() == 1) { SqlFunction fun = (SqlFunction) overloads.get(0); if ((fun.getSqlIdentifier() == null) && (fun.getSyntax() != SqlSyntax.FUNCTION_ID)) { final int expectedArgCount = fun.getOperandCountRange().getMin(); throw newValidationError(call, RESOURCE.invalidArgCount(call.getOperator().getName(), expectedArgCount)); } } AssignableOperandTypeChecker typeChecking = new AssignableOperandTypeChecker(argTypes, argNames); String signature = typeChecking.getAllowedSignatures( unresolvedFunction, unresolvedFunction.getName()); throw newValidationError(call, RESOURCE.validatorUnknownFunction(signature)); } protected void inferUnknownTypes( RelDataType inferredType, SqlValidatorScope scope, SqlNode node) { final SqlValidatorScope newScope = scopes.get(node); if (newScope != null) { scope = newScope; } boolean isNullLiteral = SqlUtil.isNullLiteral(node, false); if ((node instanceof SqlDynamicParam) || isNullLiteral) { if (inferredType.equals(unknownType)) { if (isNullLiteral) { throw newValidationError(node, RESOURCE.nullIllegal()); } else { throw newValidationError(node, RESOURCE.dynamicParamIllegal()); } } // REVIEW: should dynamic parameter types always be nullable? RelDataType newInferredType = typeFactory.createTypeWithNullability(inferredType, true); if (SqlTypeUtil.inCharFamily(inferredType)) { newInferredType = typeFactory.createTypeWithCharsetAndCollation( newInferredType, inferredType.getCharset(), inferredType.getCollation()); } setValidatedNodeType(node, newInferredType); } else if (node instanceof SqlNodeList) { SqlNodeList nodeList = (SqlNodeList) node; if (inferredType.isStruct()) { if (inferredType.getFieldCount() != nodeList.size()) { // this can happen when we're validating an INSERT // where the source and target degrees are different; // bust out, and the error will be detected higher up return; } } int i = 0; for (SqlNode child : nodeList) { RelDataType type; if (inferredType.isStruct()) { type = inferredType.getFieldList().get(i).getType(); ++i; } else { type = inferredType; } inferUnknownTypes(type, scope, child); } } else if (node instanceof SqlCase) { final SqlCase caseCall = (SqlCase) node; final RelDataType whenType = caseCall.getValueOperand() == null ? booleanType : unknownType; for (SqlNode sqlNode : caseCall.getWhenOperands().getList()) { inferUnknownTypes(whenType, scope, sqlNode); } RelDataType returnType = deriveType(scope, node); for (SqlNode sqlNode : caseCall.getThenOperands().getList()) { inferUnknownTypes(returnType, scope, sqlNode); } if (!SqlUtil.isNullLiteral(caseCall.getElseOperand(), false)) { inferUnknownTypes( returnType, scope, caseCall.getElseOperand()); } else { setValidatedNodeType(caseCall.getElseOperand(), returnType); } } else if (node instanceof SqlCall) { final SqlCall call = (SqlCall) node; final SqlOperandTypeInference operandTypeInference = call.getOperator().getOperandTypeInference(); final SqlCallBinding callBinding = new SqlCallBinding(this, scope, call); final List<SqlNode> operands = callBinding.operands(); final RelDataType[] operandTypes = new RelDataType[operands.size()]; if (operandTypeInference == null) { // TODO: eventually should assert(operandTypeInference != null) // instead; for now just eat it Arrays.fill(operandTypes, unknownType); } else { operandTypeInference.inferOperandTypes( callBinding, inferredType, operandTypes); } for (int i = 0; i < operands.size(); ++i) { inferUnknownTypes(operandTypes[i], scope, operands.get(i)); } } } /** * Adds an expression to a select list, ensuring that its alias does not * clash with any existing expressions on the list. */ protected void addToSelectList( List<SqlNode> list, Set<String> aliases, List<Map.Entry<String, RelDataType>> fieldList, SqlNode exp, SqlValidatorScope scope, final boolean includeSystemVars) { String alias = SqlValidatorUtil.getAlias(exp, -1); String uniqueAlias = SqlValidatorUtil.uniquify( alias, aliases, SqlValidatorUtil.EXPR_SUGGESTER); if (!alias.equals(uniqueAlias)) { exp = SqlValidatorUtil.addAlias(exp, uniqueAlias); } fieldList.add(Pair.of(uniqueAlias, deriveType(scope, exp))); list.add(exp); } public String deriveAlias( SqlNode node, int ordinal) { return SqlValidatorUtil.getAlias(node, ordinal); } // implement SqlValidator public void setIdentifierExpansion(boolean expandIdentifiers) { this.expandIdentifiers = expandIdentifiers; } // implement SqlValidator public void setColumnReferenceExpansion( boolean expandColumnReferences) { this.expandColumnReferences = expandColumnReferences; } // implement SqlValidator public boolean getColumnReferenceExpansion() { return expandColumnReferences; } public void setDefaultNullCollation(NullCollation nullCollation) { this.nullCollation = Preconditions.checkNotNull(nullCollation); } public NullCollation getDefaultNullCollation() { return nullCollation; } // implement SqlValidator public void setCallRewrite(boolean rewriteCalls) { this.rewriteCalls = rewriteCalls; } public boolean shouldExpandIdentifiers() { return expandIdentifiers; } protected boolean shouldAllowIntermediateOrderBy() { return true; } private void registerMatchRecognize( SqlValidatorScope parentScope, SqlValidatorScope usingScope, SqlMatchRecognize call, SqlNode enclosingNode, String alias, boolean forceNullable) { final MatchRecognizeNamespace matchRecognizeNamespace = createMatchRecognizeNameSpace(call, enclosingNode); registerNamespace(usingScope, alias, matchRecognizeNamespace, forceNullable); final MatchRecognizeScope matchRecognizeScope = new MatchRecognizeScope(parentScope, call); scopes.put(call, matchRecognizeScope); // parse input query SqlNode expr = call.getTableRef(); SqlNode newExpr = registerFrom(usingScope, matchRecognizeScope, expr, expr, null, null, forceNullable); if (expr != newExpr) { call.setOperand(0, newExpr); } } protected MatchRecognizeNamespace createMatchRecognizeNameSpace( SqlMatchRecognize call, SqlNode enclosingNode) { return new MatchRecognizeNamespace(this, call, enclosingNode); } /** * Registers a new namespace, and adds it as a child of its parent scope. * Derived class can override this method to tinker with namespaces as they * are created. * * @param usingScope Parent scope (which will want to look for things in * this namespace) * @param alias Alias by which parent will refer to this namespace * @param ns Namespace * @param forceNullable Whether to force the type of namespace to be nullable */ protected void registerNamespace( SqlValidatorScope usingScope, String alias, SqlValidatorNamespace ns, boolean forceNullable) { namespaces.put(ns.getNode(), ns); if (usingScope != null) { usingScope.addChild(ns, alias, forceNullable); } } /** * Registers scopes and namespaces implied a relational expression in the * FROM clause. * * <p>{@code parentScope} and {@code usingScope} are often the same. They * differ when the namespace are not visible within the parent. (Example * needed.) * * <p>Likewise, {@code enclosingNode} and {@code node} are often the same. * {@code enclosingNode} is the topmost node within the FROM clause, from * which any decorations like an alias (<code>AS alias</code>) or a table * sample clause are stripped away to get {@code node}. Both are recorded in * the namespace. * * @param parentScope Parent scope which this scope turns to in order to * resolve objects * @param usingScope Scope whose child list this scope should add itself to * @param node Node which namespace is based on * @param enclosingNode Outermost node for namespace, including decorations * such as alias and sample clause * @param alias Alias * @param extendList Definitions of extended columns * @param forceNullable Whether to force the type of namespace to be * nullable because it is in an outer join * @return registered node, usually the same as {@code node} */ private SqlNode registerFrom( SqlValidatorScope parentScope, SqlValidatorScope usingScope, final SqlNode node, SqlNode enclosingNode, String alias, SqlNodeList extendList, boolean forceNullable) { final SqlKind kind = node.getKind(); SqlNode expr; SqlNode newExpr; // Add an alias if necessary. SqlNode newNode = node; if (alias == null) { switch (kind) { case IDENTIFIER: case OVER: alias = deriveAlias(node, -1); if (alias == null) { alias = deriveAlias(node, nextGeneratedId++); } if (shouldExpandIdentifiers()) { newNode = SqlValidatorUtil.addAlias(node, alias); } break; case SELECT: case UNION: case INTERSECT: case EXCEPT: case VALUES: case UNNEST: case OTHER_FUNCTION: case COLLECTION_TABLE: case MATCH_RECOGNIZE: // give this anonymous construct a name since later // query processing stages rely on it alias = deriveAlias(node, nextGeneratedId++); if (shouldExpandIdentifiers()) { // Since we're expanding identifiers, we should make the // aliases explicit too, otherwise the expanded query // will not be consistent if we convert back to SQL, e.g. // "select EXPR$1.EXPR$2 from values (1)". newNode = SqlValidatorUtil.addAlias(node, alias); } break; } } SqlCall call; SqlNode operand; SqlNode newOperand; switch (kind) { case AS: call = (SqlCall) node; if (alias == null) { alias = call.operand(1).toString(); } SqlValidatorScope usingScope2 = usingScope; if (call.operandCount() > 2) { usingScope2 = null; } expr = call.operand(0); newExpr = registerFrom( parentScope, usingScope2, expr, enclosingNode, alias, extendList, forceNullable); if (newExpr != expr) { call.setOperand(0, newExpr); } // If alias has a column list, introduce a namespace to translate // column names. if (call.operandCount() > 2) { registerNamespace( usingScope, alias, new AliasNamespace(this, call, enclosingNode), forceNullable); } return node; case MATCH_RECOGNIZE: registerMatchRecognize(parentScope, usingScope, (SqlMatchRecognize) node, enclosingNode, alias, forceNullable); return node; case TABLESAMPLE: call = (SqlCall) node; expr = call.operand(0); newExpr = registerFrom( parentScope, usingScope, expr, enclosingNode, alias, extendList, forceNullable); if (newExpr != expr) { call.setOperand(0, newExpr); } return node; case JOIN: final SqlJoin join = (SqlJoin) node; final JoinScope joinScope = new JoinScope(parentScope, usingScope, join); scopes.put(join, joinScope); final SqlNode left = join.getLeft(); final SqlNode right = join.getRight(); final boolean rightIsLateral = isLateral(right); boolean forceLeftNullable = forceNullable; boolean forceRightNullable = forceNullable; switch (join.getJoinType()) { case LEFT: forceRightNullable = true; break; case RIGHT: forceLeftNullable = true; break; case FULL: forceLeftNullable = true; forceRightNullable = true; break; } final SqlNode newLeft = registerFrom( parentScope, joinScope, left, left, null, null, forceLeftNullable); if (newLeft != left) { join.setLeft(newLeft); } final SqlValidatorScope rightParentScope; if (rightIsLateral) { rightParentScope = joinScope; } else { rightParentScope = parentScope; } final SqlNode newRight = registerFrom( rightParentScope, joinScope, right, right, null, null, forceRightNullable); if (newRight != right) { join.setRight(newRight); } registerSubQueries(joinScope, join.getCondition()); final JoinNamespace joinNamespace = new JoinNamespace(this, join); registerNamespace(null, null, joinNamespace, forceNullable); return join; case IDENTIFIER: final SqlIdentifier id = (SqlIdentifier) node; final IdentifierNamespace newNs = new IdentifierNamespace( this, id, extendList, enclosingNode, parentScope); registerNamespace(usingScope, alias, newNs, forceNullable); if (tableScope == null) { tableScope = new TableScope(parentScope, node); } tableScope.addChild(newNs, alias, forceNullable); if (extendList != null && extendList.size() != 0) { return enclosingNode; } return newNode; case LATERAL: if (tableScope != null) { tableScope.meetLateral(); } return registerFrom( parentScope, usingScope, ((SqlCall) node).operand(0), enclosingNode, alias, extendList, forceNullable); case COLLECTION_TABLE: call = (SqlCall) node; operand = call.operand(0); newOperand = registerFrom( tableScope == null ? parentScope : tableScope, usingScope, operand, enclosingNode, alias, extendList, forceNullable); if (newOperand != operand) { call.setOperand(0, newOperand); } scopes.put(node, parentScope); return newNode; case SELECT: case UNION: case INTERSECT: case EXCEPT: case VALUES: case WITH: case UNNEST: case OTHER_FUNCTION: if (alias == null) { alias = deriveAlias(node, nextGeneratedId++); } registerQuery( parentScope, usingScope, node, enclosingNode, alias, forceNullable); return newNode; case OVER: if (!shouldAllowOverRelation()) { throw Util.unexpected(kind); } call = (SqlCall) node; final OverScope overScope = new OverScope(usingScope, call); scopes.put(call, overScope); operand = call.operand(0); newOperand = registerFrom( parentScope, overScope, operand, enclosingNode, alias, extendList, forceNullable); if (newOperand != operand) { call.setOperand(0, newOperand); } for (ScopeChild child : overScope.children) { registerNamespace(usingScope, child.name, child.namespace, forceNullable); } return newNode; case EXTEND: final SqlCall extend = (SqlCall) node; return registerFrom(parentScope, usingScope, extend.getOperandList().get(0), extend, alias, (SqlNodeList) extend.getOperandList().get(1), forceNullable); default: throw Util.unexpected(kind); } } private static boolean isLateral(SqlNode node) { switch (node.getKind()) { case LATERAL: case UNNEST: // Per SQL std, UNNEST is implicitly LATERAL. return true; case AS: return isLateral(((SqlCall) node).operand(0)); default: return false; } } protected boolean shouldAllowOverRelation() { return false; } /** * Creates a namespace for a <code>SELECT</code> node. Derived class may * override this factory method. * * @param select Select node * @param enclosingNode Enclosing node * @return Select namespace */ protected SelectNamespace createSelectNamespace( SqlSelect select, SqlNode enclosingNode) { return new SelectNamespace(this, select, enclosingNode); } /** * Creates a namespace for a set operation (<code>UNION</code>, <code> * INTERSECT</code>, or <code>EXCEPT</code>). Derived class may override * this factory method. * * @param call Call to set operation * @param enclosingNode Enclosing node * @return Set operation namespace */ protected SetopNamespace createSetopNamespace( SqlCall call, SqlNode enclosingNode) { return new SetopNamespace(this, call, enclosingNode); } /** * Registers a query in a parent scope. * * @param parentScope Parent scope which this scope turns to in order to * resolve objects * @param usingScope Scope whose child list this scope should add itself to * @param node Query node * @param alias Name of this query within its parent. Must be specified * if usingScope != null */ private void registerQuery( SqlValidatorScope parentScope, SqlValidatorScope usingScope, SqlNode node, SqlNode enclosingNode, String alias, boolean forceNullable) { Preconditions.checkArgument(usingScope == null || alias != null); registerQuery( parentScope, usingScope, node, enclosingNode, alias, forceNullable, true); } /** * Registers a query in a parent scope. * * @param parentScope Parent scope which this scope turns to in order to * resolve objects * @param usingScope Scope whose child list this scope should add itself to * @param node Query node * @param alias Name of this query within its parent. Must be specified * if usingScope != null * @param checkUpdate if true, validate that the update feature is supported * if validating the update statement */ private void registerQuery( SqlValidatorScope parentScope, SqlValidatorScope usingScope, SqlNode node, SqlNode enclosingNode, String alias, boolean forceNullable, boolean checkUpdate) { Preconditions.checkNotNull(node); Preconditions.checkNotNull(enclosingNode); Preconditions.checkArgument(usingScope == null || alias != null); SqlCall call; List<SqlNode> operands; switch (node.getKind()) { case SELECT: final SqlSelect select = (SqlSelect) node; final SelectNamespace selectNs = createSelectNamespace(select, enclosingNode); registerNamespace(usingScope, alias, selectNs, forceNullable); final SqlValidatorScope windowParentScope = (usingScope != null) ? usingScope : parentScope; SelectScope selectScope = new SelectScope(parentScope, windowParentScope, select); scopes.put(select, selectScope); // Start by registering the WHERE clause whereScopes.put(select, selectScope); registerOperandSubQueries( selectScope, select, SqlSelect.WHERE_OPERAND); // Register FROM with the inherited scope 'parentScope', not // 'selectScope', otherwise tables in the FROM clause would be // able to see each other. final SqlNode from = select.getFrom(); if (from != null) { final SqlNode newFrom = registerFrom( parentScope, selectScope, from, from, null, null, false); if (newFrom != from) { select.setFrom(newFrom); } } // If this is an aggregating query, the SELECT list and HAVING // clause use a different scope, where you can only reference // columns which are in the GROUP BY clause. SqlValidatorScope aggScope = selectScope; if (isAggregate(select)) { aggScope = new AggregatingSelectScope(selectScope, select, false); selectScopes.put(select, aggScope); } else { selectScopes.put(select, selectScope); } if (select.getGroup() != null) { GroupByScope groupByScope = new GroupByScope(selectScope, select.getGroup(), select); groupByScopes.put(select, groupByScope); registerSubQueries(groupByScope, select.getGroup()); } registerOperandSubQueries( aggScope, select, SqlSelect.HAVING_OPERAND); registerSubQueries(aggScope, select.getSelectList()); final SqlNodeList orderList = select.getOrderList(); if (orderList != null) { // If the query is 'SELECT DISTINCT', restrict the columns // available to the ORDER BY clause. if (select.isDistinct()) { aggScope = new AggregatingSelectScope(selectScope, select, true); } OrderByScope orderScope = new OrderByScope(aggScope, orderList, select); orderScopes.put(select, orderScope); registerSubQueries(orderScope, orderList); if (!isAggregate(select)) { // Since this is not an aggregating query, // there cannot be any aggregates in the ORDER BY clause. SqlNode agg = aggFinder.findAgg(orderList); if (agg != null) { throw newValidationError(agg, RESOURCE.aggregateIllegalInOrderBy()); } } } break; case INTERSECT: validateFeature(RESOURCE.sQLFeature_F302(), node.getParserPosition()); registerSetop( parentScope, usingScope, node, node, alias, forceNullable); break; case EXCEPT: validateFeature(RESOURCE.sQLFeature_E071_03(), node.getParserPosition()); registerSetop( parentScope, usingScope, node, node, alias, forceNullable); break; case UNION: registerSetop( parentScope, usingScope, node, node, alias, forceNullable); break; case WITH: registerWith(parentScope, usingScope, (SqlWith) node, enclosingNode, alias, forceNullable, checkUpdate); break; case VALUES: call = (SqlCall) node; scopes.put(call, parentScope); final TableConstructorNamespace tableConstructorNamespace = new TableConstructorNamespace( this, call, parentScope, enclosingNode); registerNamespace( usingScope, alias, tableConstructorNamespace, forceNullable); operands = call.getOperandList(); for (int i = 0; i < operands.size(); ++i) { assert operands.get(i).getKind() == SqlKind.ROW; // FIXME jvs 9-Feb-2005: Correlation should // be illegal in these sub-queries. Same goes for // any non-lateral SELECT in the FROM list. registerOperandSubQueries(parentScope, call, i); } break; case INSERT: SqlInsert insertCall = (SqlInsert) node; InsertNamespace insertNs = new InsertNamespace( this, insertCall, enclosingNode, parentScope); registerNamespace(usingScope, null, insertNs, forceNullable); registerQuery( parentScope, usingScope, insertCall.getSource(), enclosingNode, null, false); break; case DELETE: SqlDelete deleteCall = (SqlDelete) node; DeleteNamespace deleteNs = new DeleteNamespace( this, deleteCall, enclosingNode, parentScope); registerNamespace(usingScope, null, deleteNs, forceNullable); registerQuery( parentScope, usingScope, deleteCall.getSourceSelect(), enclosingNode, null, false); break; case UPDATE: if (checkUpdate) { validateFeature(RESOURCE.sQLFeature_E101_03(), node.getParserPosition()); } SqlUpdate updateCall = (SqlUpdate) node; UpdateNamespace updateNs = new UpdateNamespace( this, updateCall, enclosingNode, parentScope); registerNamespace(usingScope, null, updateNs, forceNullable); registerQuery( parentScope, usingScope, updateCall.getSourceSelect(), enclosingNode, null, false); break; case MERGE: validateFeature(RESOURCE.sQLFeature_F312(), node.getParserPosition()); SqlMerge mergeCall = (SqlMerge) node; MergeNamespace mergeNs = new MergeNamespace( this, mergeCall, enclosingNode, parentScope); registerNamespace(usingScope, null, mergeNs, forceNullable); registerQuery( parentScope, usingScope, mergeCall.getSourceSelect(), enclosingNode, null, false); // update call can reference either the source table reference // or the target table, so set its parent scope to the merge's // source select; when validating the update, skip the feature // validation check if (mergeCall.getUpdateCall() != null) { registerQuery( whereScopes.get(mergeCall.getSourceSelect()), null, mergeCall.getUpdateCall(), enclosingNode, null, false, false); } if (mergeCall.getInsertCall() != null) { registerQuery( parentScope, null, mergeCall.getInsertCall(), enclosingNode, null, false); } break; case UNNEST: call = (SqlCall) node; final UnnestNamespace unnestNs = new UnnestNamespace(this, call, parentScope, enclosingNode); registerNamespace( usingScope, alias, unnestNs, forceNullable); registerOperandSubQueries(parentScope, call, 0); scopes.put(node, parentScope); break; case OTHER_FUNCTION: call = (SqlCall) node; ProcedureNamespace procNs = new ProcedureNamespace( this, parentScope, call, enclosingNode); registerNamespace( usingScope, alias, procNs, forceNullable); registerSubQueries(parentScope, call); break; case MULTISET_QUERY_CONSTRUCTOR: case MULTISET_VALUE_CONSTRUCTOR: validateFeature(RESOURCE.sQLFeature_S271(), node.getParserPosition()); call = (SqlCall) node; CollectScope cs = new CollectScope(parentScope, usingScope, call); final CollectNamespace tableConstructorNs = new CollectNamespace(call, cs, enclosingNode); final String alias2 = deriveAlias(node, nextGeneratedId++); registerNamespace( usingScope, alias2, tableConstructorNs, forceNullable); operands = call.getOperandList(); for (int i = 0; i < operands.size(); i++) { registerOperandSubQueries(parentScope, call, i); } break; default: throw Util.unexpected(node.getKind()); } } private void registerSetop( SqlValidatorScope parentScope, SqlValidatorScope usingScope, SqlNode node, SqlNode enclosingNode, String alias, boolean forceNullable) { SqlCall call = (SqlCall) node; final SetopNamespace setopNamespace = createSetopNamespace(call, enclosingNode); registerNamespace(usingScope, alias, setopNamespace, forceNullable); // A setop is in the same scope as its parent. scopes.put(call, parentScope); for (SqlNode operand : call.getOperandList()) { registerQuery( parentScope, null, operand, operand, null, false); } } private void registerWith( SqlValidatorScope parentScope, SqlValidatorScope usingScope, SqlWith with, SqlNode enclosingNode, String alias, boolean forceNullable, boolean checkUpdate) { final WithNamespace withNamespace = new WithNamespace(this, with, enclosingNode); registerNamespace(usingScope, alias, withNamespace, forceNullable); SqlValidatorScope scope = parentScope; for (SqlNode withItem_ : with.withList) { final SqlWithItem withItem = (SqlWithItem) withItem_; final WithScope withScope = new WithScope(scope, withItem); scopes.put(withItem, withScope); registerQuery(scope, null, withItem.query, with, withItem.name.getSimple(), false); registerNamespace(null, alias, new WithItemNamespace(this, withItem, enclosingNode), false); scope = withScope; } registerQuery(scope, null, with.body, enclosingNode, alias, forceNullable, checkUpdate); } public boolean isAggregate(SqlSelect select) { if (getAggregate(select) != null) { return true; } // Also when nested window aggregates are present for (SqlNode node : select.getSelectList()) { if (node instanceof SqlCall) { SqlCall call = (SqlCall) overFinder.findAgg(node); if (call != null && call.getOperator().getKind() == SqlKind.OVER && call.getOperandList().size() != 0) { if (call.operand(0) instanceof SqlCall && isNestedAggregateWindow((SqlCall) call.operand(0))) { return true; } } } } return false; } protected boolean isNestedAggregateWindow(SqlCall windowFunction) { AggFinder nestedAggFinder = new AggFinder(opTab, false, false, false, aggFinder); return nestedAggFinder.findAgg(windowFunction) != null; } /** Returns the parse tree node (GROUP BY, HAVING, or an aggregate function * call) that causes {@code select} to be an aggregate query, or null if it is * not an aggregate query. * * <p>The node is useful context for error messages. */ protected SqlNode getAggregate(SqlSelect select) { SqlNode node = select.getGroup(); if (node != null) { return node; } node = select.getHaving(); if (node != null) { return node; } return getAgg(select); } private SqlNode getAgg(SqlSelect select) { final SelectScope selectScope = getRawSelectScope(select); if (selectScope != null) { final List<SqlNode> selectList = selectScope.getExpandedSelectList(); if (selectList != null) { return aggFinder.findAgg(selectList); } } return aggFinder.findAgg(select.getSelectList()); } @SuppressWarnings("deprecation") public boolean isAggregate(SqlNode selectNode) { return aggFinder.findAgg(selectNode) != null; } private void validateNodeFeature(SqlNode node) { switch (node.getKind()) { case MULTISET_VALUE_CONSTRUCTOR: validateFeature(RESOURCE.sQLFeature_S271(), node.getParserPosition()); break; } } private void registerSubQueries( SqlValidatorScope parentScope, SqlNode node) { if (node == null) { return; } if (node.getKind().belongsTo(SqlKind.QUERY) || node.getKind() == SqlKind.MULTISET_QUERY_CONSTRUCTOR || node.getKind() == SqlKind.MULTISET_VALUE_CONSTRUCTOR) { registerQuery(parentScope, null, node, node, null, false); } else if (node instanceof SqlCall) { validateNodeFeature(node); SqlCall call = (SqlCall) node; for (int i = 0; i < call.operandCount(); i++) { registerOperandSubQueries(parentScope, call, i); } } else if (node instanceof SqlNodeList) { SqlNodeList list = (SqlNodeList) node; for (int i = 0, count = list.size(); i < count; i++) { SqlNode listNode = list.get(i); if (listNode.getKind().belongsTo(SqlKind.QUERY)) { listNode = SqlStdOperatorTable.SCALAR_QUERY.createCall( listNode.getParserPosition(), listNode); list.set(i, listNode); } registerSubQueries(parentScope, listNode); } } else { // atomic node -- can be ignored } } /** * Registers any sub-queries inside a given call operand, and converts the * operand to a scalar sub-query if the operator requires it. * * @param parentScope Parent scope * @param call Call * @param operandOrdinal Ordinal of operand within call * @see SqlOperator#argumentMustBeScalar(int) */ private void registerOperandSubQueries( SqlValidatorScope parentScope, SqlCall call, int operandOrdinal) { SqlNode operand = call.operand(operandOrdinal); if (operand == null) { return; } if (operand.getKind().belongsTo(SqlKind.QUERY) && call.getOperator().argumentMustBeScalar(operandOrdinal)) { operand = SqlStdOperatorTable.SCALAR_QUERY.createCall( operand.getParserPosition(), operand); call.setOperand(operandOrdinal, operand); } registerSubQueries(parentScope, operand); } public void validateIdentifier(SqlIdentifier id, SqlValidatorScope scope) { final SqlQualified fqId = scope.fullyQualify(id); if (expandColumnReferences) { // NOTE jvs 9-Apr-2007: this doesn't cover ORDER BY, which has its // own ideas about qualification. id.assignNamesFrom(fqId.identifier); } else { Util.discard(fqId); } } public void validateLiteral(SqlLiteral literal) { switch (literal.getTypeName()) { case DECIMAL: // Decimal and long have the same precision (as 64-bit integers), so // the unscaled value of a decimal must fit into a long. // REVIEW jvs 4-Aug-2004: This should probably be calling over to // the available calculator implementations to see what they // support. For now use ESP instead. // // jhyde 2006/12/21: I think the limits should be baked into the // type system, not dependent on the calculator implementation. BigDecimal bd = (BigDecimal) literal.getValue(); BigInteger unscaled = bd.unscaledValue(); long longValue = unscaled.longValue(); if (!BigInteger.valueOf(longValue).equals(unscaled)) { // overflow throw newValidationError(literal, RESOURCE.numberLiteralOutOfRange(bd.toString())); } break; case DOUBLE: validateLiteralAsDouble(literal); break; case BINARY: final BitString bitString = (BitString) literal.getValue(); if ((bitString.getBitCount() % 8) != 0) { throw newValidationError(literal, RESOURCE.binaryLiteralOdd()); } break; case DATE: case TIME: case TIMESTAMP: Calendar calendar = literal.getValueAs(Calendar.class); final int year = calendar.get(Calendar.YEAR); final int era = calendar.get(Calendar.ERA); if (year < 1 || era == GregorianCalendar.BC || year > 9999) { throw newValidationError(literal, RESOURCE.dateLiteralOutOfRange(literal.toString())); } break; case INTERVAL_YEAR: case INTERVAL_YEAR_MONTH: case INTERVAL_MONTH: case INTERVAL_DAY: case INTERVAL_DAY_HOUR: case INTERVAL_DAY_MINUTE: case INTERVAL_DAY_SECOND: case INTERVAL_HOUR: case INTERVAL_HOUR_MINUTE: case INTERVAL_HOUR_SECOND: case INTERVAL_MINUTE: case INTERVAL_MINUTE_SECOND: case INTERVAL_SECOND: if (literal instanceof SqlIntervalLiteral) { SqlIntervalLiteral.IntervalValue interval = (SqlIntervalLiteral.IntervalValue) literal.getValue(); SqlIntervalQualifier intervalQualifier = interval.getIntervalQualifier(); // ensure qualifier is good before attempting to validate literal validateIntervalQualifier(intervalQualifier); String intervalStr = interval.getIntervalLiteral(); // throws CalciteContextException if string is invalid int[] values = intervalQualifier.evaluateIntervalLiteral(intervalStr, literal.getParserPosition(), typeFactory.getTypeSystem()); Util.discard(values); } break; default: // default is to do nothing } } private void validateLiteralAsDouble(SqlLiteral literal) { BigDecimal bd = (BigDecimal) literal.getValue(); double d = bd.doubleValue(); if (Double.isInfinite(d) || Double.isNaN(d)) { // overflow throw newValidationError(literal, RESOURCE.numberLiteralOutOfRange(Util.toScientificNotation(bd))); } // REVIEW jvs 4-Aug-2004: what about underflow? } public void validateIntervalQualifier(SqlIntervalQualifier qualifier) { assert qualifier != null; boolean startPrecisionOutOfRange = false; boolean fractionalSecondPrecisionOutOfRange = false; final RelDataTypeSystem typeSystem = typeFactory.getTypeSystem(); final int startPrecision = qualifier.getStartPrecision(typeSystem); final int fracPrecision = qualifier.getFractionalSecondPrecision(typeSystem); final int maxPrecision = typeSystem.getMaxPrecision(qualifier.typeName()); final int minPrecision = qualifier.typeName().getMinPrecision(); final int minScale = qualifier.typeName().getMinScale(); final int maxScale = typeSystem.getMaxScale(qualifier.typeName()); if (qualifier.isYearMonth()) { if (startPrecision < minPrecision || startPrecision > maxPrecision) { startPrecisionOutOfRange = true; } else { if (fracPrecision < minScale || fracPrecision > maxScale) { fractionalSecondPrecisionOutOfRange = true; } } } else { if (startPrecision < minPrecision || startPrecision > maxPrecision) { startPrecisionOutOfRange = true; } else { if (fracPrecision < minScale || fracPrecision > maxScale) { fractionalSecondPrecisionOutOfRange = true; } } } if (startPrecisionOutOfRange) { throw newValidationError(qualifier, RESOURCE.intervalStartPrecisionOutOfRange(startPrecision, "INTERVAL " + qualifier)); } else if (fractionalSecondPrecisionOutOfRange) { throw newValidationError(qualifier, RESOURCE.intervalFractionalSecondPrecisionOutOfRange( fracPrecision, "INTERVAL " + qualifier)); } } /** * Validates the FROM clause of a query, or (recursively) a child node of * the FROM clause: AS, OVER, JOIN, VALUES, or sub-query. * * @param node Node in FROM clause, typically a table or derived * table * @param targetRowType Desired row type of this expression, or * {@link #unknownType} if not fussy. Must not be null. * @param scope Scope */ protected void validateFrom( SqlNode node, RelDataType targetRowType, SqlValidatorScope scope) { Preconditions.checkNotNull(targetRowType); switch (node.getKind()) { case AS: validateFrom( ((SqlCall) node).operand(0), targetRowType, scope); break; case VALUES: validateValues((SqlCall) node, targetRowType, scope); break; case JOIN: validateJoin((SqlJoin) node, scope); break; case OVER: validateOver((SqlCall) node, scope); break; default: validateQuery(node, scope, targetRowType); break; } // Validate the namespace representation of the node, just in case the // validation did not occur implicitly. getNamespace(node, scope).validate(targetRowType); } protected void validateOver(SqlCall call, SqlValidatorScope scope) { throw new AssertionError("OVER unexpected in this context"); } private void checkRollUpInUsing(SqlIdentifier identifier, SqlNode leftOrRight) { leftOrRight = stripAs(leftOrRight); // if it's not a SqlIdentifier then that's fine, it'll be validated somewhere else. if (leftOrRight instanceof SqlIdentifier) { SqlIdentifier from = (SqlIdentifier) leftOrRight; Table table = findTable(catalogReader.getRootSchema(), Util.last(from.names), catalogReader.nameMatcher().isCaseSensitive()); String name = Util.last(identifier.names); if (table != null && table.isRolledUp(name)) { throw newValidationError(identifier, RESOURCE.rolledUpNotAllowed(name, "USING")); } } } protected void validateJoin(SqlJoin join, SqlValidatorScope scope) { SqlNode left = join.getLeft(); SqlNode right = join.getRight(); SqlNode condition = join.getCondition(); boolean natural = join.isNatural(); final JoinType joinType = join.getJoinType(); final JoinConditionType conditionType = join.getConditionType(); final SqlValidatorScope joinScope = scopes.get(join); validateFrom(left, unknownType, joinScope); validateFrom(right, unknownType, joinScope); // Validate condition. switch (conditionType) { case NONE: Preconditions.checkArgument(condition == null); break; case ON: Preconditions.checkArgument(condition != null); SqlNode expandedCondition = expand(condition, joinScope); join.setOperand(5, expandedCondition); condition = join.getCondition(); validateWhereOrOn(joinScope, condition, "ON"); checkRollUp(null, join, condition, joinScope, "ON"); break; case USING: SqlNodeList list = (SqlNodeList) condition; // Parser ensures that using clause is not empty. Preconditions.checkArgument(list.size() > 0, "Empty USING clause"); for (int i = 0; i < list.size(); i++) { SqlIdentifier id = (SqlIdentifier) list.get(i); final RelDataType leftColType = validateUsingCol(id, left); final RelDataType rightColType = validateUsingCol(id, right); if (!SqlTypeUtil.isComparable(leftColType, rightColType)) { throw newValidationError(id, RESOURCE.naturalOrUsingColumnNotCompatible(id.getSimple(), leftColType.toString(), rightColType.toString())); } checkRollUpInUsing(id, left); checkRollUpInUsing(id, right); } break; default: throw Util.unexpected(conditionType); } // Validate NATURAL. if (natural) { if (condition != null) { throw newValidationError(condition, RESOURCE.naturalDisallowsOnOrUsing()); } // Join on fields that occur exactly once on each side. Ignore // fields that occur more than once on either side. final RelDataType leftRowType = getNamespace(left).getRowType(); final RelDataType rightRowType = getNamespace(right).getRowType(); List<String> naturalColumnNames = SqlValidatorUtil.deriveNaturalJoinColumnList( leftRowType, rightRowType); // Check compatibility of the chosen columns. final SqlNameMatcher nameMatcher = catalogReader.nameMatcher(); for (String name : naturalColumnNames) { final RelDataType leftColType = nameMatcher.field(leftRowType, name).getType(); final RelDataType rightColType = nameMatcher.field(rightRowType, name).getType(); if (!SqlTypeUtil.isComparable(leftColType, rightColType)) { throw newValidationError(join, RESOURCE.naturalOrUsingColumnNotCompatible(name, leftColType.toString(), rightColType.toString())); } } } // Which join types require/allow a ON/USING condition, or allow // a NATURAL keyword? switch (joinType) { case INNER: case LEFT: case RIGHT: case FULL: if ((condition == null) && !natural) { throw newValidationError(join, RESOURCE.joinRequiresCondition()); } break; case COMMA: case CROSS: if (condition != null) { throw newValidationError(join.getConditionTypeNode(), RESOURCE.crossJoinDisallowsCondition()); } if (natural) { throw newValidationError(join.getConditionTypeNode(), RESOURCE.crossJoinDisallowsCondition()); } break; default: throw Util.unexpected(joinType); } } /** * Throws an error if there is an aggregate or windowed aggregate in the * given clause. * * @param aggFinder Finder for the particular kind(s) of aggregate function * @param node Parse tree * @param clause Name of clause: "WHERE", "GROUP BY", "ON" */ private void validateNoAggs(AggFinder aggFinder, SqlNode node, String clause) { final SqlCall agg = aggFinder.findAgg(node); if (agg == null) { return; } final SqlOperator op = agg.getOperator(); if (op == SqlStdOperatorTable.OVER) { throw newValidationError(agg, RESOURCE.windowedAggregateIllegalInClause(clause)); } else if (op.isGroup() || op.isGroupAuxiliary()) { throw newValidationError(agg, RESOURCE.groupFunctionMustAppearInGroupByClause(op.getName())); } else { throw newValidationError(agg, RESOURCE.aggregateIllegalInClause(clause)); } } private RelDataType validateUsingCol(SqlIdentifier id, SqlNode leftOrRight) { if (id.names.size() == 1) { String name = id.names.get(0); final SqlValidatorNamespace namespace = getNamespace(leftOrRight); final RelDataType rowType = namespace.getRowType(); final SqlNameMatcher nameMatcher = catalogReader.nameMatcher(); final RelDataTypeField field = nameMatcher.field(rowType, name); if (field != null) { if (Collections.frequency(rowType.getFieldNames(), name) > 1) { throw newValidationError(id, RESOURCE.columnInUsingNotUnique(id.toString())); } return field.getType(); } } throw newValidationError(id, RESOURCE.columnNotFound(id.toString())); } /** * Validates a SELECT statement. * * @param select Select statement * @param targetRowType Desired row type, must not be null, may be the data * type 'unknown'. */ protected void validateSelect( SqlSelect select, RelDataType targetRowType) { assert targetRowType != null; // Namespace is either a select namespace or a wrapper around one. final SelectNamespace ns = getNamespace(select).unwrap(SelectNamespace.class); // Its rowtype is null, meaning it hasn't been validated yet. // This is important, because we need to take the targetRowType into // account. assert ns.rowType == null; if (select.isDistinct()) { validateFeature(RESOURCE.sQLFeature_E051_01(), select.getModifierNode(SqlSelectKeyword.DISTINCT) .getParserPosition()); } final SqlNodeList selectItems = select.getSelectList(); RelDataType fromType = unknownType; if (selectItems.size() == 1) { final SqlNode selectItem = selectItems.get(0); if (selectItem instanceof SqlIdentifier) { SqlIdentifier id = (SqlIdentifier) selectItem; if (id.isStar() && (id.names.size() == 1)) { // Special case: for INSERT ... VALUES(?,?), the SQL // standard says we're supposed to propagate the target // types down. So iff the select list is an unqualified // star (as it will be after an INSERT ... VALUES has been // expanded), then propagate. fromType = targetRowType; } } } // Make sure that items in FROM clause have distinct aliases. final SelectScope fromScope = (SelectScope) getFromScope(select); List<String> names = fromScope.getChildNames(); if (!catalogReader.nameMatcher().isCaseSensitive()) { names = Lists.transform(names, new Function<String, String>() { public String apply(String s) { return s.toUpperCase(Locale.ROOT); } }); } final int duplicateAliasOrdinal = Util.firstDuplicate(names); if (duplicateAliasOrdinal >= 0) { final ScopeChild child = fromScope.children.get(duplicateAliasOrdinal); throw newValidationError(child.namespace.getEnclosingNode(), RESOURCE.fromAliasDuplicate(child.name)); } if (select.getFrom() == null) { if (conformance.isFromRequired()) { throw newValidationError(select, RESOURCE.selectMissingFrom()); } } else { validateFrom(select.getFrom(), fromType, fromScope); } validateWhereClause(select); validateGroupClause(select); validateHavingClause(select); validateWindowClause(select); // Validate the SELECT clause late, because a select item might // depend on the GROUP BY list, or the window function might reference // window name in the WINDOW clause etc. final RelDataType rowType = validateSelectList(selectItems, select, targetRowType); ns.setType(rowType); // Validate ORDER BY after we have set ns.rowType because in some // dialects you can refer to columns of the select list, e.g. // "SELECT empno AS x FROM emp ORDER BY x" validateOrderList(select); if (shouldCheckForRollUp(select.getFrom())) { checkRollUpInSelectList(select); checkRollUp(null, select, select.getWhere(), getWhereScope(select)); checkRollUp(null, select, select.getHaving(), getHavingScope(select)); checkRollUpInWindowDecl(select); checkRollUpInGroupBy(select); checkRollUpInOrderBy(select); } } private void checkRollUpInSelectList(SqlSelect select) { SqlValidatorScope scope = getSelectScope(select); for (SqlNode item : select.getSelectList()) { checkRollUp(null, select, item, scope); } } private void checkRollUpInGroupBy(SqlSelect select) { SqlNodeList group = select.getGroup(); if (group != null) { for (SqlNode node : group) { checkRollUp(null, select, node, getGroupScope(select), "GROUP BY"); } } } private void checkRollUpInOrderBy(SqlSelect select) { SqlNodeList orderList = select.getOrderList(); if (orderList != null) { for (SqlNode node : orderList) { checkRollUp(null, select, node, getOrderScope(select), "ORDER BY"); } } } private void checkRollUpInWindow(SqlWindow window, SqlValidatorScope scope) { if (window != null) { for (SqlNode node : window.getPartitionList()) { checkRollUp(null, window, node, scope, "PARTITION BY"); } for (SqlNode node : window.getOrderList()) { checkRollUp(null, window, node, scope, "ORDER BY"); } } } private void checkRollUpInWindowDecl(SqlSelect select) { for (SqlNode decl : select.getWindowList()) { checkRollUpInWindow((SqlWindow) decl, getSelectScope(select)); } } private void checkRollUp(SqlNode grandParent, SqlNode parent, SqlNode current, SqlValidatorScope scope, String optionalClause) { current = stripAs(current); if (current instanceof SqlCall && !(current instanceof SqlSelect)) { // Validate OVER separately checkRollUpInWindow(getWindowInOver(current), scope); current = stripOver(current); List<SqlNode> children = ((SqlCall) current).getOperandList(); for (SqlNode child : children) { checkRollUp(parent, current, child, scope, optionalClause); } } else if (current instanceof SqlIdentifier) { SqlIdentifier id = (SqlIdentifier) current; if (!id.isStar() && isRolledUpColumn(id, scope)) { if (!isAggregation(parent.getKind()) || !isRolledUpColumnAllowedInAgg(id, scope, (SqlCall) parent, grandParent)) { String context = optionalClause != null ? optionalClause : parent.getKind().toString(); throw newValidationError(id, RESOURCE.rolledUpNotAllowed(deriveAlias(id, 0), context)); } } } } private void checkRollUp(SqlNode grandParent, SqlNode parent, SqlNode current, SqlValidatorScope scope) { checkRollUp(grandParent, parent, current, scope, null); } private SqlWindow getWindowInOver(SqlNode over) { if (over.getKind() == SqlKind.OVER) { SqlNode window = ((SqlCall) over).getOperandList().get(1); if (window instanceof SqlWindow) { return (SqlWindow) window; } // SqlIdentifier, gets validated elsewhere return null; } return null; } private static SqlNode stripOver(SqlNode node) { switch (node.getKind()) { case OVER: return ((SqlCall) node).getOperandList().get(0); default: return node; } } private Pair<String, String> findTableColumnPair(SqlIdentifier identifier, SqlValidatorScope scope) { SqlCall call = SqlUtil.makeCall(getOperatorTable(), identifier); if (call != null) { return null; } SqlQualified qualified = scope.fullyQualify(identifier); List<String> names = qualified.identifier.names; if (names.size() < 2) { return null; } return new Pair<>(names.get(names.size() - 2), Util.last(names)); } // Returns true iff the given column is valid inside the given aggCall. private boolean isRolledUpColumnAllowedInAgg(SqlIdentifier identifier, SqlValidatorScope scope, SqlCall aggCall, SqlNode parent) { Pair<String, String> pair = findTableColumnPair(identifier, scope); if (pair == null) { return true; } String tableAlias = pair.left; String columnName = pair.right; Table table = findTable(tableAlias); if (table != null) { return table.rolledUpColumnValidInsideAgg(columnName, aggCall, parent, catalogReader.getConfig()); } return true; } // Returns true iff the given column is actually rolled up. private boolean isRolledUpColumn(SqlIdentifier identifier, SqlValidatorScope scope) { Pair<String, String> pair = findTableColumnPair(identifier, scope); if (pair == null) { return false; } String tableAlias = pair.left; String columnName = pair.right; Table table = findTable(tableAlias); if (table != null) { return table.isRolledUp(columnName); } return false; } private Table findTable(CalciteSchema schema, String tableName, boolean caseSensitive) { CalciteSchema.TableEntry entry = schema.getTable(tableName, caseSensitive); if (entry != null) { return entry.getTable(); } // Check sub schemas for (CalciteSchema subSchema : schema.getSubSchemaMap().values()) { Table table = findTable(subSchema, tableName, caseSensitive); if (table != null) { return table; } } return null; } /** * Given a table alias, find the corresponding {@link Table} associated with it * */ private Table findTable(String alias) { List<String> names = null; if (tableScope == null) { // no tables to find return null; } for (ScopeChild child : tableScope.children) { if (catalogReader.nameMatcher().matches(child.name, alias)) { names = ((SqlIdentifier) child.namespace.getNode()).names; break; } } if (names == null || names.size() == 0) { return null; } else if (names.size() == 1) { return findTable(catalogReader.getRootSchema(), names.get(0), catalogReader.nameMatcher().isCaseSensitive()); } String schemaName = names.get(0); String tableName = names.get(1); CalciteSchema schema = catalogReader.getRootSchema().getSubSchemaMap().get(schemaName); if (schema == null) { return null; } CalciteSchema.TableEntry entry = schema.getTable(tableName, catalogReader.nameMatcher().isCaseSensitive()); return entry == null ? null : entry.getTable(); } private boolean shouldCheckForRollUp(SqlNode from) { if (from != null) { SqlKind kind = stripAs(from).getKind(); return kind != SqlKind.VALUES && kind != SqlKind.SELECT; } return false; } /** Validates that a query can deliver the modality it promises. Only called * on the top-most SELECT or set operator in the tree. */ private void validateModality(SqlNode query) { final SqlModality modality = deduceModality(query); if (query instanceof SqlSelect) { final SqlSelect select = (SqlSelect) query; validateModality(select, modality, true); } else if (query.getKind() == SqlKind.VALUES) { switch (modality) { case STREAM: throw newValidationError(query, Static.RESOURCE.cannotStreamValues()); } } else { assert query.isA(SqlKind.SET_QUERY); final SqlCall call = (SqlCall) query; for (SqlNode operand : call.getOperandList()) { if (deduceModality(operand) != modality) { throw newValidationError(operand, Static.RESOURCE.streamSetOpInconsistentInputs()); } validateModality(operand); } } } /** Return the intended modality of a SELECT or set-op. */ private SqlModality deduceModality(SqlNode query) { if (query instanceof SqlSelect) { SqlSelect select = (SqlSelect) query; return select.getModifierNode(SqlSelectKeyword.STREAM) != null ? SqlModality.STREAM : SqlModality.RELATION; } else if (query.getKind() == SqlKind.VALUES) { return SqlModality.RELATION; } else { assert query.isA(SqlKind.SET_QUERY); final SqlCall call = (SqlCall) query; return deduceModality(call.getOperandList().get(0)); } } public boolean validateModality(SqlSelect select, SqlModality modality, boolean fail) { final SelectScope scope = getRawSelectScope(select); switch (modality) { case STREAM: if (scope.children.size() == 1) { for (ScopeChild child : scope.children) { if (!child.namespace.supportsModality(modality)) { if (fail) { throw newValidationError(child.namespace.getNode(), Static.RESOURCE.cannotConvertToStream(child.name)); } else { return false; } } } } else { int supportsModalityCount = 0; for (ScopeChild child : scope.children) { if (child.namespace.supportsModality(modality)) { ++supportsModalityCount; } } if (supportsModalityCount == 0) { if (fail) { String inputs = Joiner.on(", ").join(scope.getChildNames()); throw newValidationError(select, Static.RESOURCE.cannotStreamResultsForNonStreamingInputs(inputs)); } else { return false; } } } break; default: for (ScopeChild child : scope.children) { if (!child.namespace.supportsModality(modality)) { if (fail) { throw newValidationError(child.namespace.getNode(), Static.RESOURCE.cannotConvertToRelation(child.name)); } else { return false; } } } } // Make sure that aggregation is possible. final SqlNode aggregateNode = getAggregate(select); if (aggregateNode != null) { switch (modality) { case STREAM: SqlNodeList groupList = select.getGroup(); if (groupList == null || !SqlValidatorUtil.containsMonotonic(scope, groupList)) { if (fail) { throw newValidationError(aggregateNode, Static.RESOURCE.streamMustGroupByMonotonic()); } else { return false; } } } } // Make sure that ORDER BY is possible. final SqlNodeList orderList = select.getOrderList(); if (orderList != null && orderList.size() > 0) { switch (modality) { case STREAM: if (!hasSortedPrefix(scope, orderList)) { if (fail) { throw newValidationError(orderList.get(0), Static.RESOURCE.streamMustOrderByMonotonic()); } else { return false; } } } } return true; } /** Returns whether the prefix is sorted. */ private boolean hasSortedPrefix(SelectScope scope, SqlNodeList orderList) { return isSortCompatible(scope, orderList.get(0), false); } private boolean isSortCompatible(SelectScope scope, SqlNode node, boolean descending) { switch (node.getKind()) { case DESCENDING: return isSortCompatible(scope, ((SqlCall) node).getOperandList().get(0), true); } final SqlMonotonicity monotonicity = scope.getMonotonicity(node); switch (monotonicity) { case INCREASING: case STRICTLY_INCREASING: return !descending; case DECREASING: case STRICTLY_DECREASING: return descending; default: return false; } } protected void validateWindowClause(SqlSelect select) { final SqlNodeList windowList = select.getWindowList(); @SuppressWarnings("unchecked") final List<SqlWindow> windows = (List) windowList.getList(); if (windows.isEmpty()) { return; } final SelectScope windowScope = (SelectScope) getFromScope(select); assert windowScope != null; // 1. ensure window names are simple // 2. ensure they are unique within this scope for (SqlWindow window : windows) { SqlIdentifier declName = window.getDeclName(); if (!declName.isSimple()) { throw newValidationError(declName, RESOURCE.windowNameMustBeSimple()); } if (windowScope.existingWindowName(declName.toString())) { throw newValidationError(declName, RESOURCE.duplicateWindowName()); } else { windowScope.addWindowName(declName.toString()); } } // 7.10 rule 2 // Check for pairs of windows which are equivalent. for (int i = 0; i < windows.size(); i++) { SqlNode window1 = windows.get(i); for (int j = i + 1; j < windows.size(); j++) { SqlNode window2 = windows.get(j); if (window1.equalsDeep(window2, Litmus.IGNORE)) { throw newValidationError(window2, RESOURCE.dupWindowSpec()); } } } for (SqlWindow window : windows) { final SqlNodeList expandedOrderList = (SqlNodeList) expand(window.getOrderList(), windowScope); window.setOrderList(expandedOrderList); expandedOrderList.validate(this, windowScope); final SqlNodeList expandedPartitionList = (SqlNodeList) expand(window.getPartitionList(), windowScope); window.setPartitionList(expandedPartitionList); expandedPartitionList.validate(this, windowScope); } // Hand off to validate window spec components windowList.validate(this, windowScope); } public void validateWith(SqlWith with, SqlValidatorScope scope) { final SqlValidatorNamespace namespace = getNamespace(with); validateNamespace(namespace, unknownType); } public void validateWithItem(SqlWithItem withItem) { if (withItem.columnList != null) { final RelDataType rowType = getValidatedNodeType(withItem.query); final int fieldCount = rowType.getFieldCount(); if (withItem.columnList.size() != fieldCount) { throw newValidationError(withItem.columnList, RESOURCE.columnCountMismatch()); } SqlValidatorUtil.checkIdentifierListForDuplicates( withItem.columnList.getList(), validationErrorFunction); } else { // Luckily, field names have not been make unique yet. final List<String> fieldNames = getValidatedNodeType(withItem.query).getFieldNames(); final int i = Util.firstDuplicate(fieldNames); if (i >= 0) { throw newValidationError(withItem.query, RESOURCE.duplicateColumnAndNoColumnList(fieldNames.get(i))); } } } public void validateSequenceValue(SqlValidatorScope scope, SqlIdentifier id) { // Resolve identifier as a table. final SqlValidatorScope.ResolvedImpl resolved = new SqlValidatorScope.ResolvedImpl(); scope.resolveTable(id.names, catalogReader.nameMatcher(), SqlValidatorScope.Path.EMPTY, resolved); if (resolved.count() != 1) { throw newValidationError(id, RESOURCE.tableNameNotFound(id.toString())); } // We've found a table. But is it a sequence? final SqlValidatorNamespace ns = resolved.only().namespace; if (ns instanceof TableNamespace) { final Table table = ((RelOptTable) ns.getTable()).unwrap(Table.class); switch (table.getJdbcTableType()) { case SEQUENCE: case TEMPORARY_SEQUENCE: return; } } throw newValidationError(id, RESOURCE.notASequence(id.toString())); } public SqlValidatorScope getWithScope(SqlNode withItem) { assert withItem.getKind() == SqlKind.WITH_ITEM; return scopes.get(withItem); } /** * Validates the ORDER BY clause of a SELECT statement. * * @param select Select statement */ protected void validateOrderList(SqlSelect select) { // ORDER BY is validated in a scope where aliases in the SELECT clause // are visible. For example, "SELECT empno AS x FROM emp ORDER BY x" // is valid. SqlNodeList orderList = select.getOrderList(); if (orderList == null) { return; } if (!shouldAllowIntermediateOrderBy()) { if (!cursorSet.contains(select)) { throw newValidationError(select, RESOURCE.invalidOrderByPos()); } } final SqlValidatorScope orderScope = getOrderScope(select); Preconditions.checkNotNull(orderScope != null); List<SqlNode> expandList = new ArrayList<>(); for (SqlNode orderItem : orderList) { SqlNode expandedOrderItem = expand(orderItem, orderScope); expandList.add(expandedOrderItem); } SqlNodeList expandedOrderList = new SqlNodeList( expandList, orderList.getParserPosition()); select.setOrderBy(expandedOrderList); for (SqlNode orderItem : expandedOrderList) { validateOrderItem(select, orderItem); } } /** * Validates an item in the GROUP BY clause of a SELECT statement. * * @param select Select statement * @param groupByItem GROUP BY clause item */ private void validateGroupByItem(SqlSelect select, SqlNode groupByItem) { final SqlValidatorScope groupByScope = getGroupScope(select); groupByScope.validateExpr(groupByItem); } /** * Validates an item in the ORDER BY clause of a SELECT statement. * * @param select Select statement * @param orderItem ORDER BY clause item */ private void validateOrderItem(SqlSelect select, SqlNode orderItem) { switch (orderItem.getKind()) { case DESCENDING: validateFeature(RESOURCE.sQLConformance_OrderByDesc(), orderItem.getParserPosition()); validateOrderItem(select, ((SqlCall) orderItem).operand(0)); return; } final SqlValidatorScope orderScope = getOrderScope(select); validateExpr(orderItem, orderScope); } public SqlNode expandOrderExpr(SqlSelect select, SqlNode orderExpr) { final SqlNode newSqlNode = new OrderExpressionExpander(select, orderExpr).go(); if (newSqlNode != orderExpr) { final SqlValidatorScope scope = getOrderScope(select); inferUnknownTypes(unknownType, scope, newSqlNode); final RelDataType type = deriveType(scope, newSqlNode); setValidatedNodeType(newSqlNode, type); } return newSqlNode; } /** * Validates the GROUP BY clause of a SELECT statement. This method is * called even if no GROUP BY clause is present. */ protected void validateGroupClause(SqlSelect select) { SqlNodeList groupList = select.getGroup(); if (groupList == null) { return; } validateNoAggs(aggOrOverFinder, groupList, "GROUP BY"); final SqlValidatorScope groupScope = getGroupScope(select); inferUnknownTypes(unknownType, groupScope, groupList); // expand the expression in group list. List<SqlNode> expandedList = new ArrayList<>(); for (SqlNode groupItem : groupList) { SqlNode expandedItem = expandGroupByOrHavingExpr(groupItem, groupScope, select, false); expandedList.add(expandedItem); } groupList = new SqlNodeList(expandedList, groupList.getParserPosition()); select.setGroupBy(groupList); for (SqlNode groupItem : expandedList) { validateGroupByItem(select, groupItem); } // Nodes in the GROUP BY clause are expressions except if they are calls // to the GROUPING SETS, ROLLUP or CUBE operators; this operators are not // expressions, because they do not have a type. for (SqlNode node : groupList) { switch (node.getKind()) { case GROUPING_SETS: case ROLLUP: case CUBE: node.validate(this, groupScope); break; default: node.validateExpr(this, groupScope); } } // Derive the type of each GROUP BY item. We don't need the type, but // it resolves functions, and that is necessary for deducing // monotonicity. final SqlValidatorScope selectScope = getSelectScope(select); AggregatingSelectScope aggregatingScope = null; if (selectScope instanceof AggregatingSelectScope) { aggregatingScope = (AggregatingSelectScope) selectScope; } for (SqlNode groupItem : groupList) { if (groupItem instanceof SqlNodeList && ((SqlNodeList) groupItem).size() == 0) { continue; } validateGroupItem(groupScope, aggregatingScope, groupItem); } SqlNode agg = aggFinder.findAgg(groupList); if (agg != null) { throw newValidationError(agg, RESOURCE.aggregateIllegalInGroupBy()); } } private void validateGroupItem(SqlValidatorScope groupScope, AggregatingSelectScope aggregatingScope, SqlNode groupItem) { switch (groupItem.getKind()) { case GROUPING_SETS: case ROLLUP: case CUBE: validateGroupingSets(groupScope, aggregatingScope, (SqlCall) groupItem); break; default: if (groupItem instanceof SqlNodeList) { break; } final RelDataType type = deriveType(groupScope, groupItem); setValidatedNodeType(groupItem, type); } } private void validateGroupingSets(SqlValidatorScope groupScope, AggregatingSelectScope aggregatingScope, SqlCall groupItem) { for (SqlNode node : groupItem.getOperandList()) { validateGroupItem(groupScope, aggregatingScope, node); } } protected void validateWhereClause(SqlSelect select) { // validate WHERE clause final SqlNode where = select.getWhere(); if (where == null) { return; } final SqlValidatorScope whereScope = getWhereScope(select); final SqlNode expandedWhere = expand(where, whereScope); select.setWhere(expandedWhere); validateWhereOrOn(whereScope, expandedWhere, "WHERE"); } protected void validateWhereOrOn( SqlValidatorScope scope, SqlNode condition, String keyword) { validateNoAggs(aggOrOverOrGroupFinder, condition, keyword); inferUnknownTypes( booleanType, scope, condition); condition.validate(this, scope); final RelDataType type = deriveType(scope, condition); if (!SqlTypeUtil.inBooleanFamily(type)) { throw newValidationError(condition, RESOURCE.condMustBeBoolean(keyword)); } } protected void validateHavingClause(SqlSelect select) { // HAVING is validated in the scope after groups have been created. // For example, in "SELECT empno FROM emp WHERE empno = 10 GROUP BY // deptno HAVING empno = 10", the reference to 'empno' in the HAVING // clause is illegal. SqlNode having = select.getHaving(); if (having == null) { return; } final AggregatingScope havingScope = (AggregatingScope) getSelectScope(select); if (getConformance().isHavingAlias()) { SqlNode newExpr = expandGroupByOrHavingExpr(having, havingScope, select, true); if (having != newExpr) { having = newExpr; select.setHaving(newExpr); } } havingScope.checkAggregateExpr(having, true); inferUnknownTypes( booleanType, havingScope, having); having.validate(this, havingScope); final RelDataType type = deriveType(havingScope, having); if (!SqlTypeUtil.inBooleanFamily(type)) { throw newValidationError(having, RESOURCE.havingMustBeBoolean()); } } protected RelDataType validateSelectList( final SqlNodeList selectItems, SqlSelect select, RelDataType targetRowType) { // First pass, ensure that aliases are unique. "*" and "TABLE.*" items // are ignored. // Validate SELECT list. Expand terms of the form "*" or "TABLE.*". final SqlValidatorScope selectScope = getSelectScope(select); final List<SqlNode> expandedSelectItems = new ArrayList<>(); final Set<String> aliases = Sets.newHashSet(); final List<Map.Entry<String, RelDataType>> fieldList = new ArrayList<>(); for (int i = 0; i < selectItems.size(); i++) { SqlNode selectItem = selectItems.get(i); if (selectItem instanceof SqlSelect) { handleScalarSubQuery( select, (SqlSelect) selectItem, expandedSelectItems, aliases, fieldList); } else { expandSelectItem( selectItem, select, targetRowType.isStruct() && targetRowType.getFieldCount() >= i ? targetRowType.getFieldList().get(i).getType() : unknownType, expandedSelectItems, aliases, fieldList, false); } } // Create the new select list with expanded items. Pass through // the original parser position so that any overall failures can // still reference the original input text. SqlNodeList newSelectList = new SqlNodeList( expandedSelectItems, selectItems.getParserPosition()); if (shouldExpandIdentifiers()) { select.setSelectList(newSelectList); } getRawSelectScope(select).setExpandedSelectList(expandedSelectItems); // TODO: when SELECT appears as a value sub-query, should be using // something other than unknownType for targetRowType inferUnknownTypes(targetRowType, selectScope, newSelectList); for (SqlNode selectItem : expandedSelectItems) { validateNoAggs(groupFinder, selectItem, "SELECT"); validateExpr(selectItem, selectScope); } assert fieldList.size() >= aliases.size(); return typeFactory.createStructType(fieldList); } /** * Validates an expression. * * @param expr Expression * @param scope Scope in which expression occurs */ private void validateExpr(SqlNode expr, SqlValidatorScope scope) { if (expr instanceof SqlCall) { final SqlOperator op = ((SqlCall) expr).getOperator(); if (op.isAggregator() && op.requiresOver()) { throw newValidationError(expr, RESOURCE.absentOverClause()); } } // Call on the expression to validate itself. expr.validateExpr(this, scope); // Perform any validation specific to the scope. For example, an // aggregating scope requires that expressions are valid aggregations. scope.validateExpr(expr); } /** * Processes SubQuery found in Select list. Checks that is actually Scalar * sub-query and makes proper entries in each of the 3 lists used to create * the final rowType entry. * * @param parentSelect base SqlSelect item * @param selectItem child SqlSelect from select list * @param expandedSelectItems Select items after processing * @param aliasList built from user or system values * @param fieldList Built up entries for each select list entry */ private void handleScalarSubQuery( SqlSelect parentSelect, SqlSelect selectItem, List<SqlNode> expandedSelectItems, Set<String> aliasList, List<Map.Entry<String, RelDataType>> fieldList) { // A scalar sub-query only has one output column. if (1 != selectItem.getSelectList().size()) { throw newValidationError(selectItem, RESOURCE.onlyScalarSubQueryAllowed()); } // No expansion in this routine just append to list. expandedSelectItems.add(selectItem); // Get or generate alias and add to list. final String alias = deriveAlias( selectItem, aliasList.size()); aliasList.add(alias); final SelectScope scope = (SelectScope) getWhereScope(parentSelect); final RelDataType type = deriveType(scope, selectItem); setValidatedNodeType(selectItem, type); // we do not want to pass on the RelRecordType returned // by the sub query. Just the type of the single expression // in the sub-query select list. assert type instanceof RelRecordType; RelRecordType rec = (RelRecordType) type; RelDataType nodeType = rec.getFieldList().get(0).getType(); nodeType = typeFactory.createTypeWithNullability(nodeType, true); fieldList.add(Pair.of(alias, nodeType)); } /** * Derives a row-type for INSERT and UPDATE operations. * * @param table Target table for INSERT/UPDATE * @param targetColumnList List of target columns, or null if not specified * @param append Whether to append fields to those in <code> * baseRowType</code> * @return Rowtype */ protected RelDataType createTargetRowType( SqlValidatorTable table, SqlNodeList targetColumnList, boolean append) { RelDataType baseRowType = table.getRowType(); if (targetColumnList == null) { return baseRowType; } List<RelDataTypeField> targetFields = baseRowType.getFieldList(); final List<Map.Entry<String, RelDataType>> types = new ArrayList<>(); if (append) { for (RelDataTypeField targetField : targetFields) { types.add( Pair.of(SqlUtil.deriveAliasFromOrdinal(types.size()), targetField.getType())); } } final Set<Integer> assignedFields = new HashSet<>(); final RelOptTable relOptTable = table instanceof RelOptTable ? ((RelOptTable) table) : null; for (SqlNode node : targetColumnList) { SqlIdentifier id = (SqlIdentifier) node; RelDataTypeField targetField = SqlValidatorUtil.getTargetField( baseRowType, typeFactory, id, catalogReader, relOptTable); if (targetField == null) { throw newValidationError(id, RESOURCE.unknownTargetColumn(id.toString())); } if (!assignedFields.add(targetField.getIndex())) { throw newValidationError(id, RESOURCE.duplicateTargetColumn(targetField.getName())); } types.add(targetField); } return typeFactory.createStructType(types); } public void validateInsert(SqlInsert insert) { final SqlValidatorNamespace targetNamespace = getNamespace(insert); validateNamespace(targetNamespace, unknownType); final RelOptTable relOptTable = SqlValidatorUtil.getRelOptTable( targetNamespace, catalogReader.unwrap(Prepare.CatalogReader.class), null, null); final SqlValidatorTable table = relOptTable == null ? targetNamespace.getTable() : relOptTable.unwrap(SqlValidatorTable.class); // INSERT has an optional column name list. If present then // reduce the rowtype to the columns specified. If not present // then the entire target rowtype is used. final RelDataType targetRowType = createTargetRowType( table, insert.getTargetColumnList(), false); final SqlNode source = insert.getSource(); if (source instanceof SqlSelect) { final SqlSelect sqlSelect = (SqlSelect) source; validateSelect(sqlSelect, targetRowType); } else { final SqlValidatorScope scope = scopes.get(source); validateQuery(source, scope, targetRowType); } // REVIEW jvs 4-Dec-2008: In FRG-365, this namespace row type is // discarding the type inferred by inferUnknownTypes (which was invoked // from validateSelect above). It would be better if that information // were used here so that we never saw any untyped nulls during // checkTypeAssignment. final RelDataType sourceRowType = getNamespace(source).getRowType(); final RelDataType logicalTargetRowType = getLogicalTargetRowType(targetRowType, insert); setValidatedNodeType(insert, logicalTargetRowType); final RelDataType logicalSourceRowType = getLogicalSourceRowType(sourceRowType, insert); checkFieldCount(insert.getTargetTable(), table, logicalSourceRowType, logicalTargetRowType); checkTypeAssignment(logicalSourceRowType, logicalTargetRowType, insert); checkConstraint(table, source, logicalTargetRowType); validateAccess(insert.getTargetTable(), table, SqlAccessEnum.INSERT); } /** * Validates insert values against the constraint of a modifiable view. * * @param validatorTable Table that may wrap a ModifiableViewTable * @param source The values being inserted * @param targetRowType The target type for the view */ private void checkConstraint( SqlValidatorTable validatorTable, SqlNode source, RelDataType targetRowType) { final ModifiableViewTable modifiableViewTable = validatorTable.unwrap(ModifiableViewTable.class); if (modifiableViewTable != null && source instanceof SqlCall) { final Table table = modifiableViewTable.unwrap(Table.class); final RelDataType tableRowType = table.getRowType(typeFactory); final List<RelDataTypeField> tableFields = tableRowType.getFieldList(); // Get the mapping from column indexes of the underlying table // to the target columns and view constraints. final Map<Integer, RelDataTypeField> tableIndexToTargetField = SqlValidatorUtil.getIndexToFieldMap(tableFields, targetRowType); final Map<Integer, RexNode> projectMap = RelOptUtil.getColumnConstraints(modifiableViewTable, targetRowType, typeFactory); // Determine columns (indexed to the underlying table) that need // to be validated against the view constraint. final ImmutableBitSet targetColumns = ImmutableBitSet.of(tableIndexToTargetField.keySet()); final ImmutableBitSet constrainedColumns = ImmutableBitSet.of(projectMap.keySet()); final ImmutableBitSet constrainedTargetColumns = targetColumns.intersect(constrainedColumns); // Validate insert values against the view constraint. final List<SqlNode> values = ((SqlCall) source).getOperandList(); for (final int colIndex : constrainedTargetColumns.asList()) { final String colName = tableFields.get(colIndex).getName(); final RelDataTypeField targetField = tableIndexToTargetField.get(colIndex); for (SqlNode row : values) { final SqlCall call = (SqlCall) row; final SqlNode sourceValue = call.operand(targetField.getIndex()); final ValidationError validationError = new ValidationError(sourceValue, RESOURCE.viewConstraintNotSatisfied(colName, Util.last(validatorTable.getQualifiedName()))); RelOptUtil.validateValueAgainstConstraint(sourceValue, projectMap.get(colIndex), validationError); } } } } /** * Validates updates against the constraint of a modifiable view. * * @param validatorTable A {@link SqlValidatorTable} that may wrap a * ModifiableViewTable * @param update The UPDATE parse tree node * @param targetRowType The target type */ private void checkConstraint( SqlValidatorTable validatorTable, SqlUpdate update, RelDataType targetRowType) { final ModifiableViewTable modifiableViewTable = validatorTable.unwrap(ModifiableViewTable.class); if (modifiableViewTable != null) { final Table table = modifiableViewTable.unwrap(Table.class); final RelDataType tableRowType = table.getRowType(typeFactory); final Map<Integer, RexNode> projectMap = RelOptUtil.getColumnConstraints(modifiableViewTable, targetRowType, typeFactory); final Map<String, Integer> nameToIndex = SqlValidatorUtil.mapNameToIndex(tableRowType.getFieldList()); // Validate update values against the view constraint. final List<SqlNode> targets = update.getTargetColumnList().getList(); final List<SqlNode> sources = update.getSourceExpressionList().getList(); for (final Pair<SqlNode, SqlNode> column : Pair.zip(targets, sources)) { final String columnName = ((SqlIdentifier) column.left).getSimple(); final Integer columnIndex = nameToIndex.get(columnName); if (projectMap.containsKey(columnIndex)) { final RexNode columnConstraint = projectMap.get(columnIndex); final ValidationError validationError = new ValidationError(column.right, RESOURCE.viewConstraintNotSatisfied(columnName, Util.last(validatorTable.getQualifiedName()))); RelOptUtil.validateValueAgainstConstraint(column.right, columnConstraint, validationError); } } } } private void checkFieldCount( SqlNode node, SqlValidatorTable table, RelDataType logicalSourceRowType, RelDataType logicalTargetRowType) { final int sourceFieldCount = logicalSourceRowType.getFieldCount(); final int targetFieldCount = logicalTargetRowType.getFieldCount(); if (sourceFieldCount != targetFieldCount) { throw newValidationError(node, RESOURCE.unmatchInsertColumn(targetFieldCount, sourceFieldCount)); } // Ensure that non-nullable fields are targeted. final InitializerContext rexBuilder = new InitializerContext() { public RexBuilder getRexBuilder() { return new RexBuilder(typeFactory); } }; for (final RelDataTypeField field : table.getRowType().getFieldList()) { if (!field.getType().isNullable()) { final RelDataTypeField targetField = logicalTargetRowType.getField(field.getName(), true, false); if (targetField == null && !table.columnHasDefaultValue(table.getRowType(), field.getIndex(), rexBuilder)) { throw newValidationError(node, RESOURCE.columnNotNullable(field.getName())); } } } } protected RelDataType getLogicalTargetRowType( RelDataType targetRowType, SqlInsert insert) { if (insert.getTargetColumnList() == null && conformance.isInsertSubsetColumnsAllowed()) { // Target an implicit subset of columns. final SqlNode source = insert.getSource(); final RelDataType sourceRowType = getNamespace(source).getRowType(); final RelDataType logicalSourceRowType = getLogicalSourceRowType(sourceRowType, insert); final RelDataType implicitTargetRowType = typeFactory.createStructType( targetRowType.getFieldList() .subList(0, logicalSourceRowType.getFieldCount())); final SqlValidatorNamespace targetNamespace = getNamespace(insert); validateNamespace(targetNamespace, implicitTargetRowType); return implicitTargetRowType; } else { // Either the set of columns are explicitly targeted, or target the full // set of columns. return targetRowType; } } protected RelDataType getLogicalSourceRowType( RelDataType sourceRowType, SqlInsert insert) { return sourceRowType; } protected void checkTypeAssignment( RelDataType sourceRowType, RelDataType targetRowType, final SqlNode query) { // NOTE jvs 23-Feb-2006: subclasses may allow for extra targets // representing system-maintained columns, so stop after all sources // matched List<RelDataTypeField> sourceFields = sourceRowType.getFieldList(); List<RelDataTypeField> targetFields = targetRowType.getFieldList(); final int sourceCount = sourceFields.size(); for (int i = 0; i < sourceCount; ++i) { RelDataType sourceType = sourceFields.get(i).getType(); RelDataType targetType = targetFields.get(i).getType(); if (!SqlTypeUtil.canAssignFrom(targetType, sourceType)) { // FRG-255: account for UPDATE rewrite; there's // probably a better way to do this. int iAdjusted = i; if (query instanceof SqlUpdate) { int nUpdateColumns = ((SqlUpdate) query).getTargetColumnList().size(); assert sourceFields.size() >= nUpdateColumns; iAdjusted -= sourceFields.size() - nUpdateColumns; } SqlNode node = getNthExpr(query, iAdjusted, sourceCount); String targetTypeString; String sourceTypeString; if (SqlTypeUtil.areCharacterSetsMismatched( sourceType, targetType)) { sourceTypeString = sourceType.getFullTypeString(); targetTypeString = targetType.getFullTypeString(); } else { sourceTypeString = sourceType.toString(); targetTypeString = targetType.toString(); } throw newValidationError(node, RESOURCE.typeNotAssignable( targetFields.get(i).getName(), targetTypeString, sourceFields.get(i).getName(), sourceTypeString)); } } } /** * Locates the n'th expression in an INSERT or UPDATE query. * * @param query Query * @param ordinal Ordinal of expression * @param sourceCount Number of expressions * @return Ordinal'th expression, never null */ private SqlNode getNthExpr(SqlNode query, int ordinal, int sourceCount) { if (query instanceof SqlInsert) { SqlInsert insert = (SqlInsert) query; if (insert.getTargetColumnList() != null) { return insert.getTargetColumnList().get(ordinal); } else { return getNthExpr( insert.getSource(), ordinal, sourceCount); } } else if (query instanceof SqlUpdate) { SqlUpdate update = (SqlUpdate) query; if (update.getTargetColumnList() != null) { return update.getTargetColumnList().get(ordinal); } else if (update.getSourceExpressionList() != null) { return update.getSourceExpressionList().get(ordinal); } else { return getNthExpr( update.getSourceSelect(), ordinal, sourceCount); } } else if (query instanceof SqlSelect) { SqlSelect select = (SqlSelect) query; if (select.getSelectList().size() == sourceCount) { return select.getSelectList().get(ordinal); } else { return query; // give up } } else { return query; // give up } } public void validateDelete(SqlDelete call) { final SqlSelect sqlSelect = call.getSourceSelect(); validateSelect(sqlSelect, unknownType); final SqlValidatorNamespace targetNamespace = getNamespace(call); validateNamespace(targetNamespace, unknownType); final SqlValidatorTable table = targetNamespace.getTable(); validateAccess(call.getTargetTable(), table, SqlAccessEnum.DELETE); } public void validateUpdate(SqlUpdate call) { final SqlValidatorNamespace targetNamespace = getNamespace(call); validateNamespace(targetNamespace, unknownType); final RelOptTable relOptTable = SqlValidatorUtil.getRelOptTable( targetNamespace, catalogReader.unwrap(Prepare.CatalogReader.class), null, null); final SqlValidatorTable table = relOptTable == null ? targetNamespace.getTable() : relOptTable.unwrap(SqlValidatorTable.class); final RelDataType targetRowType = createTargetRowType( table, call.getTargetColumnList(), true); final SqlSelect select = call.getSourceSelect(); validateSelect(select, targetRowType); final RelDataType sourceRowType = getNamespace(call).getRowType(); checkTypeAssignment(sourceRowType, targetRowType, call); checkConstraint(table, call, targetRowType); validateAccess(call.getTargetTable(), table, SqlAccessEnum.UPDATE); } public void validateMerge(SqlMerge call) { SqlSelect sqlSelect = call.getSourceSelect(); // REVIEW zfong 5/25/06 - Does an actual type have to be passed into // validateSelect()? // REVIEW jvs 6-June-2006: In general, passing unknownType like // this means we won't be able to correctly infer the types // for dynamic parameter markers (SET x = ?). But // maybe validateUpdate and validateInsert below will do // the job? // REVIEW ksecretan 15-July-2011: They didn't get a chance to // since validateSelect() would bail. // Let's use the update/insert targetRowType when available. IdentifierNamespace targetNamespace = (IdentifierNamespace) getNamespace(call.getTargetTable()); validateNamespace(targetNamespace, unknownType); SqlValidatorTable table = targetNamespace.getTable(); validateAccess(call.getTargetTable(), table, SqlAccessEnum.UPDATE); RelDataType targetRowType = unknownType; if (call.getUpdateCall() != null) { targetRowType = createTargetRowType( table, call.getUpdateCall().getTargetColumnList(), true); } if (call.getInsertCall() != null) { targetRowType = createTargetRowType( table, call.getInsertCall().getTargetColumnList(), false); } validateSelect(sqlSelect, targetRowType); if (call.getUpdateCall() != null) { validateUpdate(call.getUpdateCall()); } if (call.getInsertCall() != null) { validateInsert(call.getInsertCall()); } } /** * Validates access to a table. * * @param table Table * @param requiredAccess Access requested on table */ private void validateAccess( SqlNode node, SqlValidatorTable table, SqlAccessEnum requiredAccess) { if (table != null) { SqlAccessType access = table.getAllowedAccess(); if (!access.allowsAccess(requiredAccess)) { throw newValidationError(node, RESOURCE.accessNotAllowed(requiredAccess.name(), table.getQualifiedName().toString())); } } } /** * Validates a VALUES clause. * * @param node Values clause * @param targetRowType Row type which expression must conform to * @param scope Scope within which clause occurs */ protected void validateValues( SqlCall node, RelDataType targetRowType, final SqlValidatorScope scope) { assert node.getKind() == SqlKind.VALUES; final List<SqlNode> operands = node.getOperandList(); for (SqlNode operand : operands) { if (!(operand.getKind() == SqlKind.ROW)) { throw Util.needToImplement( "Values function where operands are scalars"); } SqlCall rowConstructor = (SqlCall) operand; if (conformance.isInsertSubsetColumnsAllowed() && targetRowType.isStruct() && rowConstructor.operandCount() < targetRowType.getFieldCount()) { targetRowType = typeFactory.createStructType( targetRowType.getFieldList() .subList(0, rowConstructor.operandCount())); } else if (targetRowType.isStruct() && rowConstructor.operandCount() != targetRowType.getFieldCount()) { return; } inferUnknownTypes( targetRowType, scope, rowConstructor); if (targetRowType.isStruct()) { for (Pair<SqlNode, RelDataTypeField> pair : Pair.zip(rowConstructor.getOperandList(), targetRowType.getFieldList())) { if (!pair.right.getType().isNullable() && SqlUtil.isNullLiteral(pair.left, false)) { throw newValidationError(node, RESOURCE.columnNotNullable(pair.right.getName())); } } } } for (SqlNode operand : operands) { operand.validate(this, scope); } // validate that all row types have the same number of columns // and that expressions in each column are compatible. // A values expression is turned into something that looks like // ROW(type00, type01,...), ROW(type11,...),... final int rowCount = operands.size(); if (rowCount >= 2) { SqlCall firstRow = (SqlCall) operands.get(0); final int columnCount = firstRow.operandCount(); // 1. check that all rows have the same cols length for (SqlNode operand : operands) { SqlCall thisRow = (SqlCall) operand; if (columnCount != thisRow.operandCount()) { throw newValidationError(node, RESOURCE.incompatibleValueType( SqlStdOperatorTable.VALUES.getName())); } } // 2. check if types at i:th position in each row are compatible for (int col = 0; col < columnCount; col++) { final int c = col; final RelDataType type = typeFactory.leastRestrictive( new AbstractList<RelDataType>() { public RelDataType get(int row) { SqlCall thisRow = (SqlCall) operands.get(row); return deriveType(scope, thisRow.operand(c)); } public int size() { return rowCount; } }); if (null == type) { throw newValidationError(node, RESOURCE.incompatibleValueType( SqlStdOperatorTable.VALUES.getName())); } } } } public void validateDataType(SqlDataTypeSpec dataType) { } public void validateDynamicParam(SqlDynamicParam dynamicParam) { } /** * Throws a validator exception with access to the validator context. * The exception is determined when an instance is created. */ private class ValidationError implements Supplier<CalciteContextException> { private final SqlNode sqlNode; private final Resources.ExInst<SqlValidatorException> validatorException; ValidationError(SqlNode sqlNode, Resources.ExInst<SqlValidatorException> validatorException) { this.sqlNode = sqlNode; this.validatorException = validatorException; } public CalciteContextException get() { return newValidationError(sqlNode, validatorException); } } /** * Throws a validator exception with access to the validator context. * The exception is determined when the function is applied. */ class ValidationErrorFunction implements Function2<SqlNode, Resources.ExInst<SqlValidatorException>, CalciteContextException> { @Override public CalciteContextException apply( SqlNode v0, Resources.ExInst<SqlValidatorException> v1) { return newValidationError(v0, v1); } } public ValidationErrorFunction getValidationErrorFunction() { return validationErrorFunction; } public CalciteContextException newValidationError(SqlNode node, Resources.ExInst<SqlValidatorException> e) { assert node != null; final SqlParserPos pos = node.getParserPosition(); return SqlUtil.newContextException(pos, e); } protected SqlWindow getWindowByName( SqlIdentifier id, SqlValidatorScope scope) { SqlWindow window = null; if (id.isSimple()) { final String name = id.getSimple(); window = scope.lookupWindow(name); } if (window == null) { throw newValidationError(id, RESOURCE.windowNotFound(id.toString())); } return window; } public SqlWindow resolveWindow( SqlNode windowOrRef, SqlValidatorScope scope, boolean populateBounds) { SqlWindow window; if (windowOrRef instanceof SqlIdentifier) { window = getWindowByName((SqlIdentifier) windowOrRef, scope); } else { window = (SqlWindow) windowOrRef; } while (true) { final SqlIdentifier refId = window.getRefName(); if (refId == null) { break; } final String refName = refId.getSimple(); SqlWindow refWindow = scope.lookupWindow(refName); if (refWindow == null) { throw newValidationError(refId, RESOURCE.windowNotFound(refName)); } window = window.overlay(refWindow, this); } if (populateBounds) { window.populateBounds(); } return window; } public SqlNode getOriginal(SqlNode expr) { SqlNode original = originalExprs.get(expr); if (original == null) { original = expr; } return original; } public void setOriginal(SqlNode expr, SqlNode original) { // Don't overwrite the original original. if (originalExprs.get(expr) == null) { originalExprs.put(expr, original); } } SqlValidatorNamespace lookupFieldNamespace(RelDataType rowType, String name) { final SqlNameMatcher nameMatcher = catalogReader.nameMatcher(); final RelDataTypeField field = nameMatcher.field(rowType, name); return new FieldNamespace(this, field.getType()); } public void validateWindow( SqlNode windowOrId, SqlValidatorScope scope, SqlCall call) { // Enable nested aggregates with window aggregates (OVER operator) inWindow = true; final SqlWindow targetWindow; switch (windowOrId.getKind()) { case IDENTIFIER: // Just verify the window exists in this query. It will validate // when the definition is processed targetWindow = getWindowByName((SqlIdentifier) windowOrId, scope); break; case WINDOW: targetWindow = (SqlWindow) windowOrId; break; default: throw Util.unexpected(windowOrId.getKind()); } assert targetWindow.getWindowCall() == null; targetWindow.setWindowCall(call); targetWindow.validate(this, scope); targetWindow.setWindowCall(null); call.validate(this, scope); validateAggregateParams(call, null, scope); // Disable nested aggregates post validation inWindow = false; } @Override public void validateMatchRecognize(SqlCall call) { final SqlMatchRecognize matchRecognize = (SqlMatchRecognize) call; final MatchRecognizeScope scope = (MatchRecognizeScope) getMatchRecognizeScope(matchRecognize); final MatchRecognizeNamespace ns = getNamespace(call).unwrap(MatchRecognizeNamespace.class); assert ns.rowType == null; // rows per match final SqlLiteral rowsPerMatch = matchRecognize.getRowsPerMatch(); final boolean allRows = rowsPerMatch != null && rowsPerMatch.getValue() == SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS; final RelDataTypeFactory.Builder typeBuilder = typeFactory.builder(); // parse PARTITION BY column SqlNodeList partitionBy = matchRecognize.getPartitionList(); if (partitionBy != null) { for (SqlNode node : partitionBy) { SqlIdentifier identifier = (SqlIdentifier) node; identifier.validate(this, scope); RelDataType type = deriveType(scope, identifier); String name = identifier.names.get(1); typeBuilder.add(name, type); } } // parse ORDER BY column SqlNodeList orderBy = matchRecognize.getOrderList(); if (orderBy != null) { for (SqlNode node : orderBy) { node.validate(this, scope); SqlIdentifier identifier = null; if (node instanceof SqlBasicCall) { identifier = (SqlIdentifier) ((SqlBasicCall) node).getOperands()[0]; } else { identifier = (SqlIdentifier) node; } if (allRows) { RelDataType type = deriveType(scope, identifier); String name = identifier.names.get(1); if (!typeBuilder.nameExists(name)) { typeBuilder.add(name, type); } } } } if (allRows) { final SqlValidatorNamespace sqlNs = getNamespace(matchRecognize.getTableRef()); final RelDataType inputDataType = sqlNs.getRowType(); for (RelDataTypeField fs : inputDataType.getFieldList()) { if (!typeBuilder.nameExists(fs.getName())) { typeBuilder.add(fs); } } } // retrieve pattern variables used in pattern and subset SqlNode pattern = matchRecognize.getPattern(); PatternVarVisitor visitor = new PatternVarVisitor(scope); pattern.accept(visitor); SqlLiteral interval = matchRecognize.getInterval(); if (interval != null) { interval.validate(this, scope); if (((SqlIntervalLiteral) interval).signum() < 0) { throw newValidationError(interval, RESOURCE.intervalMustBeNonNegative(interval.toValue())); } if (orderBy == null || orderBy.size() == 0) { throw newValidationError(interval, RESOURCE.cannotUseWithinWithoutOrderBy()); } SqlNode firstOrderByColumn = orderBy.getList().get(0); SqlIdentifier identifier; if (firstOrderByColumn instanceof SqlBasicCall) { identifier = (SqlIdentifier) ((SqlBasicCall) firstOrderByColumn).getOperands()[0]; } else { identifier = (SqlIdentifier) firstOrderByColumn; } RelDataType firstOrderByColumnType = deriveType(scope, identifier); if (firstOrderByColumnType.getSqlTypeName() != SqlTypeName.TIMESTAMP) { throw newValidationError(interval, RESOURCE.firstColumnOfOrderByMustBeTimestamp()); } SqlNode expand = expand(interval, scope); RelDataType type = deriveType(scope, expand); setValidatedNodeType(interval, type); } validateDefinitions(matchRecognize, scope); SqlNodeList subsets = matchRecognize.getSubsetList(); if (subsets != null && subsets.size() > 0) { for (SqlNode node : subsets) { List<SqlNode> operands = ((SqlCall) node).getOperandList(); String leftString = ((SqlIdentifier) operands.get(0)).getSimple(); if (scope.getPatternVars().contains(leftString)) { throw newValidationError(operands.get(0), RESOURCE.patternVarAlreadyDefined(leftString)); } scope.addPatternVar(leftString); for (SqlNode right : (SqlNodeList) operands.get(1)) { SqlIdentifier id = (SqlIdentifier) right; if (!scope.getPatternVars().contains(id.getSimple())) { throw newValidationError(id, RESOURCE.unknownPattern(id.getSimple())); } scope.addPatternVar(id.getSimple()); } } } // validate AFTER ... SKIP TO final SqlNode skipTo = matchRecognize.getAfter(); if (skipTo instanceof SqlCall) { final SqlCall skipToCall = (SqlCall) skipTo; final SqlIdentifier id = skipToCall.operand(0); if (!scope.getPatternVars().contains(id.getSimple())) { throw newValidationError(id, RESOURCE.unknownPattern(id.getSimple())); } } List<Map.Entry<String, RelDataType>> measureColumns = validateMeasure(matchRecognize, scope, allRows); for (Map.Entry<String, RelDataType> c : measureColumns) { if (!typeBuilder.nameExists(c.getKey())) { typeBuilder.add(c.getKey(), c.getValue()); } } final RelDataType rowType = typeBuilder.build(); if (matchRecognize.getMeasureList().size() == 0) { ns.setType(getNamespace(matchRecognize.getTableRef()).getRowType()); } else { ns.setType(rowType); } } private List<Map.Entry<String, RelDataType>> validateMeasure(SqlMatchRecognize mr, MatchRecognizeScope scope, boolean allRows) { final List<String> aliases = new ArrayList<>(); final List<SqlNode> sqlNodes = new ArrayList<>(); final SqlNodeList measures = mr.getMeasureList(); final List<Map.Entry<String, RelDataType>> fields = new ArrayList<>(); for (SqlNode measure : measures) { assert measure instanceof SqlCall; final String alias = deriveAlias(measure, aliases.size()); aliases.add(alias); SqlNode expand = expand(measure, scope); validateMeasures(expand, allRows); setOriginal(expand, measure); inferUnknownTypes(unknownType, scope, expand); final RelDataType type = deriveType(scope, expand); setValidatedNodeType(measure, type); fields.add(Pair.of(alias, type)); sqlNodes.add( SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO, expand, new SqlIdentifier(alias, SqlParserPos.ZERO))); } SqlNodeList list = new SqlNodeList(sqlNodes, measures.getParserPosition()); inferUnknownTypes(unknownType, scope, list); for (SqlNode node : list) { validateExpr(node, scope); } mr.setOperand(SqlMatchRecognize.OPERAND_MEASURES, list); return fields; } private void validateMeasures(SqlNode node, boolean allRows) { final Set<String> prefix = node.accept(new PatternValidator(true)); Util.discard(prefix); } private void validateDefinitions(SqlMatchRecognize mr, MatchRecognizeScope scope) { final Set<String> aliases = catalogReader.nameMatcher().isCaseSensitive() ? new LinkedHashSet<String>() : new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for (SqlNode item : mr.getPatternDefList().getList()) { final String alias = alias(item); if (!aliases.add(alias)) { throw newValidationError(item, Static.RESOURCE.patternVarAlreadyDefined(alias)); } scope.addPatternVar(alias); } final List<SqlNode> sqlNodes = new ArrayList<>(); for (SqlNode item : mr.getPatternDefList().getList()) { final String alias = alias(item); SqlNode expand = expand(item, scope); validateDefine(expand, alias); setOriginal(expand, item); inferUnknownTypes(booleanType, scope, expand); expand.validate(this, scope); // Some extra work need required here. // In PREV, NEXT, FINAL and LAST, only one pattern variable is allowed. sqlNodes.add( SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO, expand, new SqlIdentifier(alias, SqlParserPos.ZERO))); final RelDataType type = deriveType(scope, expand); if (!SqlTypeUtil.inBooleanFamily(type)) { throw newValidationError(expand, RESOURCE.condMustBeBoolean("DEFINE")); } setValidatedNodeType(item, type); } SqlNodeList list = new SqlNodeList(sqlNodes, mr.getPatternDefList().getParserPosition()); inferUnknownTypes(unknownType, scope, list); for (SqlNode node : list) { validateExpr(node, scope); } mr.setOperand(SqlMatchRecognize.OPERAND_PATTERN_DEFINES, list); } /** Returns the alias of a "expr AS alias" expression. */ private static String alias(SqlNode item) { assert item instanceof SqlCall; assert item.getKind() == SqlKind.AS; final SqlIdentifier identifier = ((SqlCall) item).operand(1); return identifier.getSimple(); } /** Checks that all pattern variables within a function are the same. */ private void validateDefine(SqlNode node, String alpha) { Set<String> prefix = node.accept(new PatternValidator(false)); Util.discard(prefix); } public void validateAggregateParams(SqlCall aggCall, SqlNode filter, SqlValidatorScope scope) { // For "agg(expr)", expr cannot itself contain aggregate function // invocations. For example, "SUM(2 * MAX(x))" is illegal; when // we see it, we'll report the error for the SUM (not the MAX). // For more than one level of nesting, the error which results // depends on the traversal order for validation. // // For a windowed aggregate "agg(expr)", expr can contain an aggregate // function. For example, // SELECT AVG(2 * MAX(x)) OVER (PARTITION BY y) // FROM t // GROUP BY y // is legal. Only one level of nesting is allowed since non-windowed // aggregates cannot nest aggregates. // Store nesting level of each aggregate. If an aggregate is found at an invalid // nesting level, throw an assert. final AggFinder a; if (inWindow) { a = overFinder; } else { a = aggOrOverFinder; } for (SqlNode param : aggCall.getOperandList()) { if (a.findAgg(param) != null) { throw newValidationError(aggCall, RESOURCE.nestedAggIllegal()); } } if (filter != null) { if (a.findAgg(filter) != null) { throw newValidationError(filter, RESOURCE.aggregateInFilterIllegal()); } } } public void validateCall( SqlCall call, SqlValidatorScope scope) { final SqlOperator operator = call.getOperator(); if ((call.operandCount() == 0) && (operator.getSyntax() == SqlSyntax.FUNCTION_ID) && !call.isExpanded() && !conformance.allowNiladicParentheses()) { // For example, "LOCALTIME()" is illegal. (It should be // "LOCALTIME", which would have been handled as a // SqlIdentifier.) throw handleUnresolvedFunction(call, (SqlFunction) operator, ImmutableList.<RelDataType>of(), null); } SqlValidatorScope operandScope = scope.getOperandScope(call); if (operator instanceof SqlFunction && ((SqlFunction) operator).getFunctionType() == SqlFunctionCategory.MATCH_RECOGNIZE && !(operandScope instanceof MatchRecognizeScope)) { throw newValidationError(call, Static.RESOURCE.functionMatchRecognizeOnly(call.toString())); } // Delegate validation to the operator. operator.validateCall(call, this, scope, operandScope); } /** * Validates that a particular feature is enabled. By default, all features * are enabled; subclasses may override this method to be more * discriminating. * * @param feature feature being used, represented as a resource instance * @param context parser position context for error reporting, or null if */ protected void validateFeature( Feature feature, SqlParserPos context) { // By default, do nothing except to verify that the resource // represents a real feature definition. assert feature.getProperties().get("FeatureDefinition") != null; } public SqlNode expand(SqlNode expr, SqlValidatorScope scope) { final Expander expander = new Expander(this, scope); SqlNode newExpr = expr.accept(expander); if (expr != newExpr) { setOriginal(newExpr, expr); } return newExpr; } public SqlNode expandGroupByOrHavingExpr(SqlNode expr, SqlValidatorScope scope, SqlSelect select, boolean havingExpression) { final Expander expander = new ExtendedExpander(this, scope, select, expr, havingExpression); SqlNode newExpr = expr.accept(expander); if (expr != newExpr) { setOriginal(newExpr, expr); } return newExpr; } public boolean isSystemField(RelDataTypeField field) { return false; } public List<List<String>> getFieldOrigins(SqlNode sqlQuery) { if (sqlQuery instanceof SqlExplain) { return Collections.emptyList(); } final RelDataType rowType = getValidatedNodeType(sqlQuery); final int fieldCount = rowType.getFieldCount(); if (!sqlQuery.isA(SqlKind.QUERY)) { return Collections.nCopies(fieldCount, null); } final List<List<String>> list = new ArrayList<>(); for (int i = 0; i < fieldCount; i++) { list.add(getFieldOrigin(sqlQuery, i)); } return ImmutableNullableList.copyOf(list); } private List<String> getFieldOrigin(SqlNode sqlQuery, int i) { if (sqlQuery instanceof SqlSelect) { SqlSelect sqlSelect = (SqlSelect) sqlQuery; final SelectScope scope = getRawSelectScope(sqlSelect); final List<SqlNode> selectList = scope.getExpandedSelectList(); final SqlNode selectItem = stripAs(selectList.get(i)); if (selectItem instanceof SqlIdentifier) { final SqlQualified qualified = scope.fullyQualify((SqlIdentifier) selectItem); SqlValidatorNamespace namespace = qualified.namespace; final SqlValidatorTable table = namespace.getTable(); if (table == null) { return null; } final List<String> origin = new ArrayList<>(table.getQualifiedName()); for (String name : qualified.suffix()) { namespace = namespace.lookupChild(name); if (namespace == null) { return null; } origin.add(name); } return origin; } return null; } else if (sqlQuery instanceof SqlOrderBy) { return getFieldOrigin(((SqlOrderBy) sqlQuery).query, i); } else { return null; } } public RelDataType getParameterRowType(SqlNode sqlQuery) { // NOTE: We assume that bind variables occur in depth-first tree // traversal in the same order that they occurred in the SQL text. final List<RelDataType> types = new ArrayList<>(); sqlQuery.accept( new SqlShuttle() { @Override public SqlNode visit(SqlDynamicParam param) { RelDataType type = getValidatedNodeType(param); types.add(type); return param; } }); return typeFactory.createStructType( types, new AbstractList<String>() { @Override public String get(int index) { return "?" + index; } @Override public int size() { return types.size(); } }); } public void validateColumnListParams( SqlFunction function, List<RelDataType> argTypes, List<SqlNode> operands) { throw new UnsupportedOperationException(); } private static boolean isPhysicalNavigation(SqlKind kind) { return kind == SqlKind.PREV || kind == SqlKind.NEXT; } private static boolean isLogicalNavigation(SqlKind kind) { return kind == SqlKind.FIRST || kind == SqlKind.LAST; } private static boolean isAggregation(SqlKind kind) { return kind == SqlKind.SUM || kind == SqlKind.SUM0 || kind == SqlKind.AVG || kind == SqlKind.COUNT || kind == SqlKind.MAX || kind == SqlKind.MIN; } private static boolean isRunningOrFinal(SqlKind kind) { return kind == SqlKind.RUNNING || kind == SqlKind.FINAL; } private static boolean isSingleVarRequired(SqlKind kind) { return isPhysicalNavigation(kind) || isLogicalNavigation(kind) || isAggregation(kind); } //~ Inner Classes ---------------------------------------------------------- /** * Common base class for DML statement namespaces. */ public static class DmlNamespace extends IdentifierNamespace { protected DmlNamespace(SqlValidatorImpl validator, SqlNode id, SqlNode enclosingNode, SqlValidatorScope parentScope) { super(validator, id, enclosingNode, parentScope); } } /** * Namespace for an INSERT statement. */ private static class InsertNamespace extends DmlNamespace { private final SqlInsert node; InsertNamespace(SqlValidatorImpl validator, SqlInsert node, SqlNode enclosingNode, SqlValidatorScope parentScope) { super(validator, node.getTargetTable(), enclosingNode, parentScope); this.node = Preconditions.checkNotNull(node); } public SqlInsert getNode() { return node; } } /** * Namespace for an UPDATE statement. */ private static class UpdateNamespace extends DmlNamespace { private final SqlUpdate node; UpdateNamespace(SqlValidatorImpl validator, SqlUpdate node, SqlNode enclosingNode, SqlValidatorScope parentScope) { super(validator, node.getTargetTable(), enclosingNode, parentScope); this.node = Preconditions.checkNotNull(node); } public SqlUpdate getNode() { return node; } } /** * Namespace for a DELETE statement. */ private static class DeleteNamespace extends DmlNamespace { private final SqlDelete node; DeleteNamespace(SqlValidatorImpl validator, SqlDelete node, SqlNode enclosingNode, SqlValidatorScope parentScope) { super(validator, node.getTargetTable(), enclosingNode, parentScope); this.node = Preconditions.checkNotNull(node); } public SqlDelete getNode() { return node; } } /** * Namespace for a MERGE statement. */ private static class MergeNamespace extends DmlNamespace { private final SqlMerge node; MergeNamespace(SqlValidatorImpl validator, SqlMerge node, SqlNode enclosingNode, SqlValidatorScope parentScope) { super(validator, node.getTargetTable(), enclosingNode, parentScope); this.node = Preconditions.checkNotNull(node); } public SqlMerge getNode() { return node; } } /** * retrieve pattern variables defined */ private class PatternVarVisitor implements SqlVisitor<Void> { private MatchRecognizeScope scope; PatternVarVisitor(MatchRecognizeScope scope) { this.scope = scope; } @Override public Void visit(SqlLiteral literal) { return null; } @Override public Void visit(SqlCall call) { for (int i = 0; i < call.getOperandList().size(); i++) { call.getOperandList().get(i).accept(this); } return null; } @Override public Void visit(SqlNodeList nodeList) { throw Util.needToImplement(nodeList); } @Override public Void visit(SqlIdentifier id) { Preconditions.checkArgument(id.isSimple()); scope.addPatternVar(id.getSimple()); return null; } @Override public Void visit(SqlDataTypeSpec type) { throw Util.needToImplement(type); } @Override public Void visit(SqlDynamicParam param) { throw Util.needToImplement(param); } @Override public Void visit(SqlIntervalQualifier intervalQualifier) { throw Util.needToImplement(intervalQualifier); } } /** * Visitor which derives the type of a given {@link SqlNode}. * * <p>Each method must return the derived type. This visitor is basically a * single-use dispatcher; the visit is never recursive. */ private class DeriveTypeVisitor implements SqlVisitor<RelDataType> { private final SqlValidatorScope scope; DeriveTypeVisitor(SqlValidatorScope scope) { this.scope = scope; } public RelDataType visit(SqlLiteral literal) { return literal.createSqlType(typeFactory); } public RelDataType visit(SqlCall call) { final SqlOperator operator = call.getOperator(); return operator.deriveType(SqlValidatorImpl.this, scope, call); } public RelDataType visit(SqlNodeList nodeList) { // Operand is of a type that we can't derive a type for. If the // operand is of a peculiar type, such as a SqlNodeList, then you // should override the operator's validateCall() method so that it // doesn't try to validate that operand as an expression. throw Util.needToImplement(nodeList); } public RelDataType visit(SqlIdentifier id) { // First check for builtin functions which don't have parentheses, // like "LOCALTIME". SqlCall call = SqlUtil.makeCall(opTab, id); if (call != null) { return call.getOperator().validateOperands( SqlValidatorImpl.this, scope, call); } RelDataType type = null; if (!(scope instanceof EmptyScope)) { id = scope.fullyQualify(id).identifier; } // Resolve the longest prefix of id that we can int i; for (i = id.names.size() - 1; i > 0; i--) { // REVIEW jvs 9-June-2005: The name resolution rules used // here are supposed to match SQL:2003 Part 2 Section 6.6 // (identifier chain), but we don't currently have enough // information to get everything right. In particular, // routine parameters are currently looked up via resolve; // we could do a better job if they were looked up via // resolveColumn. final SqlNameMatcher nameMatcher = catalogReader.nameMatcher(); final SqlValidatorScope.ResolvedImpl resolved = new SqlValidatorScope.ResolvedImpl(); scope.resolve(id.names.subList(0, i), nameMatcher, false, resolved); if (resolved.count() == 1) { // There's a namespace with the name we seek. final SqlValidatorScope.Resolve resolve = resolved.only(); type = resolve.rowType(); for (SqlValidatorScope.Step p : Util.skip(resolve.path.steps())) { type = type.getFieldList().get(p.i).getType(); } break; } } // Give precedence to namespace found, unless there // are no more identifier components. if (type == null || id.names.size() == 1) { // See if there's a column with the name we seek in // precisely one of the namespaces in this scope. RelDataType colType = scope.resolveColumn(id.names.get(0), id); if (colType != null) { type = colType; } ++i; } if (type == null) { final SqlIdentifier last = id.getComponent(i - 1, i); throw newValidationError(last, RESOURCE.unknownIdentifier(last.toString())); } // Resolve rest of identifier for (; i < id.names.size(); i++) { String name = id.names.get(i); final RelDataTypeField field; if (name.equals("")) { // The wildcard "*" is represented as an empty name. It never // resolves to a field. name = "*"; field = null; } else { final SqlNameMatcher nameMatcher = catalogReader.nameMatcher(); field = nameMatcher.field(type, name); } if (field == null) { throw newValidationError(id.getComponent(i), RESOURCE.unknownField(name)); } type = field.getType(); } type = SqlTypeUtil.addCharsetAndCollation( type, getTypeFactory()); return type; } public RelDataType visit(SqlDataTypeSpec dataType) { // Q. How can a data type have a type? // A. When it appears in an expression. (Say as the 2nd arg to the // CAST operator.) validateDataType(dataType); return dataType.deriveType(SqlValidatorImpl.this); } public RelDataType visit(SqlDynamicParam param) { return unknownType; } public RelDataType visit(SqlIntervalQualifier intervalQualifier) { return typeFactory.createSqlIntervalType(intervalQualifier); } } /** * Converts an expression into canonical form by fully-qualifying any * identifiers. */ private static class Expander extends SqlScopedShuttle { protected final SqlValidatorImpl validator; Expander(SqlValidatorImpl validator, SqlValidatorScope scope) { super(scope); this.validator = validator; } @Override public SqlNode visit(SqlIdentifier id) { // First check for builtin functions which don't have // parentheses, like "LOCALTIME". SqlCall call = SqlUtil.makeCall( validator.getOperatorTable(), id); if (call != null) { return call.accept(this); } final SqlIdentifier fqId = getScope().fullyQualify(id).identifier; SqlNode expandedExpr = fqId; // Convert a column ref into ITEM(*, 'col_name'). // select col_name from (select * from dynTable) // SqlIdentifier "col_name" would be resolved to a dynamic star field in dynTable's rowType. // Expand such SqlIdentifier to ITEM operator. if (DynamicRecordType.isDynamicStarColName(Util.last(fqId.names)) && !DynamicRecordType.isDynamicStarColName(Util.last(id.names))) { SqlNode[] inputs = new SqlNode[2]; inputs[0] = fqId; inputs[1] = SqlLiteral.createCharString( Util.last(id.names), id.getParserPosition()); SqlBasicCall item_call = new SqlBasicCall( SqlStdOperatorTable.ITEM, inputs, id.getParserPosition()); expandedExpr = item_call; } validator.setOriginal(expandedExpr, id); return expandedExpr; } @Override protected SqlNode visitScoped(SqlCall call) { switch (call.getKind()) { case SCALAR_QUERY: case CURRENT_VALUE: case NEXT_VALUE: case WITH: return call; } // Only visits arguments which are expressions. We don't want to // qualify non-expressions such as 'x' in 'empno * 5 AS x'. ArgHandler<SqlNode> argHandler = new CallCopyingArgHandler(call, false); call.getOperator().acceptCall(this, call, true, argHandler); final SqlNode result = argHandler.result(); validator.setOriginal(result, call); return result; } } /** * Shuttle which walks over an expression in the ORDER BY clause, replacing * usages of aliases with the underlying expression. */ class OrderExpressionExpander extends SqlScopedShuttle { private final List<String> aliasList; private final SqlSelect select; private final SqlNode root; OrderExpressionExpander(SqlSelect select, SqlNode root) { super(getOrderScope(select)); this.select = select; this.root = root; this.aliasList = getNamespace(select).getRowType().getFieldNames(); } public SqlNode go() { return root.accept(this); } public SqlNode visit(SqlLiteral literal) { // Ordinal markers, e.g. 'select a, b from t order by 2'. // Only recognize them if they are the whole expression, // and if the dialect permits. if (literal == root && getConformance().isSortByOrdinal()) { switch (literal.getTypeName()) { case DECIMAL: case DOUBLE: final int intValue = literal.intValue(false); if (intValue >= 0) { if (intValue < 1 || intValue > aliasList.size()) { throw newValidationError( literal, RESOURCE.orderByOrdinalOutOfRange()); } // SQL ordinals are 1-based, but Sort's are 0-based int ordinal = intValue - 1; return nthSelectItem(ordinal, literal.getParserPosition()); } break; } } return super.visit(literal); } /** * Returns the <code>ordinal</code>th item in the select list. */ private SqlNode nthSelectItem(int ordinal, final SqlParserPos pos) { // TODO: Don't expand the list every time. Maybe keep an expanded // version of each expression -- select lists and identifiers -- in // the validator. SqlNodeList expandedSelectList = expandStar( select.getSelectList(), select, false); SqlNode expr = expandedSelectList.get(ordinal); expr = stripAs(expr); if (expr instanceof SqlIdentifier) { expr = getScope().fullyQualify((SqlIdentifier) expr).identifier; } // Create a copy of the expression with the position of the order // item. return expr.clone(pos); } public SqlNode visit(SqlIdentifier id) { // Aliases, e.g. 'select a as x, b from t order by x'. if (id.isSimple() && getConformance().isSortByAlias()) { String alias = id.getSimple(); final SqlValidatorNamespace selectNs = getNamespace(select); final RelDataType rowType = selectNs.getRowTypeSansSystemColumns(); final SqlNameMatcher nameMatcher = catalogReader.nameMatcher(); RelDataTypeField field = nameMatcher.field(rowType, alias); if (field != null) { return nthSelectItem( field.getIndex(), id.getParserPosition()); } } // No match. Return identifier unchanged. return getScope().fullyQualify(id).identifier; } protected SqlNode visitScoped(SqlCall call) { // Don't attempt to expand sub-queries. We haven't implemented // these yet. if (call instanceof SqlSelect) { return call; } return super.visitScoped(call); } } /** * Shuttle which walks over an expression in the GROUP BY/HAVING clause, replacing * usages of aliases or ordinals with the underlying expression. */ static class ExtendedExpander extends Expander { final SqlSelect select; final SqlNode root; final boolean havingExpr; ExtendedExpander(SqlValidatorImpl validator, SqlValidatorScope scope, SqlSelect select, SqlNode root, boolean havingExpr) { super(validator, scope); this.select = select; this.root = root; this.havingExpr = havingExpr; } @Override public SqlNode visit(SqlIdentifier id) { if (id.isSimple() && (havingExpr ? validator.getConformance().isHavingAlias() : validator.getConformance().isGroupByAlias())) { String name = id.getSimple(); SqlNode expr = null; final SqlNameMatcher nameMatcher = validator.catalogReader.nameMatcher(); int n = 0; for (SqlNode s : select.getSelectList()) { final String alias = SqlValidatorUtil.getAlias(s, -1); if (alias != null && nameMatcher.matches(alias, name)) { expr = s; n++; } } if (n == 0) { return super.visit(id); } else if (n > 1) { // More than one column has this alias. throw validator.newValidationError(id, RESOURCE.columnAmbiguous(name)); } if (havingExpr && validator.isAggregate(root)) { return super.visit(id); } expr = stripAs(expr); if (expr instanceof SqlIdentifier) { expr = getScope().fullyQualify((SqlIdentifier) expr).identifier; } return expr; } return super.visit(id); } public SqlNode visit(SqlLiteral literal) { if (havingExpr || !validator.getConformance().isGroupByOrdinal()) { return super.visit(literal); } boolean isOrdinalLiteral = literal == root; switch (root.getKind()) { case GROUPING_SETS: case ROLLUP: case CUBE: if (root instanceof SqlBasicCall) { List<SqlNode> operandList = ((SqlBasicCall) root).getOperandList(); for (SqlNode node : operandList) { if (node.equals(literal)) { isOrdinalLiteral = true; break; } } } break; } if (isOrdinalLiteral) { switch (literal.getTypeName()) { case DECIMAL: case DOUBLE: final int intValue = literal.intValue(false); if (intValue >= 0) { if (intValue < 1 || intValue > select.getSelectList().size()) { throw validator.newValidationError(literal, RESOURCE.orderByOrdinalOutOfRange()); } // SQL ordinals are 1-based, but Sort's are 0-based int ordinal = intValue - 1; return SqlUtil.stripAs(select.getSelectList().get(ordinal)); } break; } } return super.visit(literal); } } /** Information about an identifier in a particular scope. */ protected static class IdInfo { public final SqlValidatorScope scope; public final SqlIdentifier id; public IdInfo(SqlValidatorScope scope, SqlIdentifier id) { this.scope = scope; this.id = id; } } /** * Utility object used to maintain information about the parameters in a * function call. */ protected static class FunctionParamInfo { /** * Maps a cursor (based on its position relative to other cursor * parameters within a function call) to the SELECT associated with the * cursor. */ public final Map<Integer, SqlSelect> cursorPosToSelectMap; /** * Maps a column list parameter to the parent cursor parameter it * references. The parameters are id'd by their names. */ public final Map<String, String> columnListParamToParentCursorMap; public FunctionParamInfo() { cursorPosToSelectMap = new HashMap<>(); columnListParamToParentCursorMap = new HashMap<>(); } } /** * Modify the nodes in navigation function * such as FIRST, LAST, PREV AND NEXT. */ private class NavigationModifier extends SqlBasicVisitor<SqlNode> { @Override public SqlNode visit(SqlLiteral literal) { return literal; } @Override public SqlNode visit(SqlIntervalQualifier intervalQualifier) { return intervalQualifier; } @Override public SqlNode visit(SqlDataTypeSpec type) { return type; } @Override public SqlNode visit(SqlDynamicParam param) { return param; } public SqlNode go(SqlNode node) { return node.accept(this); } } /** * Expand navigation expression : * eg: PREV(A.price + A.amount) to PREV(A.price) + PREV(A.amount) * eg: FIRST(A.price * 2) to FIST(A.PRICE) * 2 */ private class NavigationExpander extends NavigationModifier { SqlOperator currentOperator; SqlNode currentOffset; NavigationExpander() { } NavigationExpander(SqlOperator operator, SqlNode offset) { this.currentOffset = offset; this.currentOperator = operator; } @Override public SqlNode visit(SqlCall call) { SqlKind kind = call.getKind(); List<SqlNode> operands = call.getOperandList(); List<SqlNode> newOperands = new ArrayList<>(); if (isLogicalNavigation(kind) || isPhysicalNavigation(kind)) { SqlNode inner = operands.get(0); SqlNode offset = operands.get(1); // merge two straight prev/next, update offset if (isPhysicalNavigation(kind)) { SqlKind innerKind = inner.getKind(); if (isPhysicalNavigation(innerKind)) { List<SqlNode> innerOperands = ((SqlCall) inner).getOperandList(); SqlNode innerOffset = innerOperands.get(1); SqlOperator newOperator = innerKind == kind ? SqlStdOperatorTable.PLUS : SqlStdOperatorTable.MINUS; offset = newOperator.createCall(SqlParserPos.ZERO, offset, innerOffset); inner = call.getOperator().createCall(SqlParserPos.ZERO, innerOperands.get(0), offset); } } return inner.accept(new NavigationExpander(call.getOperator(), offset)); } for (SqlNode node : operands) { SqlNode newNode = node.accept(new NavigationExpander()); if (currentOperator != null) { newNode = currentOperator.createCall(SqlParserPos.ZERO, newNode, currentOffset); } newOperands.add(newNode); } return call.getOperator().createCall(SqlParserPos.ZERO, newOperands); } @Override public SqlNode visit(SqlIdentifier id) { if (currentOperator == null) { return id; } else { return currentOperator.createCall(SqlParserPos.ZERO, id, currentOffset); } } } /** * Replace {@code A as A.price > PREV(B.price)} * with {@code PREV(A.price, 0) > last(B.price, 0)}. */ private class NavigationReplacer extends NavigationModifier { private final String alpha; NavigationReplacer(String alpha) { this.alpha = alpha; } @Override public SqlNode visit(SqlCall call) { SqlKind kind = call.getKind(); if (isLogicalNavigation(kind) || isAggregation(kind) || isRunningOrFinal(kind)) { return call; } List<SqlNode> operands = call.getOperandList(); switch (kind) { case PREV: String name = ((SqlIdentifier) operands.get(0)).names.get(0); return name.equals(alpha) ? call : SqlStdOperatorTable.LAST.createCall(SqlParserPos.ZERO, operands); default: List<SqlNode> newOperands = new ArrayList<>(); for (SqlNode op : operands) { newOperands.add(op.accept(this)); } return call.getOperator().createCall(SqlParserPos.ZERO, newOperands); } } @Override public SqlNode visit(SqlIdentifier id) { if (id.isSimple()) { return id; } SqlOperator operator = id.names.get(0).equals(alpha) ? SqlStdOperatorTable.PREV : SqlStdOperatorTable.LAST; return operator.createCall(SqlParserPos.ZERO, id, SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO)); } } /** * Within one navigation function, the pattern var should be same */ private class PatternValidator extends SqlBasicVisitor<Set<String>> { private final boolean isMeasure; int firstLastCount; int prevNextCount; int aggregateCount; PatternValidator(boolean isMeasure) { this(isMeasure, 0, 0, 0); } PatternValidator(boolean isMeasure, int firstLastCount, int prevNextCount, int aggregateCount) { this.isMeasure = isMeasure; this.firstLastCount = firstLastCount; this.prevNextCount = prevNextCount; this.aggregateCount = aggregateCount; } @Override public Set<String> visit(SqlCall call) { boolean isSingle = false; Set<String> vars = new HashSet<>(); SqlKind kind = call.getKind(); List<SqlNode> operands = call.getOperandList(); if (isSingleVarRequired(kind)) { isSingle = true; if (isPhysicalNavigation(kind)) { if (isMeasure) { throw newValidationError(call, Static.RESOURCE.patternPrevFunctionInMeasure(call.toString())); } if (firstLastCount != 0) { throw newValidationError(call, Static.RESOURCE.patternPrevFunctionOrder(call.toString())); } prevNextCount++; } else if (isLogicalNavigation(kind)) { if (firstLastCount != 0) { throw newValidationError(call, Static.RESOURCE.patternPrevFunctionOrder(call.toString())); } firstLastCount++; } else if (isAggregation(kind)) { // cannot apply aggregation in PREV/NEXT, FIRST/LAST if (firstLastCount != 0 || prevNextCount != 0) { throw newValidationError(call, Static.RESOURCE.patternAggregationInNavigation(call.toString())); } if (kind == SqlKind.COUNT && call.getOperandList().size() > 1) { throw newValidationError(call, Static.RESOURCE.patternCountFunctionArg()); } aggregateCount++; } } if (isRunningOrFinal(kind) && !isMeasure) { throw newValidationError(call, Static.RESOURCE.patternRunningFunctionInDefine(call.toString())); } for (SqlNode node : operands) { vars.addAll( node.accept( new PatternValidator(isMeasure, firstLastCount, prevNextCount, aggregateCount))); } if (isSingle) { switch (kind) { case COUNT: if (vars.size() > 1) { throw newValidationError(call, Static.RESOURCE.patternCountFunctionArg()); } break; default: if (vars.isEmpty()) { throw newValidationError(call, Static.RESOURCE.patternFunctionNullCheck(call.toString())); } if (vars.size() != 1) { throw newValidationError(call, Static.RESOURCE.patternFunctionVariableCheck(call.toString())); } break; } } return vars; } @Override public Set<String> visit(SqlIdentifier identifier) { boolean check = prevNextCount > 0 || firstLastCount > 0 || aggregateCount > 0; Set<String> vars = new HashSet<>(); if (identifier.names.size() > 1 && check) { vars.add(identifier.names.get(0)); } return vars; } @Override public Set<String> visit(SqlLiteral literal) { return ImmutableSet.of(); } @Override public Set<String> visit(SqlIntervalQualifier qualifier) { return ImmutableSet.of(); } @Override public Set<String> visit(SqlDataTypeSpec type) { return ImmutableSet.of(); } @Override public Set<String> visit(SqlDynamicParam param) { return ImmutableSet.of(); } } //~ Enums ------------------------------------------------------------------ /** * Validation status. */ public enum Status { /** * Validation has not started for this scope. */ UNVALIDATED, /** * Validation is in progress for this scope. */ IN_PROGRESS, /** * Validation has completed (perhaps unsuccessfully). */ VALID } } // End SqlValidatorImpl.java
apache-2.0
itgeeker/jdk
src/com/sun/org/apache/bcel/internal/generic/IUSHR.java
3678
/* * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.org.apache.bcel.internal.generic; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * IUSHR - Logical shift right int * <PRE>Stack: ..., value1, value2 -&gt; ..., result</PRE> * * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A> */ public class IUSHR extends ArithmeticInstruction { public IUSHR() { super(com.sun.org.apache.bcel.internal.Constants.IUSHR); } /** * Call corresponding visitor method(s). The order is: * Call visitor methods of implemented interfaces first, then * call methods according to the class hierarchy in descending order, * i.e., the most specific visitXXX() call comes last. * * @param v Visitor object */ public void accept(Visitor v) { v.visitTypedInstruction(this); v.visitStackProducer(this); v.visitStackConsumer(this); v.visitArithmeticInstruction(this); v.visitIUSHR(this); } }
apache-2.0
jimv39/qvcsos
qvcse-qvcslib/src/main/java/com/qumasoft/qvcslib/notifications/package-info.java
771
/* Copyright 2004-2014 Jim Voris * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains notification messages sent asynchronously from the server to client listeners. */ package com.qumasoft.qvcslib.notifications;
apache-2.0
eliasah/elasticsearch-hadoop
mr/src/main/java/org/elasticsearch/hadoop/rest/commonshttp/DelegatedProtocol.java
1604
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.hadoop.rest.commonshttp; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; /** * Class used to make sure wrapped protocol object is behaving like the original one. * Otherwise this leads to connections not being closed (as they are considered different). */ class DelegatedProtocol extends Protocol { private final Protocol original; DelegatedProtocol(ProtocolSocketFactory factory, Protocol original, String scheme, int port) { super(scheme, factory, port); this.original = original; } public boolean equals(Object obj) { return (obj instanceof DelegatedProtocol ? true : original.equals(obj)); } public int hashCode() { return original.hashCode(); } }
apache-2.0
gwtproject/gwt-event-dom
gwt-event-dom/src/main/java/org/gwtproject/event/dom/client/FocusHandler.java
966
/* * Copyright © 2019 The GWT Project 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.gwtproject.event.dom.client; import org.gwtproject.event.legacy.shared.EventHandler; /** Handler interface for {@link FocusEvent} events. */ public interface FocusHandler extends EventHandler { /** * Called when FocusEvent is fired. * * @param event the {@link FocusEvent} that was fired */ void onFocus(FocusEvent event); }
apache-2.0
creatorYC/yechblog
src/com/yech/yechblog/service/ReplyService.java
430
package com.yech.yechblog.service; import java.util.List; import com.yech.yechblog.entity.Reply; public interface ReplyService { /** * ±£´æreply */ public void saveReply(Reply model); /** * ¸ù¾Ýµ±Ç°ÆÀÂÛid²éѯ´ËÆÀÂÛµÄËùÓлظ´ * @return */ public List<Reply> queryAllReplies(Integer id); /** * ¸ù¾Ýµ±Ç°answer id²éѯ´Ë´ð°¸µÄËùÓÐ×·ÎÊ * @return */ public List<Reply> queryAllQuestionReplies(Integer id); }
apache-2.0
aesterline/autopair
src/main/java/org/autopair/monitor/FilteredFileSystemChangeListener.java
752
package org.autopair.monitor; import java.util.List; import org.apache.commons.collections.CollectionUtils; public class FilteredFileSystemChangeListener implements FileSystemChangeListener { private FileSystemChangeFilter filter; private FileSystemChangeListener delegatee; public FilteredFileSystemChangeListener(FileSystemChangeFilter filter, FileSystemChangeListener delegatee) { this.filter = filter; this.delegatee = delegatee; } public void changes(List<FileSystemChange> changes) { List<FileSystemChange> filteredChanges = filter.selectMatching(changes); if(CollectionUtils.isNotEmpty(filteredChanges)) { delegatee.changes(filteredChanges); } } }
apache-2.0
davidzchen/bazel
src/main/java/com/google/devtools/build/lib/skyframe/AspectFunction.java
32814
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skyframe; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException; import com.google.devtools.build.lib.analysis.AliasProvider; import com.google.devtools.build.lib.analysis.AspectResolver; import com.google.devtools.build.lib.analysis.AspectValue; import com.google.devtools.build.lib.analysis.CachingAnalysisEnvironment; import com.google.devtools.build.lib.analysis.CachingAnalysisEnvironment.MissingDepException; import com.google.devtools.build.lib.analysis.ConfiguredAspect; import com.google.devtools.build.lib.analysis.ConfiguredAspectFactory; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.DependencyKind; import com.google.devtools.build.lib.analysis.DuplicateException; import com.google.devtools.build.lib.analysis.InconsistentAspectOrderException; import com.google.devtools.build.lib.analysis.PlatformOptions; import com.google.devtools.build.lib.analysis.ResolvedToolchainContext; import com.google.devtools.build.lib.analysis.RuleContext.InvalidExecGroupException; import com.google.devtools.build.lib.analysis.TargetAndConfiguration; import com.google.devtools.build.lib.analysis.ToolchainCollection; import com.google.devtools.build.lib.analysis.config.BuildConfiguration; import com.google.devtools.build.lib.analysis.config.BuildOptions; import com.google.devtools.build.lib.analysis.config.ConfigMatchingProvider; import com.google.devtools.build.lib.analysis.config.DependencyEvaluationException; import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException; import com.google.devtools.build.lib.analysis.configuredtargets.MergedConfiguredTarget; import com.google.devtools.build.lib.analysis.starlark.StarlarkTransition.TransitionException; import com.google.devtools.build.lib.causes.Cause; import com.google.devtools.build.lib.causes.LabelCause; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.StoredEventHandler; import com.google.devtools.build.lib.packages.Aspect; import com.google.devtools.build.lib.packages.AspectDefinition; import com.google.devtools.build.lib.packages.AspectDescriptor; import com.google.devtools.build.lib.packages.BuildFileContainsErrorsException; import com.google.devtools.build.lib.packages.NativeAspectClass; import com.google.devtools.build.lib.packages.NoSuchTargetException; import com.google.devtools.build.lib.packages.NoSuchThingException; import com.google.devtools.build.lib.packages.OutputFile; import com.google.devtools.build.lib.packages.Package; import com.google.devtools.build.lib.packages.RuleClassProvider; import com.google.devtools.build.lib.packages.StarlarkAspect; import com.google.devtools.build.lib.packages.StarlarkAspectClass; import com.google.devtools.build.lib.packages.StarlarkDefinedAspect; import com.google.devtools.build.lib.packages.Target; import com.google.devtools.build.lib.packages.Type.ConversionException; import com.google.devtools.build.lib.profiler.memory.CurrentRuleTracker; import com.google.devtools.build.lib.skyframe.AspectValueKey.AspectKey; import com.google.devtools.build.lib.skyframe.BzlLoadFunction.BzlLoadFailedException; import com.google.devtools.build.lib.skyframe.SkyframeExecutor.BuildViewProvider; import com.google.devtools.build.lib.util.OrderedSetMultimap; import com.google.devtools.build.skyframe.SkyFunction; import com.google.devtools.build.skyframe.SkyFunctionException; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.SkyValue; import com.google.devtools.build.skyframe.ValueOrException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; /** * The Skyframe function that generates aspects. * * This class, together with {@link ConfiguredTargetFunction} drives the analysis phase. For more * information, see {@link com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory}. * * {@link AspectFunction} takes a SkyKey containing an {@link AspectKey} [a tuple of * (target label, configurations, aspect class and aspect parameters)], * loads an {@link Aspect} from aspect class and aspect parameters, * gets a {@link ConfiguredTarget} for label and configurations, and then creates * a {@link ConfiguredAspect} for a given {@link AspectKey}. * * See {@link com.google.devtools.build.lib.packages.AspectClass} documentation * for an overview of aspect-related classes * * @see com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory * @see com.google.devtools.build.lib.packages.AspectClass */ public final class AspectFunction implements SkyFunction { private final BuildViewProvider buildViewProvider; private final RuleClassProvider ruleClassProvider; private final BuildOptions defaultBuildOptions; /** * Indicates whether the set of packages transitively loaded for a given {@link AspectValue} will * be needed for package root resolution later in the build. If not, they are not collected and * stored. */ private final boolean storeTransitivePackagesForPackageRootResolution; AspectFunction( BuildViewProvider buildViewProvider, RuleClassProvider ruleClassProvider, boolean storeTransitivePackagesForPackageRootResolution, BuildOptions defaultBuildOptions) { this.buildViewProvider = buildViewProvider; this.ruleClassProvider = ruleClassProvider; this.storeTransitivePackagesForPackageRootResolution = storeTransitivePackagesForPackageRootResolution; this.defaultBuildOptions = defaultBuildOptions; } /** * Load Starlark-defined aspect from an extension file. Is to be called from a SkyFunction. * * @return {@code null} if dependencies cannot be satisfied. * @throws AspectCreationException if the value loaded is not a {@link StarlarkDefinedAspect}. */ @Nullable static StarlarkDefinedAspect loadStarlarkDefinedAspect( Environment env, StarlarkAspectClass starlarkAspectClass) throws AspectCreationException, InterruptedException { Label extensionLabel = starlarkAspectClass.getExtensionLabel(); String starlarkValueName = starlarkAspectClass.getExportedName(); StarlarkAspect starlarkAspect = loadStarlarkAspect(env, extensionLabel, starlarkValueName); if (starlarkAspect == null) { return null; } if (!(starlarkAspect instanceof StarlarkDefinedAspect)) { throw new AspectCreationException( String.format( "%s from %s is not a Starlark-defined aspect", starlarkValueName, extensionLabel), extensionLabel); } else { return (StarlarkDefinedAspect) starlarkAspect; } } /** * Load Starlark aspect from an extension file. Is to be called from a SkyFunction. * * @return {@code null} if dependencies cannot be satisfied. */ @Nullable static StarlarkAspect loadStarlarkAspect( Environment env, Label extensionLabel, String starlarkValueName) throws AspectCreationException, InterruptedException { SkyKey importFileKey = BzlLoadValue.keyForBuild(extensionLabel); try { BzlLoadValue bzlLoadValue = (BzlLoadValue) env.getValueOrThrow(importFileKey, BzlLoadFailedException.class); if (bzlLoadValue == null) { Preconditions.checkState( env.valuesMissing(), "no Starlark import value for %s", importFileKey); return null; } Object starlarkValue = bzlLoadValue.getModule().getGlobal(starlarkValueName); if (starlarkValue == null) { throw new ConversionException( String.format( "%s is not exported from %s", starlarkValueName, extensionLabel.toString())); } if (!(starlarkValue instanceof StarlarkAspect)) { throw new ConversionException( String.format( "%s from %s is not an aspect", starlarkValueName, extensionLabel.toString())); } return (StarlarkAspect) starlarkValue; } catch (BzlLoadFailedException e) { env.getListener().handle(Event.error(e.getMessage())); throw new AspectCreationException(e.getMessage(), extensionLabel, e.getDetailedExitCode()); } catch (ConversionException e) { env.getListener().handle(Event.error(e.getMessage())); throw new AspectCreationException(e.getMessage(), extensionLabel); } } @Nullable @Override public SkyValue compute(SkyKey skyKey, Environment env) throws AspectFunctionException, InterruptedException { SkyframeBuildView view = buildViewProvider.getSkyframeBuildView(); NestedSetBuilder<Cause> transitiveRootCauses = NestedSetBuilder.stableOrder(); AspectKey key = (AspectKey) skyKey.argument(); ConfiguredAspectFactory aspectFactory; Aspect aspect; if (key.getAspectClass() instanceof NativeAspectClass) { NativeAspectClass nativeAspectClass = (NativeAspectClass) key.getAspectClass(); aspectFactory = (ConfiguredAspectFactory) nativeAspectClass; aspect = Aspect.forNative(nativeAspectClass, key.getParameters()); } else if (key.getAspectClass() instanceof StarlarkAspectClass) { StarlarkAspectClass starlarkAspectClass = (StarlarkAspectClass) key.getAspectClass(); StarlarkDefinedAspect starlarkAspect; try { starlarkAspect = loadStarlarkDefinedAspect(env, starlarkAspectClass); } catch (AspectCreationException e) { throw new AspectFunctionException(e); } if (starlarkAspect == null) { return null; } aspectFactory = new StarlarkAspectFactory(starlarkAspect); aspect = Aspect.forStarlark( starlarkAspect.getAspectClass(), starlarkAspect.getDefinition(key.getParameters()), key.getParameters()); } else { throw new IllegalStateException(); } // Keep this in sync with the same code in ConfiguredTargetFunction. PackageValue packageValue = (PackageValue) env.getValue(PackageValue.key(key.getLabel().getPackageIdentifier())); if (packageValue == null) { return null; } Package pkg = packageValue.getPackage(); if (pkg.containsErrors()) { throw new AspectFunctionException( new BuildFileContainsErrorsException(key.getLabel().getPackageIdentifier())); } boolean aspectHasConfiguration = key.getAspectConfigurationKey() != null; ImmutableSet<SkyKey> keys = aspectHasConfiguration ? ImmutableSet.of(key.getBaseConfiguredTargetKey(), key.getAspectConfigurationKey()) : ImmutableSet.of(key.getBaseConfiguredTargetKey()); Map<SkyKey, ValueOrException<ConfiguredValueCreationException>> baseAndAspectValues = env.getValuesOrThrow(keys, ConfiguredValueCreationException.class); if (env.valuesMissing()) { return null; } ConfiguredTargetValue baseConfiguredTargetValue; BuildConfiguration aspectConfiguration = null; try { baseConfiguredTargetValue = (ConfiguredTargetValue) baseAndAspectValues.get(key.getBaseConfiguredTargetKey()).get(); } catch (ConfiguredValueCreationException e) { throw new AspectFunctionException( new AspectCreationException(e.getMessage(), e.getRootCauses(), e.getDetailedExitCode())); } if (aspectHasConfiguration) { try { aspectConfiguration = ((BuildConfigurationValue) baseAndAspectValues.get(key.getAspectConfigurationKey()).get()) .getConfiguration(); } catch (ConfiguredValueCreationException e) { throw new IllegalStateException("Unexpected exception from BuildConfigurationFunction when " + "computing " + key.getAspectConfigurationKey(), e); } if (aspectConfiguration.trimConfigurationsRetroactively()) { throw new AssertionError("Aspects should NEVER be evaluated in retroactive trimming mode."); } } ConfiguredTarget associatedTarget = baseConfiguredTargetValue.getConfiguredTarget(); ConfiguredTargetAndData associatedConfiguredTargetAndData; Package targetPkg; BuildConfiguration configuration = null; PackageValue.Key packageKey = PackageValue.key(associatedTarget.getLabel().getPackageIdentifier()); if (associatedTarget.getConfigurationKey() == null) { PackageValue val = ((PackageValue) env.getValue(packageKey)); if (val == null) { // Unexpected in Bazel logic, but Skyframe makes no guarantees that this package is // actually present. return null; } targetPkg = val.getPackage(); } else { Map<SkyKey, SkyValue> result = env.getValues(ImmutableSet.of(packageKey, associatedTarget.getConfigurationKey())); if (env.valuesMissing()) { // Unexpected in Bazel logic, but Skyframe makes no guarantees that this package and // configuration are actually present. return null; } targetPkg = ((PackageValue) result.get(packageKey)).getPackage(); configuration = ((BuildConfigurationValue) result.get(associatedTarget.getConfigurationKey())) .getConfiguration(); if (configuration.trimConfigurationsRetroactively()) { throw new AssertionError("Aspects should NEVER be evaluated in retroactive trimming mode."); } } try { associatedConfiguredTargetAndData = new ConfiguredTargetAndData( associatedTarget, targetPkg.getTarget(associatedTarget.getLabel().getName()), configuration, null); } catch (NoSuchTargetException e) { throw new IllegalStateException("Name already verified", e); } if (baseConfiguredTargetValue.getConfiguredTarget().getProvider(AliasProvider.class) != null) { return createAliasAspect( env, associatedConfiguredTargetAndData.getTarget(), aspect, key, baseConfiguredTargetValue.getConfiguredTarget()); } ImmutableList.Builder<Aspect> aspectPathBuilder = ImmutableList.builder(); if (!key.getBaseKeys().isEmpty()) { // We transitively collect all required aspects to reduce the number of restarts. // Semantically it is enough to just request key.getBaseKeys(). ImmutableList.Builder<SkyKey> aspectPathSkyKeysBuilder = ImmutableList.builder(); ImmutableMap<AspectDescriptor, SkyKey> aspectKeys = getSkyKeysForAspectsAndCollectAspectPath(key.getBaseKeys(), aspectPathSkyKeysBuilder); Map<SkyKey, SkyValue> values = env.getValues(aspectKeys.values()); if (env.valuesMissing()) { return null; } ImmutableList<SkyKey> aspectPathSkyKeys = aspectPathSkyKeysBuilder.build(); for (SkyKey aspectPathSkyKey : aspectPathSkyKeys) { aspectPathBuilder.add(((AspectValue) values.get(aspectPathSkyKey)).getAspect()); } try { associatedTarget = getBaseTarget( associatedTarget, key.getBaseKeys(), values); } catch (DuplicateException e) { env.getListener() .handle( Event.error( associatedConfiguredTargetAndData.getTarget().getLocation(), e.getMessage())); throw new AspectFunctionException( new AspectCreationException( e.getMessage(), associatedTarget.getLabel(), aspectConfiguration)); } } associatedConfiguredTargetAndData = associatedConfiguredTargetAndData.fromConfiguredTarget(associatedTarget); aspectPathBuilder.add(aspect); SkyframeDependencyResolver resolver = view.createDependencyResolver(env); NestedSetBuilder<Package> transitivePackagesForPackageRootResolution = storeTransitivePackagesForPackageRootResolution ? NestedSetBuilder.stableOrder() : null; // When getting the dependencies of this hybrid aspect+base target, use the aspect's // configuration. The configuration of the aspect will always be a superset of the target's // (trimmed configuration mode: target is part of the aspect's config fragment requirements; // untrimmed mode: target is the same configuration as the aspect), so the fragments // required by all dependencies (both those of the aspect and those of the base target) // will be present this way. TargetAndConfiguration originalTargetAndAspectConfiguration = new TargetAndConfiguration( associatedConfiguredTargetAndData.getTarget(), aspectConfiguration); ImmutableList<Aspect> aspectPath = aspectPathBuilder.build(); try { // Determine what toolchains are needed by this target. UnloadedToolchainContext unloadedToolchainContext = null; if (configuration != null) { // Configuration can be null in the case of aspects applied to input files. In this case, // there are no chances of toolchains being used, so skip it. try { ImmutableSet<Label> requiredToolchains = aspect.getDefinition().getRequiredToolchains(); unloadedToolchainContext = (UnloadedToolchainContext) env.getValueOrThrow( ToolchainContextKey.key() .configurationKey(BuildConfigurationValue.key(configuration)) .requiredToolchainTypeLabels(requiredToolchains) .shouldSanityCheckConfiguration( configuration.trimConfigurationsRetroactively()) .build(), ToolchainException.class); } catch (ToolchainException e) { // TODO(katre): better error handling throw new AspectCreationException( e.getMessage(), new LabelCause(key.getLabel(), e.getDetailedExitCode())); } } if (env.valuesMissing()) { return null; } // Get the configuration targets that trigger this rule's configurable attributes. ImmutableMap<Label, ConfigMatchingProvider> configConditions = ConfiguredTargetFunction.getConfigConditions( env, originalTargetAndAspectConfiguration, transitivePackagesForPackageRootResolution, unloadedToolchainContext == null ? null : unloadedToolchainContext.targetPlatform(), transitiveRootCauses); if (configConditions == null) { // Those targets haven't yet been resolved. return null; } OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> depValueMap; try { depValueMap = ConfiguredTargetFunction.computeDependencies( env, resolver, originalTargetAndAspectConfiguration, aspectPath, configConditions, unloadedToolchainContext == null ? null : ToolchainCollection.builder() .addDefaultContext(unloadedToolchainContext) .build(), shouldUseToolchainTransition(configuration, aspect.getDefinition()), ruleClassProvider, view.getHostConfiguration(originalTargetAndAspectConfiguration.getConfiguration()), transitivePackagesForPackageRootResolution, transitiveRootCauses, defaultBuildOptions); } catch (ConfiguredValueCreationException e) { throw new AspectCreationException( e.getMessage(), key.getLabel(), aspectConfiguration, e.getDetailedExitCode()); } if (depValueMap == null) { return null; } if (!transitiveRootCauses.isEmpty()) { NestedSet<Cause> causes = transitiveRootCauses.build(); throw new AspectFunctionException( new AspectCreationException( "Loading failed", causes, ConfiguredTargetFunction.getPrioritizedDetailedExitCode(causes))); } // Load the requested toolchains into the ToolchainContext, now that we have dependencies. ResolvedToolchainContext toolchainContext = null; if (unloadedToolchainContext != null) { String targetDescription = String.format( "aspect %s applied to %s", aspect.getDescriptor().getDescription(), associatedConfiguredTargetAndData.getTarget()); toolchainContext = ResolvedToolchainContext.load( targetPkg.getRepositoryMapping(), unloadedToolchainContext, targetDescription, // TODO(161222568): Support exec groups on aspects. depValueMap.get(DependencyKind.defaultExecGroupToolchain())); } return createAspect( env, key, aspectPath, aspect, aspectFactory, associatedConfiguredTargetAndData, aspectConfiguration, configConditions, toolchainContext, depValueMap, transitivePackagesForPackageRootResolution); } catch (DependencyEvaluationException e) { if (e.getCause() instanceof ConfiguredValueCreationException) { ConfiguredValueCreationException cause = (ConfiguredValueCreationException) e.getCause(); throw new AspectFunctionException( new AspectCreationException( cause.getMessage(), cause.getRootCauses(), cause.getDetailedExitCode())); } else if (e.getCause() instanceof InconsistentAspectOrderException) { InconsistentAspectOrderException cause = (InconsistentAspectOrderException) e.getCause(); throw new AspectFunctionException( new AspectCreationException(cause.getMessage(), key.getLabel(), aspectConfiguration)); } else if (e.getCause() instanceof TransitionException) { TransitionException cause = (TransitionException) e.getCause(); throw new AspectFunctionException( new AspectCreationException(cause.getMessage(), key.getLabel(), aspectConfiguration)); } else { // Cast to InvalidConfigurationException as a consistency check. If you add any // DependencyEvaluationException constructors, you may need to change this code, too. InvalidConfigurationException cause = (InvalidConfigurationException) e.getCause(); throw new AspectFunctionException( new AspectCreationException( cause.getMessage(), key.getLabel(), aspectConfiguration, cause.getDetailedExitCode())); } } catch (AspectCreationException e) { throw new AspectFunctionException(e); } catch (ToolchainException e) { throw new AspectFunctionException( new AspectCreationException( e.getMessage(), new LabelCause(key.getLabel(), e.getDetailedExitCode()))); } } /** * Returns whether or not to use the new toolchain transition. Checks the global incompatible * change flag and the aspect's toolchain transition readiness attribute. */ // TODO(#10523): Remove this when the migration period for toolchain transitions has ended. private static boolean shouldUseToolchainTransition( @Nullable BuildConfiguration configuration, AspectDefinition definition) { // Check whether the global incompatible change flag is set. if (configuration != null) { PlatformOptions platformOptions = configuration.getOptions().get(PlatformOptions.class); if (platformOptions != null && platformOptions.overrideToolchainTransition) { return true; } } // Check the aspect definition to see if it is ready. return definition.useToolchainTransition(); } /** * Merges aspects defined by {@code aspectKeys} into the {@code target} using previously computed * {@code values}. * * @return A {@link ConfiguredTarget} that is a result of a merge. * @throws DuplicateException if there is a duplicate provider provided by aspects. */ private static ConfiguredTarget getBaseTarget( ConfiguredTarget target, ImmutableList<AspectKey> aspectKeys, Map<SkyKey, SkyValue> values) throws DuplicateException { ArrayList<ConfiguredAspect> aspectValues = new ArrayList<>(); for (AspectKey aspectKey : aspectKeys) { AspectValue aspectValue = (AspectValue) values.get(aspectKey); ConfiguredAspect configuredAspect = aspectValue.getConfiguredAspect(); aspectValues.add(configuredAspect); } return MergedConfiguredTarget.of(target, aspectValues); } /** * Collect all SkyKeys that are needed for a given list of AspectKeys, * including transitive dependencies. * * Also collects all propagating aspects in correct order. */ private ImmutableMap<AspectDescriptor, SkyKey> getSkyKeysForAspectsAndCollectAspectPath( ImmutableList<AspectKey> keys, ImmutableList.Builder<SkyKey> aspectPathBuilder) { HashMap<AspectDescriptor, SkyKey> result = new HashMap<>(); for (AspectKey key : keys) { buildSkyKeys(key, result, aspectPathBuilder); } return ImmutableMap.copyOf(result); } private void buildSkyKeys(AspectKey key, HashMap<AspectDescriptor, SkyKey> result, ImmutableList.Builder<SkyKey> aspectPathBuilder) { if (result.containsKey(key.getAspectDescriptor())) { return; } ImmutableList<AspectKey> baseKeys = key.getBaseKeys(); result.put(key.getAspectDescriptor(), key); for (AspectKey baseKey : baseKeys) { buildSkyKeys(baseKey, result, aspectPathBuilder); } // Post-order list of aspect SkyKeys gives the order of propagating aspects: // the aspect comes after all aspects it transitively sees. aspectPathBuilder.add(key); } private SkyValue createAliasAspect( Environment env, Target originalTarget, Aspect aspect, AspectKey originalKey, ConfiguredTarget configuredTarget) throws InterruptedException { ImmutableList<Label> aliasChain = configuredTarget.getProvider(AliasProvider.class) .getAliasChain(); // Find the next alias in the chain: either the next alias (if there are two) or the name of // the real configured target. Label aliasLabel = aliasChain.size() > 1 ? aliasChain.get(1) : configuredTarget.getLabel(); return createAliasAspect(env, originalTarget, aspect, originalKey, aliasLabel); } private AspectValue createAliasAspect( Environment env, Target originalTarget, Aspect aspect, AspectKey originalKey, Label aliasLabel) throws InterruptedException { SkyKey depKey = originalKey.withLabel(aliasLabel); // Compute the AspectValue of the target the alias refers to (which can itself be either an // alias or a real target) AspectValue real = (AspectValue) env.getValue(depKey); if (env.valuesMissing()) { return null; } NestedSet<Package> transitivePackagesForPackageRootResolution = storeTransitivePackagesForPackageRootResolution ? NestedSetBuilder.<Package>stableOrder() .addTransitive(real.getTransitivePackagesForPackageRootResolution()) .add(originalTarget.getPackage()) .build() : null; return new AspectValue( originalKey, aspect, originalTarget.getLocation(), ConfiguredAspect.forAlias(real.getConfiguredAspect()), transitivePackagesForPackageRootResolution); } @Nullable private AspectValue createAspect( Environment env, AspectKey key, ImmutableList<Aspect> aspectPath, Aspect aspect, ConfiguredAspectFactory aspectFactory, ConfiguredTargetAndData associatedTarget, BuildConfiguration aspectConfiguration, ImmutableMap<Label, ConfigMatchingProvider> configConditions, ResolvedToolchainContext toolchainContext, OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> directDeps, @Nullable NestedSetBuilder<Package> transitivePackagesForPackageRootResolution) throws AspectFunctionException, InterruptedException { SkyframeBuildView view = buildViewProvider.getSkyframeBuildView(); StoredEventHandler events = new StoredEventHandler(); CachingAnalysisEnvironment analysisEnvironment = view.createAnalysisEnvironment( key, false, events, env, aspectConfiguration); if (env.valuesMissing()) { return null; } ConfiguredAspect configuredAspect; if (aspect.getDefinition().applyToGeneratingRules() && associatedTarget.getTarget() instanceof OutputFile) { OutputFile outputFile = (OutputFile) associatedTarget.getTarget(); Label label = outputFile.getGeneratingRule().getLabel(); return createAliasAspect(env, associatedTarget.getTarget(), aspect, key, label); } else if (AspectResolver.aspectMatchesConfiguredTarget(associatedTarget, aspect)) { try { CurrentRuleTracker.beginConfiguredAspect(aspect.getAspectClass()); configuredAspect = view.getConfiguredTargetFactory() .createAspect( analysisEnvironment, associatedTarget, aspectPath, aspectFactory, aspect, directDeps, configConditions, toolchainContext, aspectConfiguration, view.getHostConfiguration(aspectConfiguration), key); } catch (MissingDepException e) { Preconditions.checkState(env.valuesMissing()); return null; } catch (ActionConflictException e) { throw new AspectFunctionException(e); } catch (InvalidExecGroupException e) { throw new AspectFunctionException(e); } finally { CurrentRuleTracker.endConfiguredAspect(); } } else { configuredAspect = ConfiguredAspect.forNonapplicableTarget(); } events.replayOn(env.getListener()); if (events.hasErrors()) { analysisEnvironment.disable(associatedTarget.getTarget()); String msg = "Analysis of target '" + associatedTarget.getTarget().getLabel() + "' failed"; throw new AspectFunctionException( new AspectCreationException(msg, key.getLabel(), aspectConfiguration)); } Preconditions.checkState(!analysisEnvironment.hasErrors(), "Analysis environment hasError() but no errors reported"); if (env.valuesMissing()) { return null; } analysisEnvironment.disable(associatedTarget.getTarget()); Preconditions.checkNotNull(configuredAspect); return new AspectValue( key, aspect, associatedTarget.getTarget().getLocation(), configuredAspect, transitivePackagesForPackageRootResolution == null ? null : transitivePackagesForPackageRootResolution.build()); } @Override public String extractTag(SkyKey skyKey) { AspectKey aspectKey = (AspectKey) skyKey.argument(); return Label.print(aspectKey.getLabel()); } /** Used to indicate errors during the computation of an {@link AspectValue}. */ public static final class AspectFunctionException extends SkyFunctionException { public AspectFunctionException(NoSuchThingException e) { super(e, Transience.PERSISTENT); } public AspectFunctionException(AspectCreationException e) { super(e, Transience.PERSISTENT); } public AspectFunctionException(InvalidExecGroupException e) { super(e, Transience.PERSISTENT); } public AspectFunctionException(ActionConflictException cause) { super(cause, Transience.PERSISTENT); } } }
apache-2.0
oleksiyp/equal5
engine/src/main/java/engine/calculation/LocusRowDiffVisitor.java
1653
package engine.calculation; import engine.expressions.Equation; import java.util.Arrays; /** * User: Oleksiy Pylypenko * At: 3/13/13 12:57 PM */ class LocusRowDiffVisitor implements Equation.TypeVisitor<int[]> { private final double[] row; private final double[] prevRow; public LocusRowDiffVisitor(double[] row, double[] prevRow) { this.row = row; this.prevRow = prevRow; } @Override public int[] less() { int []ret = new int[row.length - 1]; int sz = 0; for (int i = 0; i < row.length - 1; i++) { double a = row[i]; if (a == -1.0) { ret[sz++] = i; } } return Arrays.copyOf(ret, sz); } @Override public int[] equal() { int []ret = new int[row.length - 1]; int sz = 0; for (int i = 0; i < row.length - 1; i++) { double a = row[i], b = row[i + 1], c = prevRow[i], d = prevRow[i + 1]; double s = a + b + c + d; if (-4.0 < s && s < 4.0) { ret[sz++] = i; } } return Arrays.copyOf(ret, sz); } @Override public int[] greater() { int []ret = new int[row.length - 1]; int sz = 0; for (int i = 0; i < row.length - 1; i++) { double a = row[i]; if (a == 1.0) { ret[sz++] = i; } } return Arrays.copyOf(ret, sz); } @Override public int[] lessEqual() { return less(); } @Override public int[] greaterEqual() { return greater(); } }
apache-2.0
vinctzhang/LockManager
src/main/java/com/yflog/lckmgr/client/MessageDelivery.java
1753
package com.yflog.lckmgr.client; import com.yflog.lckmgr.common.TimeoutException; import com.yflog.lckmgr.common.TransportException; import com.yflog.lckmgr.msg.LSMessage; import org.apache.log4j.Logger; import java.util.concurrent.atomic.AtomicLong; /** * Created by vincent on 6/25/16. */ class MessageDelivery { private static final Logger _logger = Logger.getLogger("MsgDeliver"); private final AtomicLong _seq = new AtomicLong(1); private final Transport _transport; MessageDelivery(final Transport transport) { this._transport = transport; } LSMessage.Message call(final LSMessage.Message.Builder mBuilder) { try { mBuilder.setSeqId(_seq.getAndIncrement()); LSMessage.Message msg = mBuilder.build(); while (true) { _transport.write(msg); /// TransportException if failed to write message try { } catch (TimeoutException te) { // the only cause of timeout is that the service does not get the request // so we should retry _logger.warn("TimeoutException"); continue; } } } catch (TransportException te) { throw te; } } private LSMessage.Message _readWithMatchedSeq() { while (true) { LSMessage.Message ms = _transport.read(); if (ms.getSeqId() == _seq.longValue() -1) { return ms; } _logger.warn(String.format("Read an obsolete message seqId=%d, command=%s", ms.getSeqId(), ms.getCommand())); } } void shutDown() { _transport.shutDown(); } }
apache-2.0
sdnwiselab/onos
providers/bmv2/device/src/main/java/org/onosproject/provider/bmv2/device/impl/Bmv2ProviderConfig.java
3308
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.provider.bmv2.device.impl; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.annotations.Beta; import com.google.common.collect.Sets; import org.onlab.packet.IpAddress; import org.onosproject.core.ApplicationId; import org.onosproject.incubator.net.config.basics.ConfigException; import org.onosproject.net.config.Config; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; /** * Configuration decoder for Bmv2 provider. */ @Beta public class Bmv2ProviderConfig extends Config<ApplicationId> { public static final String CONFIG_VALUE_ERROR = "Error parsing config value"; private static final String IP = "ip"; private static final int DEFAULT_THRIFT_PORT = 9090; private static final String PORT = "port"; /** * Retrieves a set of Bmv2DeviceInfo containing all the device * configuration pertaining to the Bmv2 device provider. * * @return set of device configurations. * @throws ConfigException if configuration can't be read */ public Set<Bmv2DeviceInfo> getDevicesInfo() throws ConfigException { Set<Bmv2DeviceInfo> deviceInfos = Sets.newHashSet(); try { for (JsonNode node : array) { String ip = node.path(IP).asText(); IpAddress ipAddr = ip.isEmpty() ? null : IpAddress.valueOf(ip); int port = node.path(PORT).asInt(DEFAULT_THRIFT_PORT); deviceInfos.add(new Bmv2DeviceInfo(ipAddr, port)); } } catch (IllegalArgumentException e) { throw new ConfigException(CONFIG_VALUE_ERROR, e); } return deviceInfos; } /** * Contains information about a Bmv2 device retrieved from the net-cfg * subsystem. */ public static class Bmv2DeviceInfo { private final IpAddress ip; private final int port; /** * Build an information object containing the given device specifics. * * @param ip ip * @param port port */ public Bmv2DeviceInfo(IpAddress ip, int port) { // TODO use generalized host string instead of IP address this.ip = checkNotNull(ip, "ip cannot be null"); this.port = checkNotNull(port, "port cannot be null"); } /** * Returns IpAddress of the device. * * @return ip */ public IpAddress ip() { return ip; } /** * Returns port of the device. * * @return port */ public int port() { return port; } } }
apache-2.0
darciopacifico/omr
branchs/JazzQA/webportal/src/main/java/br/com/dlp/jazzqa/status/StatusJSFBean.java
2113
/** * Gerado por template generation * Diretiva de overwrite atual: * TemplateName: **/ package br.com.dlp.jazzqa.status; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import br.com.dlp.framework.business.IBusiness; import br.com.dlp.framework.jsf.AbstractJSFBeanImpl; /** * Incluir arquivo com comentários * * Implementação de Bean JSF para o componente StatusVO * **/ @Scope(value="session") @Component public class StatusJSFBean extends AbstractJSFBeanImpl<StatusVO> { private static final long serialVersionUID = 2195241915100521959L; /** * Retorna os atributos deste bean utilizados para pesquisa * @see br.com.dlp.framework.jsf.AbstractJSFBeanImpl#getCamposLimparPesquisa() */ @Override public String[] getCamposLimparPesquisa() { return new String[]{"dtInclusaoFrom", "dtInclusaoTo", "descricao","nome","dummyVO"}; } @Autowired private StatusBusiness statusBusiness; /** * Replica das propriedades pesquisaveis. Atributos para composicao de formulario de pesquisa */ private String titulo; private String descricao; /** * Pesquisa lista de StatusVO e disponibiliza resultados em statusVOs */ @Override public String actionPesquisar(){ List<StatusVO> resultados = statusBusiness.findStatusVO(titulo, descricao); setResultados(resultados); return "exibePesquisa"; } /** * Accessor Method * @return titulo */ public String getTitulo(){ return titulo; } /** * Accessor Method * @return descricao */ public String getDescricao(){ return descricao; } /** * Mutator Method * @param titulo */ public void setTitulo(String titulo){ this.titulo = titulo; } /** * Mutator Method * @param descricao */ public void setDescricao(String descricao){ this.descricao = descricao; } /* (non-Javadoc) * @see br.com.dlp.framework.jsf.AbstractJSFBeanImpl#getBusiness() */ @Override protected IBusiness<StatusVO> getBusiness() { return statusBusiness; } }
apache-2.0
xloye/tddl5
tddl-manager/src/main/java/com/alibaba/cobar/manager/web/action/LoginAction.java
3185
package com.alibaba.cobar.manager.web.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.InitializingBean; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import com.alibaba.cobar.manager.dataobject.xml.UserDO; import com.alibaba.cobar.manager.service.XmlAccesser; import com.alibaba.cobar.manager.web.URLBroker; /** * (created at 2010-7-20) * * @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a> * @author wenfeng.cenwf 2011-4-7 */ public class LoginAction extends SimpleFormController implements InitializingBean { private XmlAccesser xmlAccesser; public void setXmlAccesser(XmlAccesser xmlAccesser) { this.xmlAccesser = xmlAccesser; } @SuppressWarnings("unused") private static class Account { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } @Override public void afterPropertiesSet() throws Exception { setCommandClass(Account.class); if (xmlAccesser == null) { throw new IllegalArgumentException("property 'xmlAccesser' is null!"); } } @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { Account form = (Account) command; UserDO user = xmlAccesser.getUserDAO().validateUser(form.getUserName().trim(), form.getPassword().trim()); if (user != null) { if (logger.isInfoEnabled()) { StringBuilder sb = new StringBuilder("User '"); sb.append(user.getUsername()); sb.append("' login!"); logger.info(sb.toString()); } request.getSession().setAttribute("user", user); // request.getSession().setMaxInactiveInterval(30); String to = (String) request.getSession().getAttribute("lastRequest"); if (null != to) { request.getSession().removeAttribute("click"); request.getSession().removeAttribute("lastRequest"); response.sendRedirect(to); } else { response.sendRedirect(URLBroker.redirectClusterListScreen()); } } else { // 登录失败 boolean flag = (Boolean) request.getSession().getAttribute("click"); if (flag) { response.sendRedirect(URLBroker.redirectIndexPage("false")); } else { response.sendRedirect(URLBroker.redirectLogInPage("false")); } } return null; } }
apache-2.0
guiguegon/GeoApi
app/src/main/java/es/guiguegon/geoapi/exceptions/NotFoundException.java
1152
/** * Copyright (C) 2015 Fernando Cejas Open Source Project * <p> * 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 * <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 es.guiguegon.geoapi.exceptions; /** * Exception throw by the application when a search can't return a valid result. */ public class NotFoundException extends Exception { public NotFoundException() { super(); } public NotFoundException(final String message) { super(message); } public NotFoundException(final String message, final Throwable cause) { super(message, cause); } public NotFoundException(final Throwable cause) { super(cause); } }
apache-2.0
Kirtish/spring-data-jpa
src/main/java/com/rsoft/app/controller/UserController.java
936
package com.rsoft.app.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.rsoft.app.services.IUserService; @Controller @RequestMapping(value="/users/") public class UserController { @RequestMapping(method = RequestMethod.GET) public ModelAndView get(){ ModelAndView modelAndView = new ModelAndView(VIEW); modelAndView.addObject("allusers",getUserService().getUsers()); return modelAndView; } public IUserService getUserService() { return userService; } public void setUserService(IUserService userService) { this.userService = userService; } @Autowired private IUserService userService; private static final String VIEW = "/user/allusers"; }
apache-2.0
italiangrid/test-srm-client
src/main/java/org/italiangrid/axis/CANLAxis1SocketFactory.java
7128
/** * Copyright (c) Members of the EGEE Collaboration. 2006-2009. See * http://www.eu-egee.org/partners/ for details on the copyright holders. * * 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.italiangrid.axis; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.Hashtable; import javax.net.SocketFactory; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.axis.components.net.BooleanHolder; import org.apache.axis.components.net.SecureSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.emi.security.authn.x509.ValidationError; import eu.emi.security.authn.x509.ValidationErrorListener; import eu.emi.security.authn.x509.X509CertChainValidatorExt; import eu.emi.security.authn.x509.impl.CertificateUtils; import eu.emi.security.authn.x509.impl.HostnameMismatchCallback; import eu.emi.security.authn.x509.impl.PEMCredential; import eu.emi.security.authn.x509.impl.SocketFactoryCreator; import eu.emi.security.authn.x509.impl.X500NameUtils; /** * This class provides a CANL-based replacement for Axis 1.x trustmanager secure * socket factory class. * * @author andreaceccanti * */ public class CANLAxis1SocketFactory implements SecureSocketFactory, HostnameMismatchCallback, ValidationErrorListener { public static final Logger log = LoggerFactory .getLogger(CANLAxis1SocketFactory.class.getName()); private String sslProtocol; private String certFile; private String keyFile; private String keyPassword; private String proxyFile; private int timeout; private boolean enforcingHostnameChecks; private X509CertChainValidatorExt certChainValidator; private static CANLAxis1SocketFactoryConfigurator configurator; private boolean enableGSIHandshake = false; public CANLAxis1SocketFactory( @SuppressWarnings("rawtypes") Hashtable attributes) { CertificateUtils.configureSecProvider(); configurator.configure(this); } public static synchronized void setConfigurator( CANLAxis1SocketFactoryConfigurator conf) { configurator = conf; } private KeyManager[] getKeymanagers() throws Exception { PEMCredential cred; if (proxyFile != null) { cred = new PEMCredential(new FileInputStream(proxyFile), (char[]) null); } else { if (keyPassword != null) cred = new PEMCredential(keyFile, certFile, keyPassword.toCharArray()); else cred = new PEMCredential(keyFile, certFile, null); } return new KeyManager[] { cred.getKeyManager() }; } private TrustManager[] getTrustmanagers() throws Exception { X509TrustManager trustManager = SocketFactoryCreator .getSSLTrustManager(certChainValidator); TrustManager[] trustManagers = new TrustManager[] { trustManager }; return trustManagers; } private SecureRandom getSecureRandom() throws NoSuchAlgorithmException { return new SecureRandom(); } private SSLSocketFactory createSocketFactory() throws Exception { SSLContext context = SSLContext.getInstance(sslProtocol); KeyManager[] keyManagers = getKeymanagers(); TrustManager[] trustManagers = getTrustmanagers(); SecureRandom random = getSecureRandom(); context.init(keyManagers, trustManagers, random); return context.getSocketFactory(); } private void doGSIHandshake(SSLSocket socket) throws IOException{ socket.getOutputStream().write('0'); socket.getOutputStream().flush(); } public Socket create(String host, int port, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception { SocketFactory fac = createSocketFactory(); SSLSocket socket = (SSLSocket) fac.createSocket(host, port); socket.setEnabledProtocols(new String[] { sslProtocol }); socket.setSoTimeout(timeout); SocketFactoryCreator.connectWithHostnameChecking(socket, this); if (enableGSIHandshake) doGSIHandshake(socket); return socket; } public void nameMismatch(SSLSocket socket, X509Certificate peerCertificate, String hostName) throws SSLException { if (enforcingHostnameChecks) { try { socket.close(); } catch (IOException e) { } String peerCertificateSubject = X500NameUtils .getReadableForm(peerCertificate.getSubjectX500Principal()); String message = String.format( "Peer certificate subject %s does not match hostname %s", peerCertificateSubject, hostName); throw new SSLException(message); } } public boolean onValidationError(ValidationError error) { log.error("Certificate validation error: {}", error); return false; } /** * @param sslProtocol * the sslProtocol to set */ public synchronized void setSslProtocol(String sslProtocol) { this.sslProtocol = sslProtocol; } /** * @param certFile * the certFile to set */ public synchronized void setCertFile(String certFile) { this.certFile = certFile; } /** * @param keyFile * the keyFile to set */ public synchronized void setKeyFile(String keyFile) { this.keyFile = keyFile; } /** * @param keyPassword * the keyPassword to set */ public synchronized void setKeyPassword(String keyPassword) { this.keyPassword = keyPassword; } /** * @param proxyFile * the proxyFile to set */ public synchronized void setProxyFile(String proxyFile) { this.proxyFile = proxyFile; } /** * @param timeout * the timeout to set */ public synchronized void setTimeout(int timeout) { this.timeout = timeout; } /** * @param enforcingHostnameChecks * the enforcingHostnameChecks to set */ public synchronized void setEnforcingHostnameChecks( boolean enforcingHostnameChecks) { this.enforcingHostnameChecks = enforcingHostnameChecks; } /** * @return the certChainValidator */ public synchronized X509CertChainValidatorExt getCertChainValidator() { return certChainValidator; } /** * @param certChainValidator * the certChainValidator to set */ public synchronized void setCertChainValidator( X509CertChainValidatorExt certChainValidator) { this.certChainValidator = certChainValidator; } /** * @param enableGSIHandshake the enableGSIHandshake to set */ public void setEnableGSIHandshake(boolean enableGSIHandshake) { this.enableGSIHandshake = enableGSIHandshake; } }
apache-2.0
tkaczmarzyk/specification-arg-resolver
src/main/java/net/kaczmarzyk/spring/data/jpa/domain/Equal.java
2863
/** * Copyright 2014-2020 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 net.kaczmarzyk.spring.data.jpa.domain; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import net.kaczmarzyk.spring.data.jpa.utils.Converter; import net.kaczmarzyk.spring.data.jpa.utils.QueryContext; /** * <p>Filters with equal where-clause (e.g. {@code where firstName = "Homer"}).</p> * * <p>Supports multiple field types: strings, numbers, booleans, enums, dates.</p> * * @author Tomasz Kaczmarzyk */ public class Equal<T> extends PathSpecification<T> { private static final long serialVersionUID = 1L; protected String expectedValue; private Converter converter; public Equal(QueryContext queryContext, String path, String[] httpParamValues, Converter converter) { super(queryContext, path); if (httpParamValues == null || httpParamValues.length != 1) { throw new IllegalArgumentException(); } this.expectedValue = httpParamValues[0]; this.converter = converter; } @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Class<?> typeOnPath = path(root).getJavaType(); return cb.equal(path(root), converter.convert(expectedValue, typeOnPath)); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((converter == null) ? 0 : converter.hashCode()); result = prime * result + ((expectedValue == null) ? 0 : expectedValue.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Equal other = (Equal) obj; if (converter == null) { if (other.converter != null) return false; } else if (!converter.equals(other.converter)) return false; if (expectedValue == null) { if (other.expectedValue != null) return false; } else if (!expectedValue.equals(other.expectedValue)) return false; return true; } @Override public String toString() { return "Equal [expectedValue=" + expectedValue + ", converter=" + converter + ", path=" + super.path + "]"; } }
apache-2.0
edu1910/BuscaML
BuscaML/src/br/com/ceducarneiro/buscaml/MLParser.java
3492
package br.com.ceducarneiro.buscaml; import android.os.AsyncTask; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MLParser { private MLParserCallback callback; private MLAsyncTask task; public MLParser(MLParserCallback callback) { this.callback = callback; } public void getProducts(String query) { if (task != null) { task.cancel(true); } task = new MLAsyncTask(); task.execute(query.replace(" ", "%20")); } interface MLParserCallback { void onSuccess(List<MLProduct> products); void onError(); } public class MLProduct { public String id; public String title; public double price; public boolean newProduct; public String link; public String thumbnail; } private class MLAsyncTask extends AsyncTask<String, Void, List<MLProduct>> { private static final String URL = "https://api.mercadolibre.com/sites/MLB/search?q=%s"; @Override protected List<MLProduct> doInBackground(String... params) { List<MLProduct> products = null; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(String.format(URL, params[0])); try { HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { products = parseProducts(EntityUtils.toString(entity)); } } catch (Exception ignored) { products = null; } return products; } private List<MLProduct> parseProducts(String jsonString) { List<MLProduct> products = new ArrayList<MLProduct>(); try { JSONObject jsonObj = new JSONObject(jsonString); JSONArray productsArray = jsonObj.getJSONArray("results"); for (int i = 0; i < productsArray.length(); i++) { JSONObject product = productsArray.getJSONObject(i); MLProduct productObj = new MLProduct(); productObj.id = product.getString("id"); productObj.link = product.getString("permalink"); productObj.newProduct = product.getString("condition").equals("new"); productObj.price = product.getDouble("price"); productObj.title = product.getString("title"); productObj.thumbnail = product.getString("thumbnail"); products.add(productObj); } } catch (JSONException ignored) { products = null; } return products; } @Override protected void onPostExecute(List<MLProduct> mlProducts) { if (callback != null) { if (mlProducts != null) { callback.onSuccess(mlProducts); } else { callback.onError(); } } } } }
apache-2.0
garybentley/quollwriter
src/com/quollwriter/ui/QColorChooser.java
24729
package com.quollwriter.ui; import java.awt.*; import java.awt.event.*; import java.text.*; import java.util.ArrayList; import java.util.Set; import java.util.LinkedHashSet; import java.util.List; import java.util.Vector; import java.util.StringTokenizer; import java.util.Collections; import java.util.Iterator; import java.util.Enumeration; import java.util.Arrays; import javax.swing.*; import javax.swing.colorchooser.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import com.jgoodies.forms.builder.*; import com.jgoodies.forms.factories.*; import com.jgoodies.forms.layout.*; import com.gentlyweb.utils.*; import com.quollwriter.*; import com.quollwriter.events.*; import com.quollwriter.ui.components.ChangeAdapter; import com.quollwriter.ui.components.ImagePanel; import com.quollwriter.ui.components.QPopup; import com.quollwriter.ui.components.ActionAdapter; import com.quollwriter.ui.components.DocumentAdapter; import static com.quollwriter.LanguageStrings.*; import static com.quollwriter.Environment.getUIString; public class QColorChooser extends Box implements UserPropertyListener { public static final String SWATCH_TYPE = "swatch"; public static final String RGB_TYPE = "rgb"; private List<ChangeListener> changeListeners = new ArrayList (); private JPanel rgbPanel = null; private JSlider rs = null; private JSlider gs = null; private JSlider bs = null; private JSpinner rsp = null; private JSpinner gsp = null; private JSpinner bsp = null; private JTextField rgb = null; private Color currentColor = null; private Color initialColor = null; private boolean updating = false; private ActionListener onSelect = null; private ActionListener onCancel = null; private JList<Color> swatches = null; private JScrollPane swatchesScrollPane = null; private int showRows = 2; private int horizGap = 3; private int vertGap = 3; private Dimension swatchSize = new Dimension (20, 20); private int borderWidth = 1; private String userPropName = null; public QColorChooser (Color initial) { super (BoxLayout.Y_AXIS); final QColorChooser _this = this; this.rs = new JSlider (0, 255); this.gs = new JSlider (0, 255); this.bs = new JSlider (0, 255); this.initialColor = initial; Set<Color> cols = this.getSwatchColors (); this.swatchesScrollPane = new JScrollPane (); this.setSwatches (cols); final Dimension sSize = new Dimension (this.swatchSize.width + (2 * this.borderWidth) + (2 * this.horizGap), this.swatchSize.height + (2 * this.borderWidth) + (2 * this.vertGap)); this.swatchesScrollPane.setHorizontalScrollBarPolicy (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); this.swatchesScrollPane.getVerticalScrollBar ().setUnitIncrement (this.swatchSize.height + (2 * this.borderWidth) + (this.vertGap * 2)); this.swatchesScrollPane.setAlignmentX (JComponent.LEFT_ALIGNMENT); this.swatchesScrollPane.setOpaque (false); this.swatchesScrollPane.getViewport ().setPreferredSize (new Dimension (8 * sSize.width, this.showRows * sSize.height)); this.swatchesScrollPane.setBorder (null); List<String> prefix = Arrays.asList (colorchooser,labels); FormLayout rgbfl = new FormLayout ("right:p, 6px, 150px:grow, 3px, 48px", "p, 6px, p, 6px, p, 6px, p, 10px, top:p"); int rr = 1; int gr = 3; int br = 5; int hr = 7; int cr = 9; int butr = 11; PanelBuilder rgbbuilder = new PanelBuilder (rgbfl); CellConstraints cc = new CellConstraints (); rgbbuilder.addLabel (getUIString (prefix,hex), //"HEX", cc.xy (1, hr)); this.rgb = new JTextField (); this.rgb.setPreferredSize (new Dimension (80, this.rgb.getPreferredSize ().height)); this.rgb.setMaximumSize (this.rgb.getPreferredSize ()); this.rgb.getDocument ().addDocumentListener (new DocumentAdapter () { @Override public void insertUpdate (DocumentEvent ev) { String t = rgb.getText ().trim (); if (!t.startsWith ("#")) { t = "#" + t; } if (t.length () < 7) { return; } t = t.toUpperCase (); Color c = null; try { c = Color.decode (t); } catch (Exception e) { return; } _this.update (c, false); } }); Box brgb = new Box (BoxLayout.X_AXIS); brgb.add (this.rgb); brgb.add (Box.createHorizontalGlue ()); rgbbuilder.add (brgb, cc.xy (3, hr)); rgbbuilder.addLabel (Environment.getUIString (prefix, LanguageStrings.red), //"Red", cc.xy (1, rr)); rs.setOpaque (false); rgbbuilder.add (rs, cc.xy (3, rr)); SpinnerNumberModel rm = new SpinnerNumberModel (initial.getRed (), 0, 255, 1); this.rsp = new JSpinner (rm); rgbbuilder.add (this.rsp, cc.xy (5, rr)); rgbbuilder.addLabel (Environment.getUIString (prefix, LanguageStrings.green), //"Green", cc.xy (1, gr)); this.gs.setOpaque (false); rgbbuilder.add (this.gs, cc.xy (3, gr)); SpinnerNumberModel gm = new SpinnerNumberModel (initial.getGreen (), 0, 255, 1); this.gsp = new JSpinner (gm); rgbbuilder.add (this.gsp, cc.xy (5, gr)); rgbbuilder.addLabel (Environment.getUIString (prefix, LanguageStrings.blue), //"Blue", cc.xy (1, br)); bs.setOpaque (false); rgbbuilder.add (bs, cc.xy (3, br)); SpinnerNumberModel bm = new SpinnerNumberModel (initial.getBlue (), 0, 255, 1); this.bsp = new JSpinner (bm); rgbbuilder.add (this.bsp, cc.xy (5, br)); rgbbuilder.addLabel (Environment.getUIString (prefix, LanguageStrings.color), //"Color", cc.xy (1, cr)); rgbbuilder.add (this.swatchesScrollPane, cc.xywh (3, cr, 3, 1)); ChangeListener vcl = new ChangeListener () { @Override public void stateChanged (ChangeEvent ev) { Color c = new Color (((Number) _this.rsp.getValue ()).intValue (), ((Number) _this.gsp.getValue ()).intValue (), ((Number) _this.bsp.getValue ()).intValue ()); _this.update (c, true); } }; this.rsp.addChangeListener (vcl); this.gsp.addChangeListener (vcl); this.bsp.addChangeListener (vcl); ChangeListener cl = new ChangeAdapter () { public void stateChanged (ChangeEvent ev) { // Get the new color, then fire a state change. Color c = new Color (_this.rs.getValue (), _this.gs.getValue (), _this.bs.getValue ()); _this.update (c, true); /* _this.fireChangeEvent (c, RGB_TYPE); */ } }; this.rs.addChangeListener (cl); this.gs.addChangeListener (cl); this.bs.addChangeListener (cl); this.setColor (initial); this.rgbPanel = rgbbuilder.getPanel (); this.rgbPanel.setOpaque (false); this.rgbPanel.setAlignmentX (JComponent.LEFT_ALIGNMENT); this.add (this.rgbPanel); this.setOpaque (false); this.setAlignmentX (JComponent.LEFT_ALIGNMENT); if (initial != null) { this.fireChangeEvent (initial, SWATCH_TYPE); } } public void setUserPropertyName (String n) { this.userPropName = n; if (n != null) { UserProperties.addListener (this); } else { UserProperties.removeListener (this); } } @Override public void propertyChanged (UserPropertyEvent ev) { if (ev.getName ().equals (this.userPropName)) { try { this.updating = true; Color c = UIUtils.getColor (UserProperties.get (this.userPropName)); this.currentColor = c; this.rs.setValue (this.currentColor.getRed ()); this.gs.setValue (this.currentColor.getGreen ()); this.bs.setValue (this.currentColor.getBlue ()); this.rsp.setValue (this.currentColor.getRed ()); this.gsp.setValue (this.currentColor.getGreen ()); this.bsp.setValue (this.currentColor.getBlue ()); this.rgb.setText (UIUtils.colorToHex (this.currentColor).toUpperCase ()); } finally { this.updating = false; } } } public Color getCurrentColor () { return this.currentColor; } public void setShowRows (int r) { this.showRows = r; } public void setHorizontalGap (int g) { this.horizGap = g; } public void setVerticalGap (int g) { this.vertGap = g; } public void setSwatchSize (Dimension d) { this.swatchSize = d; } public void setOnSelect (ActionListener l) { this.onSelect = l; } public void setOnCancel (ActionListener l) { this.onCancel = l; } public static JPanel getSwatch (Color col) { return QColorChooser.getSwatch (col, new Dimension (25, 25), 0, 0); } public static JPanel getSwatch (Color col, Dimension swatchSize, int horizGap, int vertGap) { Border ccBorder = new MatteBorder (1, 1, 1, 1, Environment.getBorderColor ()); ccBorder = new CompoundBorder (new MatteBorder (vertGap, horizGap, vertGap, horizGap, UIUtils.getComponentColor ()), UIUtils.createLineBorder ()); Dimension s = new Dimension (swatchSize.width + (horizGap * 2) + 2, swatchSize.height + (vertGap * 2) + 2); JPanel c = new JPanel (); c.setSize (s.width, s.height); c.setMinimumSize (s); c.setMaximumSize (s); c.setPreferredSize (c.getMinimumSize ()); c.setBorder (ccBorder); c.setBackground (col); //UIUtils.setAsButton (c); return c; } public void resetToInitial () { this.setColor (this.initialColor); } // TODO: Use a better lock. private synchronized void update (Color c, boolean updateRGB) { if (this.updating) { return; } this.updating = true; this.currentColor = c; this.rs.setValue (this.currentColor.getRed ()); this.gs.setValue (this.currentColor.getGreen ()); this.bs.setValue (this.currentColor.getBlue ()); this.rsp.setValue (this.currentColor.getRed ()); this.gsp.setValue (this.currentColor.getGreen ()); this.bsp.setValue (this.currentColor.getBlue ()); if (updateRGB) { this.rgb.setText (UIUtils.colorToHex (this.currentColor).toUpperCase ()); } this.fireChangeEvent (c, RGB_TYPE); this.updating = false; } public void setColor (final Color c) { this.update (c, true); } public Color getColor () { return this.currentColor; } public void removeChangeListener (ChangeListener l) { this.changeListeners.remove (l); } public void addChangeListener (ChangeListener l) { this.changeListeners.add (l); } public void setSwatches (Set<Color> colors) { final QColorChooser _this = this; DefaultListModel<Color> m = new DefaultListModel (); for (Color c : colors) { m.addElement (c); } this.swatches = new JList (); this.swatches.setModel (m); this.swatches.setLayoutOrientation (JList.HORIZONTAL_WRAP); this.swatches.setVisibleRowCount (0); this.swatches.setOpaque (true); this.swatches.setBackground (UIUtils.getComponentColor ()); UIUtils.setAsButton (this.swatches); this.swatches.setCellRenderer (new DefaultListCellRenderer () { public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { return _this.getSwatch ((Color) value, swatchSize, horizGap, vertGap); } }); this.swatches.addListSelectionListener (new ListSelectionListener () { @Override public void valueChanged (ListSelectionEvent ev) { if (ev.getValueIsAdjusting ()) { return; } Color c = (Color) _this.swatches.getSelectedValue (); _this.update (c, true); } }); this.swatches.setAlignmentX (JComponent.LEFT_ALIGNMENT); this.swatches.addMouseListener (new MouseEventHandler () { @Override public void fillPopup (JPopupMenu m, MouseEvent ev) { final int ind = _this.swatches.locationToIndex (ev.getPoint ()); if (ind >= 0) { Color c = _this.swatches.getModel ().getElementAt (ind); if ((c != Color.white) && (c != Color.black) ) { JMenuItem mi = null; mi = new JMenuItem (getUIString (colorchooser,swatch,popupmenu,items,remove), //"Remove", Environment.getIcon (Constants.DELETE_ICON_NAME, Constants.ICON_MENU)); mi.addActionListener (new ActionAdapter () { public void actionPerformed (ActionEvent ev) { // Remove the file. DefaultListModel<Color> model = (DefaultListModel<Color>) _this.swatches.getModel (); Object o = model.remove (ind); Set<Color> ncols = new LinkedHashSet (Collections.list (model.elements ())); _this.setSwatchColors (ncols); } }); m.add (mi); } } } }); this.swatchesScrollPane.setViewportView (this.swatches); } protected void fireChangeEvent (Color c, String type) { NewColorStateChangeEvent ev = new NewColorStateChangeEvent (c, type); for (ChangeListener cl : this.changeListeners) { cl.stateChanged (ev); } // Sneaky :) this.rs.setValue (c.getRed ()); this.gs.setValue (c.getGreen ()); this.bs.setValue (c.getBlue ()); } public static QPopup getColorChooserPopup (final String title, final Color initialColor, final String userPropName, final ChangeListener cl, final ActionListener closeListener) { final QColorChooser cc = new QColorChooser (initialColor); cc.setUserPropertyName (userPropName); final QPopup qp = UIUtils.createClosablePopup ((title != null ? title : getUIString (colorchooser,popup,title)), //"Select a color"), null, closeListener); cc.setBorder (UIUtils.createPadding (0, 0, 10, 0)); if (cl != null) { cc.addChangeListener (cl); } Box content = new Box (BoxLayout.Y_AXIS); content.setBorder (UIUtils.createPadding (10, 10, 10, 10)); cc.setAlignmentX (Component.LEFT_ALIGNMENT); content.add (cc); JButton f = UIUtils.createButton (getUIString (buttons,finish), new ActionListener () { @Override public void actionPerformed (ActionEvent ev) { cc.addSwatchColor (cc.getCurrentColor ()); qp.removeFromParent (); } }); JButton r = UIUtils.createButton (getUIString (colorchooser,popup,reset,text), //"Reset", new ActionListener () { @Override public void actionPerformed (ActionEvent ev) { cc.resetToInitial (); } }); r.setToolTipText (getUIString (colorchooser,popup,reset,tooltip)); //"Reset to the initial color."); JButton[] _buts = { f, r }; JComponent bs = UIUtils.createButtonBar2 (_buts, Component.CENTER_ALIGNMENT); bs.setAlignmentX (Component.LEFT_ALIGNMENT); content.add (bs); qp.setContent (content); return qp; } public void addSwatchColor (Color c) { if (!this.getSwatchColors ().contains (c)) { DefaultListModel<Color> model = (DefaultListModel<Color>) this.swatches.getModel (); if (model.getSize () < 2) { model.addElement (c); } else { Enumeration<Color> els = model.elements (); int ind = 0; int bind = -1; int wind = -1; int s = model.getSize (); while (els.hasMoreElements ()) { Color _c = els.nextElement (); if (_c == Color.black) { bind = ind; } if (_c == Color.white) { wind = ind; } ind++; } if (bind > 0) { if (s > bind) { model.add (bind + 1, c); } else { model.addElement (c); } } if ((bind < 0) && (wind > 0) ) { if (s > wind) { model.add (wind + 1, c); } else { model.addElement (c); } } if ((bind < 0) && (wind < 0) ) { model.add (0, c); } } Set<Color> ncols = new LinkedHashSet (Collections.list (model.elements ())); this.setSwatchColors (ncols); } } public Set<Color> getSwatchColors () { String colors = UserProperties.get (Constants.COLOR_SWATCHES_PROPERTY_NAME); StringTokenizer t = new StringTokenizer (colors, ","); Set<Color> cols = new LinkedHashSet (); cols.add (Color.white); cols.add (Color.black); while (t.hasMoreTokens ()) { cols.add (UIUtils.getColor (t.nextToken ().trim ())); } return cols; } private void setSwatchColors (Set<Color> colors) { StringBuilder b = new StringBuilder (); if (colors == null) { return; } Iterator<Color> iter = colors.iterator (); while (iter.hasNext ()) { Color col = iter.next (); String c = UIUtils.colorToHex (col).toUpperCase (); if ((c.equals ("#000000")) || (c.equals ("#FFFFFF")) ) { continue; } b.append (c); if (iter.hasNext ()) { b.append (","); } } UserProperties.set (Constants.COLOR_SWATCHES_PROPERTY_NAME, b.toString ()); } }
apache-2.0
kwakutwumasi/Quakearts-JSF-Webtools
qa-testtools/src/test/java/test/junit/beans/Parent.java
1242
/******************************************************************************* * Copyright (C) 2016 Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com>. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com> - initial API and implementation ******************************************************************************/ package test.junit.beans; import java.util.List; import com.quakearts.tools.test.generator.annotation.CollectionType; public class Parent { private Person person; private List<Parent> children; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } @CollectionType(Parent.class) public List<Parent> getChildren() { return children; } public void setChildren(List<Parent> children) { this.children = children; } @Override public String toString() { return "Parent [person=" + person + ", children=" + children + "]"; } }
apache-2.0
wxb2939/rwxlicai
mzb-phone-app-android/MzbCustomerApp/src/main/java/com/xem/mzbcustomerapp/adapter/TextAdapter.java
1473
package com.xem.mzbcustomerapp.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.xem.mzbcustomerapp.R; import com.xem.mzbcustomerapp.entity.GridViewDetail; import java.util.ArrayList; /** * Created by xuebing on 15/11/25. */ public class TextAdapter extends BaseAdapter { Context mContext; ArrayList<GridViewDetail> list; public TextAdapter(Context mContext,ArrayList<GridViewDetail> list){ this.mContext=mContext; this.list=list; } @Override public int getCount() { return 6; } @Override public Object getItem(int position) { return list != null ? null:list.get(6%position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null){ convertView= LayoutInflater.from(mContext).inflate(R.layout.mygrid_item,null); } if (position < list.size()){ GridViewDetail obj=list.get(position); ((ImageView)convertView.findViewById(R.id.images)).setImageResource(obj.images); ((TextView)convertView.findViewById(R.id.tex)).setText(obj.desc); } return convertView; } }
apache-2.0
skyrohithigh/Build-It-Bigger
app/src/test/java/rohit/bitshifters/com/builditbigger/ExampleUnitTest.java
328
package rohit.bitshifters.com.builditbigger; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
oneliang/third-party-lib
google/com/google/common/io/Closeables.java
4612
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.logging.Level; import java.util.logging.Logger; /** * Utility methods for working with {@link Closeable} objects. * * @author Michael Lancaster * @since 1.0 */ @Beta public final class Closeables { @VisibleForTesting static final Logger logger = Logger.getLogger(Closeables.class.getName()); private Closeables() {} /** * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown. * This is primarily useful in a finally block, where a thrown exception needs to be logged but * not propagated (otherwise the original exception will be lost). * * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log * it. * * <p>Example: <pre> {@code * * public void useStreamNicely() throws IOException { * SomeStream stream = new SomeStream("foo"); * boolean threw = true; * try { * // ... code which does something with the stream ... * threw = false; * } finally { * // If an exception occurs, rethrow it only if threw==false: * Closeables.close(stream, threw); * } * }}</pre> * * @param closeable the {@code Closeable} object to be closed, or null, in which case this method * does nothing * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close} * methods * @throws IOException if {@code swallowIOException} is false and {@code close} throws an * {@code IOException}. */ public static void close( Closeable closeable, boolean swallowIOException) throws IOException { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { if (swallowIOException) { logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e); } else { throw e; } } } /** * Closes the given {@link InputStream}, logging any {@code IOException} that's thrown rather * than propagating it. * * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing * an I/O resource, it should generally be safe in the case of a resource that's being used only * for reading, such as an {@code InputStream}. Unlike with writable resources, there's no * chance that a failure that occurs when closing the stream indicates a meaningful problem such * as a failure to flush all bytes to the underlying resource. * * @param inputStream the input stream to be closed, or {@code null} in which case this method * does nothing * @since 17.0 */ public static void closeQuietly( InputStream inputStream) { try { close(inputStream, true); } catch (IOException impossible) { throw new AssertionError(impossible); } } /** * Closes the given {@link Reader}, logging any {@code IOException} that's thrown rather than * propagating it. * * <p>While it's not safe in the general case to ignore exceptions that are thrown when closing * an I/O resource, it should generally be safe in the case of a resource that's being used only * for reading, such as a {@code Reader}. Unlike with writable resources, there's no chance that * a failure that occurs when closing the reader indicates a meaningful problem such as a failure * to flush all bytes to the underlying resource. * * @param reader the reader to be closed, or {@code null} in which case this method does nothing * @since 17.0 */ public static void closeQuietly( Reader reader) { try { close(reader, true); } catch (IOException impossible) { throw new AssertionError(impossible); } } }
apache-2.0
thanple/icevirgin
Project/sicevirgin/src/main/java/com/thanple/gs/app/chat/toast/ToastUtil.java
955
package com.thanple.gs.app.chat.toast; import com.thanple.gs.app.session.user.ISession; import com.thanple.gs.app.session.user.Onlines; import com.thanple.gs.app.session.user.Session; import com.thanple.gs.common.nio.manager.Protocol; import com.thanple.gs.common.nio.protocol._SToastMsg; import io.netty.channel.ChannelHandlerContext; /** * Created by Thanple on 2017/5/31. */ public class ToastUtil { /** * 弹出Toast提示 * */ public static void show(ChannelHandlerContext ctx, String msg) { _SToastMsg.SToastMsg.Builder toast = _SToastMsg.SToastMsg.newBuilder(); toast.setMsg(msg); Protocol.send(ctx,toast.build()); } public static void show(long roleId,String msg) { ISession session = Onlines.getUserSession().get(roleId); _SToastMsg.SToastMsg.Builder toast = _SToastMsg.SToastMsg.newBuilder(); toast.setMsg(msg); session.writeChanel(toast.build()); } }
apache-2.0
benbek/HereAStory-Android
android-maps-extensions-2.1.0/android-maps-extensions-2.1.0/src/com/androidmapsextensions/impl/IGoogleMap.java
4611
/* * Copyright (C) 2013 Maciej Górski * * 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.androidmapsextensions.impl; import android.graphics.Bitmap; import android.location.Location; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.CancelableCallback; import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter; import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener; import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener; import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener; import com.google.android.gms.maps.LocationSource; import com.google.android.gms.maps.UiSettings; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.GroundOverlay; import com.google.android.gms.maps.model.GroundOverlayOptions; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.google.android.gms.maps.model.TileOverlay; import com.google.android.gms.maps.model.TileOverlayOptions; //TODO: to be deleted when com.google.android.gms.maps.GoogleMap becomes an interface interface IGoogleMap { Circle addCircle(CircleOptions options); GroundOverlay addGroundOverlay(GroundOverlayOptions options); Marker addMarker(MarkerOptions options); Polygon addPolygon(PolygonOptions options); Polyline addPolyline(PolylineOptions options); TileOverlay addTileOverlay(TileOverlayOptions options); void animateCamera(CameraUpdate update, CancelableCallback callback); void animateCamera(CameraUpdate update, int durationMs, CancelableCallback callback); void animateCamera(CameraUpdate update); void clear(); CameraPosition getCameraPosition(); int getMapType(); float getMaxZoomLevel(); float getMinZoomLevel(); Location getMyLocation(); IProjection getProjection(); UiSettings getUiSettings(); boolean isBuildingsEnabled(); boolean isIndoorEnabled(); boolean isMyLocationEnabled(); boolean isTrafficEnabled(); void moveCamera(CameraUpdate update); void setBuildingsEnabled(boolean enabled); boolean setIndoorEnabled(boolean enabled); void setInfoWindowAdapter(InfoWindowAdapter adapter); void setLocationSource(LocationSource source); void setMapType(int type); void setMyLocationEnabled(boolean enabled); void setOnCameraChangeListener(OnCameraChangeListener listener); void setOnInfoWindowClickListener(OnInfoWindowClickListener listener); void setOnMapClickListener(OnMapClickListener listener); void setOnMapLoadedCallback(GoogleMap.OnMapLoadedCallback callback); void setOnMapLongClickListener(OnMapLongClickListener listener); void setOnMarkerClickListener(OnMarkerClickListener listener); void setOnMarkerDragListener(OnMarkerDragListener listener); void setOnMyLocationButtonClickListener(OnMyLocationButtonClickListener listener); void setOnMyLocationChangeListener(OnMyLocationChangeListener listener); void setPadding(int left, int top, int right, int bottom); void setTrafficEnabled(boolean enabled); void snapshot(GoogleMap.SnapshotReadyCallback callback); void snapshot(GoogleMap.SnapshotReadyCallback callback, Bitmap bitmap); void stopAnimation(); GoogleMap getMap(); }
apache-2.0
triceo/splitlog
splitlog-api/src/main/java/com/github/triceo/splitlog/api/LogWatchBuilder.java
13297
package com.github.triceo.splitlog.api; import java.io.File; import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; /** * Prepares an instance of {@link LogWatch} that will automatically * {@link LogWatch#start()}. Unless overriden by the user, the instance will * have the following properties: * * <dl> * <dt>Reads file from beginning?</dt> * <dd>Yes.</dd> * <dt>Closes file when the reading is finished?</dt> * <dd>No.</dd> * <dt>The default interval between each read</dt> * <dd>See {@link #DEFAULT_DELAY_BETWEEN_READS_IN_MILLISECONDS}.</dd> * <dt>The buffer size for reading</dt> * <dd>See {@link #DEFAULT_READ_BUFFER_SIZE_IN_BYTES}.</dd> * <dt>Default message capacity</dt> * <dd>{@link Integer#MAX_VALUE}, the maximum possible.</dd> * <dt>Interval between two sweeps for unreachable messages.</dt> * <dd>See {@link #DEFAULT_DELAY_BETWEEN_SWEEPS_IN_MILLISECONDS}.</dd> * <dt>Interval between requesting tailing and the actual start of tailing.</dt> * </dl> * * By default, the instance will store (and notify of) every message that has * passed the {@link #getGateCondition()} and not do so for all others. */ public abstract class LogWatchBuilder { public static final long DEFAULT_DELAY_BETWEEN_READS_IN_MILLISECONDS = 1000; public static final long DEFAULT_DELAY_BETWEEN_SWEEPS_IN_MILLISECONDS = 60 * 1000; public static final int DEFAULT_READ_BUFFER_SIZE_IN_BYTES = 4096; /** * Used to construct a {@link LogWatch} for a particular log file. * * @return Builder that is used to configure the new log watch instance * before using. */ public static LogWatchBuilder getDefault() { final ServiceLoader<LogWatchBuilder> ldr = ServiceLoader.load(LogWatchBuilder.class); if (!ldr.iterator().hasNext()) { throw new IllegalStateException("No LogWatchBuilder implementation registered."); } return ldr.iterator().next(); } private static long getDelay(final int length, final TimeUnit unit) { if (length < 1) { throw new IllegalArgumentException("The length of time must be at least 1."); } switch (unit) { case NANOSECONDS: if (length < (1000 * 1000)) { throw new IllegalArgumentException("The length of time must amount to at least 1 ms."); } break; case MICROSECONDS: if (length < 1000) { throw new IllegalArgumentException("The length of time must amount to at least 1 ms."); } break; default: // every other unit is more than 1 ms by default } return unit.toMillis(length); } private boolean autoStarting = true; private int bufferSize = LogWatchBuilder.DEFAULT_READ_BUFFER_SIZE_IN_BYTES; private boolean closingBetweenReads; private long delayBetweenReads = LogWatchBuilder.DEFAULT_DELAY_BETWEEN_READS_IN_MILLISECONDS; private long delayBetweenSweeps = LogWatchBuilder.DEFAULT_DELAY_BETWEEN_SWEEPS_IN_MILLISECONDS; private File fileToWatch; private SimpleMessageCondition gateCondition; private int limitCapacityTo = Integer.MAX_VALUE; private boolean readingFromBeginning = true; private SimpleMessageCondition storageCondition; /** * Build the log watch with previously defined properties, or defaults where * not overriden. Such log watch will not start actually reading * {@link #getFileToWatch()} until after {@link LogWatch#startFollowing()} * or * {@link LogWatch#startConsuming(com.github.triceo.splitlog.api.MessageListener)} * . * * @return The newly built log watch. */ public abstract LogWatch build(); /** * Build the log watch with previously defined properties, or defaults where * not overriden, and immediately start listening for {@link Message}s. * * @return The follower that will receive the initial messages. The actual * {@link LogWatch} can be retrieved by * {@link Follower#getFollowed()}. */ public abstract Follower buildFollowing(); /** * Build the log watch with previously defined properties, or defaults where * not overriden, and immediately start listening for {@link Message}s * * @param splitter * The splitter instance to use for the log watch instead of the * default. * @return The follower that will receive the initial messages. The actual * {@link LogWatch} can be retrieved by * {@link Follower#getFollowed()}. */ public abstract Follower buildFollowingWith(final TailSplitter splitter); /** * Build the log watch with previously defined properties, or defaults where * not overriden. Such log watch will not start actually reading * {@link #getFileToWatch()} until after {@link LogWatch#startFollowing()} * or * {@link LogWatch#startConsuming(com.github.triceo.splitlog.api.MessageListener)} * . * * @param splitter * The splitter instance to use for the log watch instead of the * default. * @return The newly built log watch. This log watch will not start tailing * until after {@link LogWatch#startFollowing()} or * {@link LogWatch#startConsuming(com.github.triceo.splitlog.api.MessageListener)} * . */ public abstract LogWatch buildWith(final TailSplitter splitter); /** * Change the default behavior of the future log watch to close the watched * file after each reading. * * @return This. */ public LogWatchBuilder closingAfterReading() { this.closingBetweenReads = true; return this; } /** * Do not run {@link LogWatch#start()} on the new instance. * * @return This. */ public LogWatchBuilder doNotStart() { this.autoStarting = false; return this; } /** * Get the capacity of the future log watch. * * @return Maximum capacity in messages. */ public int getCapacityLimit() { return this.limitCapacityTo; } /** * Get the delay between attempts to read from the watched file. * * @return In milliseconds. */ public long getDelayBetweenReads() { return this.delayBetweenReads; } /** * Get the delay between attempts to sweep unreachable messages from memory. * * @return In milliseconds. */ public long getDelayBetweenSweeps() { return this.delayBetweenSweeps; } /** * Get the file that the log watch will be watching. * * @return The file that will be watched by the future log watch. */ public File getFileToWatch() { return this.fileToWatch; } /** * The condition that will be used for accepting a {@link Message} into * {@link LogWatch}. * * @return The condition. */ public SimpleMessageCondition getGateCondition() { return this.gateCondition; } /** * Get the buffer size for the log watch. * * @return In bytes. */ public int getReadingBufferSize() { return this.bufferSize; } /** * The condition that will be used for storing a {@link Message} within * {@link LogWatch}. * * @return The condition. */ public SimpleMessageCondition getStorageCondition() { return this.storageCondition; } /** * Change the default behavior of the future log watch so that the existing * contents of the file is ignored and only the future additions to the file * are reported. * * @return This. */ public LogWatchBuilder ignoringPreexistingContent() { this.readingFromBeginning = false; return this; } /** * @return Whether or not the file will be closed after it is read from. */ public boolean isClosingBetweenReads() { return this.closingBetweenReads; } /** * @return True if the file will be read from the beginning, false if just * the additions made post starting the log watch. */ public boolean isReadingFromBeginning() { return this.readingFromBeginning; } /** * Limit capacity of the log watch to a given amount of messages. * * @param size * Maximum amount of messages to store. * @return This. */ public LogWatchBuilder limitCapacityTo(final int size) { if (size <= 0) { throw new IllegalArgumentException("Size of the memory store must be larger than zero."); } this.limitCapacityTo = size; return this; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("LogWatchBuilder [bufferSize=").append(this.bufferSize).append(", closingBetweenReads=") .append(this.closingBetweenReads).append(", delayBetweenReads=").append(this.delayBetweenReads) .append(", delayBetweenSweeps=").append(this.delayBetweenSweeps).append(", "); if (this.fileToWatch != null) { builder.append("fileToWatch=").append(this.fileToWatch).append(", "); } if (this.gateCondition != null) { builder.append("gateCondition=").append(this.gateCondition).append(", "); } builder.append("limitCapacityTo=").append(this.limitCapacityTo).append(", readingFromBeginning=") .append(this.readingFromBeginning).append(", "); if (this.storageCondition != null) { builder.append("storageCondition=").append(this.storageCondition); } builder.append("]"); return builder.toString(); } /** * Set the file that the future {@link LogWatch} will be tailing. * * @param f * File to watch. * @return This. */ public LogWatchBuilder watchedFile(final File f) { if (f == null) { throw new IllegalArgumentException("File can not be null."); } this.fileToWatch = f; return this; } /** * @return True if the new logwatch will already be {@link LogWatch#start()}ed. */ public boolean willBeStarted() { return this.autoStarting; } /** * Specify the delay between attempts to read the file. * * @param length * Length of time. * @param unit * Unit of that length. * @return This. */ public LogWatchBuilder withDelayBetweenReads(final int length, final TimeUnit unit) { this.delayBetweenReads = LogWatchBuilder.getDelay(length, unit); return this; } /** * Specify the delay between attempts to sweep the log watch from * unreachable messages. * * @param length * Length of time. * @param unit * Unit of that length. * @return This. */ public LogWatchBuilder withDelayBetweenSweeps(final int length, final TimeUnit unit) { this.delayBetweenSweeps = LogWatchBuilder.getDelay(length, unit); return this; } /** * Only the {@link Message}s for which * {@link SimpleMessageCondition#accept(Message)} is true will be passed to * {@link Follower}s and other {@link MessageConsumer}s. Such * {@link Message}s will also never be stored. For the purposes of Splitlog, * if it fails this condition, it's as if it never existed. * * @param condition * The condition. * @return This. */ public LogWatchBuilder withGateCondition(final SimpleMessageCondition condition) { if (condition == null) { throw new IllegalArgumentException("Gate condition must not be null."); } this.gateCondition = condition; return this; } /** * Specify the buffer size that will be used for reading changes made to the * watched file. * * @param bufferSize * In bytes. * @return This. */ public LogWatchBuilder withReadingBufferSize(final int bufferSize) { if (bufferSize < 1) { throw new IllegalArgumentException("Buffer size must be at least 1."); } this.bufferSize = bufferSize; return this; } /** * Only the messages for which * {@link SimpleMessageCondition#accept(Message)} is true will be stored * within the future {@link LogWatch}. However, {@link MessageConsumer}s * will be notified of them either way. * * The condition in question will only ever be called on {@link Message}s * that have already passed the {@link #getGateCondition()}. * * @param condition * The condition. * @return This. */ public LogWatchBuilder withStorageCondition(final SimpleMessageCondition condition) { if (condition == null) { throw new IllegalArgumentException("Storage acceptance condition must not be null."); } this.storageCondition = condition; return this; } }
apache-2.0
rbieniek/BGP4J
osgi-bundles/bgp4j-protocol-netty/src/main/java/org/bgp4j/netty/handlers/ValidateServerIdentifier.java
5075
/** * Copyright 2012 Rainer Bieniek (Rainer.Bieniek@web.de) * * 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.bgp4j.netty.handlers; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import org.bgp4j.definitions.peer.PeerConnectionInformation; import org.bgp4j.net.BGPv4Constants; import org.bgp4j.net.capabilities.AutonomousSystem4Capability; import org.bgp4j.net.packets.open.BadBgpIdentifierNotificationPacket; import org.bgp4j.net.packets.open.BadPeerASNotificationPacket; import org.bgp4j.net.packets.open.OpenPacket; import org.bgp4j.netty.Attributes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This channel handler checks if the OPEN packet contains the configured remote BGP identifier and autonomous system. If the configured * and the received BGP identifier or the configured and the received autonomous system do not match, the connection is closed. * The peer identifier verification is moved out of the finite state machine to make it generic for both client and server case. * * @author Rainer Bieniek (Rainer.Bieniek@web.de) * */ public class ValidateServerIdentifier extends ChannelInboundHandlerAdapter { private Logger log = LoggerFactory.getLogger(ValidateServerIdentifier.class); public static final String HANDLER_NAME ="BGP4-ValidateServerIdentifier"; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if(msg instanceof OpenPacket) { OpenPacket openPacket = (OpenPacket)msg; PeerConnectionInformation peerConnInfo = ctx.channel().attr(Attributes.peerInfoKey).get(); if(openPacket.getBgpIdentifier() != peerConnInfo.getRemoteBgpIdentifier()) { log.error("expected remote BGP identifier {}, received BGP identifier {}", peerConnInfo.getRemoteBgpIdentifier(), openPacket.getBgpIdentifier()); NotificationHelper.sendNotification(ctx, new BadBgpIdentifierNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } if(peerConnInfo.getRemoteAS() > 65535) { // we must have an AutonomousSystem4 capability at this point in the OPEN packet and a AS_TRANS 2-octet AS number if(openPacket.getAutonomousSystem() != BGPv4Constants.BGP_AS_TRANS) { log.error("expected remote autonomous system {}, received autonomous system {}", BGPv4Constants.BGP_AS_TRANS, openPacket.getAutonomousSystem()); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } AutonomousSystem4Capability as4cap = openPacket.findCapability(AutonomousSystem4Capability.class); if(as4cap == null) { log.error("missing Autonomous system 4-octet capability"); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } if(as4cap.getAutonomousSystem() != peerConnInfo.getRemoteAS()) { log.error("expected remote autonomous system {}, received autonomous system {}", peerConnInfo.getRemoteAS(), as4cap.getAutonomousSystem()); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } } else { if(openPacket.getAutonomousSystem() != peerConnInfo.getRemoteAS()) { log.error("expected remote autonomous system {}, received autonomous system {}", peerConnInfo.getRemoteAS(), openPacket.getAutonomousSystem()); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } // we may have an optional AS4 capability but if we have it it must carry the same AS number as the 2-octet AS number AutonomousSystem4Capability as4cap = openPacket.findCapability(AutonomousSystem4Capability.class); if(as4cap != null) { if(as4cap.getAutonomousSystem() != peerConnInfo.getRemoteAS()) { log.error("expected remote autonomous system {}, received autonomous system {}", peerConnInfo.getRemoteAS(), as4cap.getAutonomousSystem()); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } } } } ctx.fireChannelRead(msg); } }
apache-2.0
dflemstr/docker-java
src/test/java/com/github/dockerjava/client/command/BuildImageCmdTest.java
7486
package com.github.dockerjava.client.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.lang.reflect.Method; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang.StringUtils; import org.glassfish.jersey.client.ClientResponse; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; import javax.ws.rs.core.Response; public class BuildImageCmdTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); } @AfterTest public void afterTest() { super.afterTest(); } @BeforeMethod public void beforeMethod(Method method) { super.beforeMethod(method); } @AfterMethod public void afterMethod(ITestResult result) { super.afterMethod(result); } @Test public void testNginxDockerfileBuilder() throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("nginx").getFile()); Response response = dockerClient.buildImageCmd(baseDir).exec(); StringWriter logwriter = new StringWriter(); InputStream is = response.readEntity(InputStream.class); try { LineIterator itr = IOUtils.lineIterator( is, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { IOUtils.closeQuietly(is); } String fullLog = logwriter.toString(); assertThat(fullLog, containsString("Successfully built")); String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim(); InspectImageResponse inspectImageResponse = dockerClient .inspectImageCmd(imageId).exec(); assertThat(inspectImageResponse, not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); tmpImgs.add(inspectImageResponse.getId()); assertThat(inspectImageResponse.getAuthor(), equalTo("Guillaume J. Charmes \"guillaume@dotcloud.com\"")); } @Test public void testDockerBuilderAddUrl() throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testAddUrl").getFile()); dockerfileBuild(baseDir, "Docker"); } @Test public void testDockerBuilderAddFileInSubfolder() throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testAddFileInSubfolder").getFile()); dockerfileBuild(baseDir, "Successfully executed testrun.sh"); } @Test public void testDockerBuilderAddFolder() throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testAddFolder").getFile()); dockerfileBuild(baseDir, "Successfully executed testAddFolder.sh"); } private String dockerfileBuild(File baseDir, String expectedText) throws DockerException, IOException { // Build image Response response = dockerClient.buildImageCmd(baseDir).exec(); StringWriter logwriter = new StringWriter(); InputStream is = response.readEntity(InputStream.class); try { LineIterator itr = IOUtils.lineIterator( is, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { IOUtils.closeQuietly(is); } String fullLog = logwriter.toString(); assertThat(fullLog, containsString("Successfully built")); String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim(); // Create container based on image CreateContainerResponse container = dockerClient.createContainerCmd( imageId).exec(); LOG.info("Created container: {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); dockerClient.waitContainerCmd(container.getId()).exec(); tmpContainers.add(container.getId()); // Log container Response logResponse = logContainer(container .getId()); assertThat(logResponseStream(logResponse), containsString(expectedText)); return container.getId(); } private Response logContainer(String containerId) { return dockerClient.logContainerCmd(containerId).withStdErr().withStdOut().exec(); } @Test public void testNetCatDockerfileBuilder() throws DockerException, IOException, InterruptedException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("netcat").getFile()); Response response = dockerClient.buildImageCmd(baseDir).withNoCache().exec(); StringWriter logwriter = new StringWriter(); InputStream is = response.readEntity(InputStream.class); try { LineIterator itr = IOUtils.lineIterator( is, "UTF-8"); while (itr.hasNext()) { String line = itr.next(); logwriter.write(line + "\n"); LOG.info(line); } } finally { IOUtils.closeQuietly(is); } String fullLog = logwriter.toString(); assertThat(fullLog, containsString("Successfully built")); String imageId = StringUtils.substringBetween(fullLog, "Successfully built ", "\\n\"}").trim(); InspectImageResponse inspectImageResponse = dockerClient .inspectImageCmd(imageId).exec(); assertThat(inspectImageResponse, not(nullValue())); assertThat(inspectImageResponse.getId(), not(nullValue())); LOG.info("Image Inspect: {}", inspectImageResponse.toString()); tmpImgs.add(inspectImageResponse.getId()); CreateContainerResponse container = dockerClient.createContainerCmd( inspectImageResponse.getId()).exec(); assertThat(container.getId(), not(isEmptyString())); dockerClient.startContainerCmd(container.getId()).exec(); tmpContainers.add(container.getId()); InspectContainerResponse inspectContainerResponse = dockerClient .inspectContainerCmd(container.getId()).exec(); assertThat(inspectContainerResponse.getId(), notNullValue()); assertThat(inspectContainerResponse.getNetworkSettings().getPorts(), notNullValue()); // No use as such if not running on the server // for (Ports.Port p : inspectContainerResponse.getNetworkSettings().getPorts().getAllPorts()) { // int port = Integer.valueOf(p.getHostPort()); // LOG.info("Checking port {} is open", port); // assertThat(available(port), is(false)); // } dockerClient.stopContainerCmd(container.getId()).withTimeout(0).exec(); } @Test public void testAddAndCopySubstitution () throws DockerException, IOException { File baseDir = new File(Thread.currentThread().getContextClassLoader() .getResource("testENVSubstitution").getFile()); dockerfileBuild(baseDir, "testENVSubstitution successfully completed"); } }
apache-2.0
migbee/migbee
src/main/java/com/github/migbee/annotation/ChangeSet.java
1067
package com.github.migbee.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ChangeSet { /** * Author of the changeSet. * Mandatory * @return author */ String author(); // must be set /** * Unique NAME of the changeSet. * Mandatory * @return unique name */ String name(); // must be set /** * Sequence that provide correct order for changeSet. Sorted alphabetically, ascending. * Mandatory. * @return ordering */ String order(); // must be set /** * Executes the change set on every migbee's execution, even if it has been run before. * Optional (default is false) * @return should run always? */ boolean runAlways() default false; /** * When true, if the migration fails, an exceptionRuntime is thrown * Optional (default is false) * @return isCritical ? */ boolean isCritical() default false; }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/transform/CreateConfigurationSetRequestMarshaller.java
2259
/* * 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.simpleemail.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.simpleemail.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * CreateConfigurationSetRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateConfigurationSetRequestMarshaller implements Marshaller<Request<CreateConfigurationSetRequest>, CreateConfigurationSetRequest> { public Request<CreateConfigurationSetRequest> marshall(CreateConfigurationSetRequest createConfigurationSetRequest) { if (createConfigurationSetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } Request<CreateConfigurationSetRequest> request = new DefaultRequest<CreateConfigurationSetRequest>(createConfigurationSetRequest, "AmazonSimpleEmailService"); request.addParameter("Action", "CreateConfigurationSet"); request.addParameter("Version", "2010-12-01"); request.setHttpMethod(HttpMethodName.POST); { ConfigurationSet configurationSet = createConfigurationSetRequest.getConfigurationSet(); if (configurationSet != null) { if (configurationSet.getName() != null) { request.addParameter("ConfigurationSet.Name", StringUtils.fromString(configurationSet.getName())); } } } return request; } }
apache-2.0
yohomall/yohomall
yohomall/src/com/yohomall/service/impl/OrdersServiceImpl.java
2670
package com.yohomall.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.yohomall.dao.OrdersMapper; import com.yohomall.pojo.Orderitem; import com.yohomall.pojo.Orders; import com.yohomall.pojo.OrdersVo; import com.yohomall.service.OrdersService; import com.yohomall.service.exception.existException; @Service(value="oservice") public class OrdersServiceImpl implements OrdersService { @Autowired private OrdersMapper ordersMapper; @Override public int newOrder(Orders order) { return ordersMapper.add(order); } @Transactional @Override public void save(Orders order) throws Exception{ //Ïòorders±íÖвåÈëÒ»ÌõÊý¾Ý ordersMapper.save(order); //Ïòorderitem±íÖвåÈë¶àÌõÊý¾Ý for (Orderitem orderitem:order.getOrderitems()) { ordersMapper.saveOrderItem(orderitem); } } @Override public int getTotalRecord(Integer uid) throws Exception { // TODO Auto-generated method stub return ordersMapper.getTotalRecord(uid); } @Override public List<Orders> getMyOrdersByPage(Integer uid, Integer StartIndex, Integer pageSize) throws Exception { List<Orders> list=ordersMapper.getMyOrdersByPage(uid, StartIndex, pageSize); for (Orders orders : list) { List<OrdersVo> list2=ordersMapper.getMyOrderItem(orders.getOid()); for (OrdersVo ordersVo : list2) { orders.getOrdersVos().add(ordersVo); } } return list; } @Override public Orders getByID(String oid) throws Exception { Orders order=ordersMapper.getByID(oid); List<OrdersVo> list=ordersMapper.getMyOrderItem(oid); for (OrdersVo ordersVo : list) { order.getOrdersVos().add(ordersVo); } return order; } @Override public void update(Orders order) throws Exception { ordersMapper.update(order); } @Override public List<Orders> findOrderDetails() { return ordersMapper.findOrderDetails(); } @Override public List<Orders> findAllOrder(Integer status,Integer StartIndex, Integer pageSize) { // TODO Auto-generated method stub return ordersMapper.findAllOrder(status, StartIndex, pageSize); } @Override public Integer getAdminTotalRecord(Integer status) { // TODO Auto-generated method stub return ordersMapper.getAdminTotalRecord(status); } }
apache-2.0
anuraaga/armeria
grpc/src/main/java/com/linecorp/armeria/server/grpc/ArmeriaServerCall.java
23456
/* * Copyright 2017 LINE Corporation * * LINE Corporation 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: * * 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.linecorp.armeria.server.grpc; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static io.netty.util.AsciiString.c2b; import static java.util.Objects.requireNonNull; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import javax.annotation.Nullable; import org.curioswitch.common.protobuf.json.MessageMarshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.util.concurrent.MoreExecutors; import com.linecorp.armeria.common.HttpData; import com.linecorp.armeria.common.HttpHeaders; import com.linecorp.armeria.common.HttpHeadersBuilder; import com.linecorp.armeria.common.HttpObject; import com.linecorp.armeria.common.HttpResponseWriter; import com.linecorp.armeria.common.ResponseHeaders; import com.linecorp.armeria.common.SerializationFormat; import com.linecorp.armeria.common.grpc.GrpcSerializationFormats; import com.linecorp.armeria.common.grpc.ThrowableProto; import com.linecorp.armeria.common.grpc.protocol.ArmeriaMessageDeframer; import com.linecorp.armeria.common.grpc.protocol.ArmeriaMessageDeframer.DeframedMessage; import com.linecorp.armeria.common.grpc.protocol.ArmeriaMessageFramer; import com.linecorp.armeria.common.grpc.protocol.Decompressor; import com.linecorp.armeria.common.grpc.protocol.GrpcHeaderNames; import com.linecorp.armeria.common.grpc.protocol.GrpcTrailersUtil; import com.linecorp.armeria.common.logging.RequestLogProperty; import com.linecorp.armeria.common.util.SafeCloseable; import com.linecorp.armeria.internal.common.grpc.ForwardingCompressor; import com.linecorp.armeria.internal.common.grpc.ForwardingDecompressor; import com.linecorp.armeria.internal.common.grpc.GrpcLogUtil; import com.linecorp.armeria.internal.common.grpc.GrpcMessageMarshaller; import com.linecorp.armeria.internal.common.grpc.GrpcStatus; import com.linecorp.armeria.internal.common.grpc.HttpStreamReader; import com.linecorp.armeria.internal.common.grpc.MetadataUtil; import com.linecorp.armeria.internal.common.grpc.TransportStatusListener; import com.linecorp.armeria.server.ServiceRequestContext; import com.linecorp.armeria.unsafe.ByteBufHttpData; import com.linecorp.armeria.unsafe.grpc.GrpcUnsafeBufferUtil; import io.grpc.Codec; import io.grpc.Codec.Identity; import io.grpc.Compressor; import io.grpc.CompressorRegistry; import io.grpc.DecompressorRegistry; import io.grpc.InternalMetadata; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.MethodDescriptor.MethodType; import io.grpc.ServerCall; import io.grpc.Status; import io.grpc.StatusException; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.util.AsciiString; /** * Encapsulates the state of a single server call, reading messages from the client, passing to business logic * via {@link ServerCall.Listener}, and writing messages passed back to the response. */ final class ArmeriaServerCall<I, O> extends ServerCall<I, O> implements ArmeriaMessageDeframer.Listener, TransportStatusListener { private static final Logger logger = LoggerFactory.getLogger(ArmeriaServerCall.class); @SuppressWarnings("rawtypes") private static final AtomicIntegerFieldUpdater<ArmeriaServerCall> pendingMessagesUpdater = AtomicIntegerFieldUpdater.newUpdater(ArmeriaServerCall.class, "pendingMessages"); // Only most significant bit of a byte is set. @VisibleForTesting static final byte TRAILERS_FRAME_HEADER = (byte) (1 << 7); private static final Splitter ACCEPT_ENCODING_SPLITTER = Splitter.on(',').trimResults(); private final MethodDescriptor<I, O> method; private final HttpStreamReader messageReader; private final ArmeriaMessageFramer messageFramer; private final HttpResponseWriter res; private final CompressorRegistry compressorRegistry; private final ServiceRequestContext ctx; private final SerializationFormat serializationFormat; private final GrpcMessageMarshaller<I, O> marshaller; private final boolean unsafeWrapRequestBuffers; @Nullable private final Executor blockingExecutor; private final ResponseHeaders defaultHeaders; // Only set once. @Nullable private ServerCall.Listener<I> listener; @Nullable private O firstResponse; @Nullable private final String clientAcceptEncoding; @Nullable private Compressor compressor; // Message compression defaults to being enabled unless a user disables it using a server interceptor. private boolean messageCompression = true; private boolean messageReceived; // state private volatile boolean cancelled; private volatile boolean clientStreamClosed; private volatile boolean listenerClosed; private boolean sendHeadersCalled; private boolean closeCalled; private volatile int pendingMessages; ArmeriaServerCall(HttpHeaders clientHeaders, MethodDescriptor<I, O> method, CompressorRegistry compressorRegistry, DecompressorRegistry decompressorRegistry, HttpResponseWriter res, int maxInboundMessageSizeBytes, int maxOutboundMessageSizeBytes, ServiceRequestContext ctx, SerializationFormat serializationFormat, @Nullable MessageMarshaller jsonMarshaller, boolean unsafeWrapRequestBuffers, boolean useBlockingTaskExecutor, ResponseHeaders defaultHeaders) { requireNonNull(clientHeaders, "clientHeaders"); this.method = requireNonNull(method, "method"); this.ctx = requireNonNull(ctx, "ctx"); this.serializationFormat = requireNonNull(serializationFormat, "serializationFormat"); this.defaultHeaders = requireNonNull(defaultHeaders, "defaultHeaders"); messageReader = new HttpStreamReader( requireNonNull(decompressorRegistry, "decompressorRegistry"), new ArmeriaMessageDeframer( this, maxInboundMessageSizeBytes, ctx.alloc()) .decompressor(clientDecompressor(clientHeaders, decompressorRegistry)), this); messageFramer = new ArmeriaMessageFramer(ctx.alloc(), maxOutboundMessageSizeBytes); this.res = requireNonNull(res, "res"); this.compressorRegistry = requireNonNull(compressorRegistry, "compressorRegistry"); clientAcceptEncoding = Strings.emptyToNull(clientHeaders.get(GrpcHeaderNames.GRPC_ACCEPT_ENCODING)); marshaller = new GrpcMessageMarshaller<>(ctx.alloc(), serializationFormat, method, jsonMarshaller, unsafeWrapRequestBuffers); this.unsafeWrapRequestBuffers = unsafeWrapRequestBuffers; blockingExecutor = useBlockingTaskExecutor ? MoreExecutors.newSequentialExecutor(ctx.blockingTaskExecutor()) : null; res.whenComplete().handleAsync((unused, t) -> { if (!closeCalled) { // Closed by client, not by server. cancelled = true; try (SafeCloseable ignore = ctx.push()) { close(Status.CANCELLED, new Metadata()); } } return null; }, ctx.eventLoop()); } @Override public void request(int numMessages) { if (ctx.eventLoop().inEventLoop()) { messageReader.request(numMessages); } else { ctx.eventLoop().submit(() -> messageReader.request(numMessages)); } } @Override public void sendHeaders(Metadata metadata) { if (ctx.eventLoop().inEventLoop()) { doSendHeaders(metadata); } else { ctx.eventLoop().submit(() -> doSendHeaders(metadata)); } } private void doSendHeaders(Metadata metadata) { checkState(!sendHeadersCalled, "sendHeaders already called"); checkState(!closeCalled, "call is closed"); if (compressor == null || !messageCompression || clientAcceptEncoding == null) { compressor = Codec.Identity.NONE; } else { final List<String> acceptedEncodingsList = ACCEPT_ENCODING_SPLITTER.splitToList(clientAcceptEncoding); if (!acceptedEncodingsList.contains(compressor.getMessageEncoding())) { // resort to using no compression. compressor = Codec.Identity.NONE; } } messageFramer.setCompressor(ForwardingCompressor.forGrpc(compressor)); ResponseHeaders headers = defaultHeaders; if (compressor != Codec.Identity.NONE || InternalMetadata.headerCount(metadata) > 0) { headers = headers.withMutations(builder -> { if (compressor != Codec.Identity.NONE) { builder.set(GrpcHeaderNames.GRPC_ENCODING, compressor.getMessageEncoding()); } MetadataUtil.fillHeaders(metadata, builder); }); } sendHeadersCalled = true; res.write(headers); } @Override public void sendMessage(O message) { pendingMessagesUpdater.incrementAndGet(this); if (ctx.eventLoop().inEventLoop()) { doSendMessage(message); } else { ctx.eventLoop().submit(() -> doSendMessage(message)); } } private void doSendMessage(O message) { checkState(sendHeadersCalled, "sendHeaders has not been called"); checkState(!closeCalled, "call is closed"); if (firstResponse == null) { firstResponse = message; } try { res.write(messageFramer.writePayload(marshaller.serializeResponse(message))); res.whenConsumed().thenRun(() -> { if (pendingMessagesUpdater.decrementAndGet(this) == 0) { if (blockingExecutor != null) { blockingExecutor.execute(this::invokeOnReady); } else { invokeOnReady(); } } }); } catch (RuntimeException e) { close(GrpcStatus.fromThrowable(e), new Metadata()); throw e; } catch (Throwable t) { close(GrpcStatus.fromThrowable(t), new Metadata()); throw new RuntimeException(t); } } private void invokeOnReady() { try { listener.onReady(); } catch (Throwable t) { close(GrpcStatus.fromThrowable(t), new Metadata()); } } @Override public boolean isReady() { return !closeCalled && pendingMessages == 0; } @Override public void close(Status status, Metadata metadata) { if (ctx.eventLoop().inEventLoop()) { doClose(status, metadata); } else { ctx.eventLoop().submit(() -> doClose(status, metadata)); } } private void doClose(Status status, Metadata metadata) { checkState(!closeCalled, "call already closed"); closeCalled = true; if (cancelled) { // No need to write anything to client if cancelled already. closeListener(status); return; } final HttpHeaders trailers = statusToTrailers(ctx, status, metadata, sendHeadersCalled); final HttpObject trailersObj; if (sendHeadersCalled && GrpcSerializationFormats.isGrpcWeb(serializationFormat)) { // Normal trailers are not supported in grpc-web and must be encoded as a message. // Message compression is not supported in grpc-web, so we don't bother using the normal // ArmeriaMessageFramer. trailersObj = serializeTrailersAsMessage(trailers); } else { trailersObj = trailers; } try { if (res.tryWrite(trailersObj)) { res.close(); } } finally { closeListener(status); } } @VisibleForTesting boolean isCloseCalled() { return closeCalled; } @Override public boolean isCancelled() { return cancelled; } @Override public synchronized void setMessageCompression(boolean messageCompression) { messageFramer.setMessageCompression(messageCompression); this.messageCompression = messageCompression; } @Override public synchronized void setCompression(String compressorName) { checkState(!sendHeadersCalled, "sendHeaders has been called"); compressor = compressorRegistry.lookupCompressor(compressorName); checkArgument(compressor != null, "Unable to find compressor by name %s", compressorName); messageFramer.setCompressor(ForwardingCompressor.forGrpc(compressor)); } @Override public MethodDescriptor<I, O> getMethodDescriptor() { return method; } @Override public void messageRead(DeframedMessage message) { final I request; final ByteBuf buf = message.buf(); boolean success = false; try { // Special case for unary calls. if (messageReceived && method.getType() == MethodType.UNARY) { closeListener(Status.INTERNAL.withDescription( "More than one request messages for unary call or server streaming call")); return; } messageReceived = true; if (isCancelled()) { return; } success = true; } finally { if (buf != null && !success) { buf.release(); } } try { request = marshaller.deserializeRequest(message); } catch (IOException e) { throw new UncheckedIOException(e); } if (!ctx.log().isAvailable(RequestLogProperty.REQUEST_CONTENT)) { ctx.logBuilder().requestContent(GrpcLogUtil.rpcRequest(method, request), null); } if (unsafeWrapRequestBuffers && buf != null) { GrpcUnsafeBufferUtil.storeBuffer(buf, request, ctx); } if (blockingExecutor != null) { blockingExecutor.execute(() -> invokeOnMessage(request)); } else { invokeOnMessage(request); } } private void invokeOnMessage(I request) { try (SafeCloseable ignored = ctx.push()) { listener.onMessage(request); } catch (Throwable t) { close(GrpcStatus.fromThrowable(t), new Metadata()); } } @Override public void endOfStream() { setClientStreamClosed(); if (!closeCalled) { if (!ctx.log().isAvailable(RequestLogProperty.REQUEST_CONTENT)) { ctx.logBuilder().requestContent(GrpcLogUtil.rpcRequest(method), null); } if (blockingExecutor != null) { blockingExecutor.execute(this::invokeHalfClose); } else { invokeHalfClose(); } } } private void invokeHalfClose() { try (SafeCloseable ignored = ctx.push()) { listener.onHalfClose(); } catch (Throwable t) { close(GrpcStatus.fromThrowable(t), new Metadata()); } } @Override public void transportReportStatus(Status status, Metadata unused) { // A server doesn't see trailers from the client so will never have Metadata here. if (closeCalled) { // We've already called close on the server-side and will close the listener with the server-side // status, so we ignore client transport status's at this point (it's usually the RST_STREAM // corresponding to a successful stream ending in practice, but even if it was an actual transport // failure there's no need to notify the server listener of it). return; } closeListener(status); } private void closeListener(Status newStatus) { if (!listenerClosed) { listenerClosed = true; setClientStreamClosed(); messageFramer.close(); ctx.logBuilder().responseContent(GrpcLogUtil.rpcResponse(newStatus, firstResponse), null); if (newStatus.isOk()) { if (blockingExecutor != null) { blockingExecutor.execute(this::invokeOnComplete); } else { invokeOnComplete(); } } else { cancelled = true; if (blockingExecutor != null) { blockingExecutor.execute(this::invokeOnCancel); } else { invokeOnCancel(); } // Transport error, not business logic error, so reset the stream. if (!closeCalled) { final StatusException statusException = newStatus.asException(); final Throwable cause = statusException.getCause(); if (cause != null) { res.close(cause); } else { res.abort(); } } } } } private void invokeOnComplete() { try (SafeCloseable ignored = ctx.push()) { listener.onComplete(); } catch (Throwable t) { // This should not be possible with normal generated stubs which do not implement // onComplete, but is conceivable for a completely manually constructed stub. logger.warn("Error in gRPC onComplete handler.", t); } } private void invokeOnCancel() { try (SafeCloseable ignored = ctx.push()) { listener.onCancel(); } catch (Throwable t) { if (!closeCalled) { // A custom error when dealing with client cancel or transport issues should be // returned. We have already closed the listener, so it will not receive any more // callbacks as designed. close(GrpcStatus.fromThrowable(t), new Metadata()); } } } private void setClientStreamClosed() { if (!clientStreamClosed) { messageReader().cancel(); clientStreamClosed = true; } } // Returns ResponseHeaders if headersSent == false or HttpHeaders otherwise. static HttpHeaders statusToTrailers( ServiceRequestContext ctx, Status status, Metadata metadata, boolean headersSent) { final HttpHeadersBuilder trailers = GrpcTrailersUtil.statusToTrailers( status.getCode().value(), status.getDescription(), headersSent); MetadataUtil.fillHeaders(metadata, trailers); if (ctx.config().verboseResponses() && status.getCause() != null) { final ThrowableProto proto = GrpcStatus.serializeThrowable(status.getCause()); trailers.add(GrpcHeaderNames.ARMERIA_GRPC_THROWABLEPROTO_BIN, Base64.getEncoder().encodeToString(proto.toByteArray())); } final HttpHeaders additionalTrailers = ctx.additionalResponseTrailers(); ctx.mutateAdditionalResponseTrailers(HttpHeadersBuilder::clear); trailers.add(additionalTrailers); return trailers.build(); } HttpStreamReader messageReader() { return messageReader; } void setListener(Listener<I> listener) { checkState(this.listener == null, "listener already set"); this.listener = requireNonNull(listener, "listener"); } private HttpData serializeTrailersAsMessage(HttpHeaders trailers) { final ByteBuf serialized = ctx.alloc().buffer(); boolean success = false; try { serialized.writeByte(TRAILERS_FRAME_HEADER); // Skip, we'll set this after serializing the headers. serialized.writeInt(0); for (Map.Entry<AsciiString, String> trailer : trailers) { encodeHeader(trailer.getKey(), trailer.getValue(), serialized); } final int messageSize = serialized.readableBytes() - 5; serialized.setInt(1, messageSize); success = true; } finally { if (!success) { serialized.release(); } } return new ByteBufHttpData(serialized, true); } @Nullable private static Decompressor clientDecompressor(HttpHeaders headers, DecompressorRegistry registry) { final String encoding = headers.get(GrpcHeaderNames.GRPC_ENCODING); if (encoding == null) { return ForwardingDecompressor.forGrpc(Identity.NONE); } final io.grpc.Decompressor decompressor = registry.lookupDecompressor(encoding); if (decompressor != null) { return ForwardingDecompressor.forGrpc(decompressor); } return ForwardingDecompressor.forGrpc(Identity.NONE); } // Copied from io.netty.handler.codec.http.HttpHeadersEncoder private static void encodeHeader(CharSequence name, CharSequence value, ByteBuf buf) { final int nameLen = name.length(); final int valueLen = value.length(); final int entryLen = nameLen + valueLen + 4; buf.ensureWritable(entryLen); int offset = buf.writerIndex(); writeAscii(buf, offset, name, nameLen); offset += nameLen; buf.setByte(offset++, ':'); buf.setByte(offset++, ' '); writeAscii(buf, offset, value, valueLen); offset += valueLen; buf.setByte(offset++, '\r'); buf.setByte(offset++, '\n'); buf.writerIndex(offset); } private static void writeAscii(ByteBuf buf, int offset, CharSequence value, int valueLen) { if (value instanceof AsciiString) { ByteBufUtil.copy((AsciiString) value, 0, buf, offset, valueLen); } else { writeCharSequence(buf, offset, value, valueLen); } } private static void writeCharSequence(ByteBuf buf, int offset, CharSequence value, int valueLen) { for (int i = 0; i < valueLen; ++i) { buf.setByte(offset++, c2b(value.charAt(i))); } } }
apache-2.0
VHAINNOVATIONS/Telepathology
Source/Java/CoreValueObjects/main/src/java/gov/va/med/imaging/datasource/DataSourceSpi.java
1567
/** * Package: MAG - VistA Imaging * WARNING: Per VHA Directive 2004-038, this routine should not be modified. * Date Created: Apr 30, 2008 * Site Name: Washington OI Field Office, Silver Spring, MD * @author VHAISWBECKEC * @version 1.0 * * ---------------------------------------------------------------- * Property of the US Government. * No permission to copy or redistribute this software is given. * Use of unreleased versions of this software requires the user * to execute a written test agreement with the VistA Imaging * Development Office of the Department of Veterans Affairs, * telephone (301) 734-0100. * * The Food and Drug Administration classifies this software as * a Class II medical device. As such, it may not be changed * in any way. Modifications to this software may result in an * adulterated medical device under 21CFR820, the use of which * is considered to be a violation of US Federal Statutes. * ---------------------------------------------------------------- */ package gov.va.med.imaging.datasource; /** * The root abstract class of all service provider interfaces. * This is simply a marker-interface to allow for the use * of type-safe generics. * * Known Derivations: * @see gov.va.med.imaging.datasource.VersionableDataSourceSpi * @see gov.va.med.imaging.datasource.LocalDataSourceSpi * * @author VHAISWBECKEC * */ public interface DataSourceSpi { /** * Sets the configuration of the data source. * * @param configuration */ public void setConfiguration(Object configuration); }
apache-2.0
intropro/prairie
units/hdfs-unit/src/main/java/com/intropro/prairie/unit/hdfs/cmd/HdfsShell.java
1208
package com.intropro.prairie.unit.hdfs.cmd; import com.intropro.prairie.unit.cmd.Command; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FsShell; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.List; /** * Created by presidentio on 8/19/16. */ public class HdfsShell implements Command { private static final Logger LOGGER = LogManager.getLogger(HdfsShell.class); private Configuration configuration; public HdfsShell(Configuration configuration) { this.configuration = configuration; } @Override public int exec(List<String> args, Reader in, Writer out) throws InterruptedException, IOException { FsShell fsShell = new FsShellWithIO(configuration, in, out); try { return fsShell.run(args.subList(1, args.size()).toArray(new String[args.size() - 1])); } catch (Exception e) { LOGGER.error("Failed to execute hdfs shell with args: " + args, e); return 1; } } @Override public boolean useInputStream() { return false; } }
apache-2.0
pacozaa/BoofCV
main/ip/test/boofcv/abst/filter/binary/TestAdaptiveGaussianBinaryFilter.java
1846
/* * Copyright (c) 2011-2014, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.abst.filter.binary; import boofcv.alg.filter.binary.GThresholdImageOps; import boofcv.alg.misc.GImageMiscOps; import boofcv.core.image.GeneralizedImageOps; import boofcv.struct.image.ImageFloat32; import boofcv.struct.image.ImageSingleBand; import boofcv.struct.image.ImageType; import boofcv.struct.image.ImageUInt8; import boofcv.testing.BoofTesting; import org.junit.Test; import java.util.Random; /** * @author Peter Abeles */ public class TestAdaptiveGaussianBinaryFilter { Random rand = new Random(234); @Test public void compare() { Class imageTypes[] = new Class[]{ImageUInt8.class,ImageFloat32.class}; for( Class type : imageTypes ) { ImageSingleBand input = GeneralizedImageOps.createSingleBand(type,30,40); ImageUInt8 found = new ImageUInt8(30,40); ImageUInt8 expected = new ImageUInt8(30,40); GImageMiscOps.fillUniform(input,rand,0,200); AdaptiveGaussianBinaryFilter alg = new AdaptiveGaussianBinaryFilter(4,-1,true, ImageType.single(type)); alg.process(input,found); GThresholdImageOps.adaptiveGaussian(input,expected,4,-1,true,null,null); BoofTesting.assertEquals(found,expected,0); } } }
apache-2.0
codemonkeykings/study
designmode/src/main/java/faced/nonuse/support/CodeGenerator.java
252
package faced.nonuse.support; /** * 代码生成接口. * * @author Zhang.Ge * @version v1.0 2017年3月25日 下午11:24:08 */ public interface CodeGenerator { /** * 代码生成. */ public void generate(); }
apache-2.0
stormleoxia/teamcity-nuget-support
nuget-server/src/jetbrains/buildServer/nuget/server/toolRegistry/ui/EditNugetExeSettingsGroupController.java
2501
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.nuget.server.toolRegistry.ui; import jetbrains.buildServer.controllers.BaseController; import jetbrains.buildServer.nuget.server.toolRegistry.NuGetToolManager; import jetbrains.buildServer.util.StringUtil; import jetbrains.buildServer.web.openapi.PluginDescriptor; import jetbrains.buildServer.web.openapi.WebControllerManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author Evgeniy.Koshkin */ public class EditNugetExeSettingsGroupController extends BaseController { private final PluginDescriptor myDescriptor; private final NuGetToolManager myToolManager; public EditNugetExeSettingsGroupController(@NotNull final NuGetToolManager toolManager, @NotNull final PluginDescriptor descriptor, @NotNull final WebControllerManager web) { myToolManager = toolManager; myDescriptor = descriptor; web.registerController(descriptor.getPluginResourcesPath("tool/editNugetExeSettings.html"), this); } @Nullable @Override protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response) throws Exception { final ModelAndView mv = new ModelAndView(myDescriptor.getPluginResourcesPath("tool/nugetExeSettingsGroup.jsp")); mv.getModel().put("name", safe(request.getParameter("name"))); mv.getModel().put("clazz", safe(request.getParameter("class"))); mv.getModel().put("nugetExeDefaultSpecified", myToolManager.getDefaultTool() != null); return mv; } @NotNull private static String safe(@Nullable String s) { if (s == null || StringUtil.isEmptyOrSpaces(s)) return ""; return s; } }
apache-2.0
alancnet/artifactory
web/common/src/main/java/org/artifactory/common/wicket/model/SelectedItemModel.java
1685
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.common.wicket.model; import org.apache.wicket.model.IModel; import java.util.Collection; /** * Boolean model for selecting item in a collection. If model value is true, item is contained in collection. Else, item * isn't contained in collection. * * @author Yoav Aharoni */ public class SelectedItemModel<T> implements IModel<Boolean> { private Collection<T> items; private T item; public SelectedItemModel(Collection<T> items, T item) { this.items = items; this.item = item; } @Override public Boolean getObject() { return items.contains(item); } @Override public void setObject(Boolean object) { if ((Boolean) object) { if (!items.contains(item)) { items.add(item); } } else { items.remove(item); } } @Override public void detach() { } }
apache-2.0
samueltardieu/cgeo
main/src/cgeo/geocaching/WaypointPopupFragment.java
5332
package cgeo.geocaching; import cgeo.geocaching.apps.navi.NavigationAppFactory; import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.location.Units; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.models.Waypoint; import cgeo.geocaching.sensors.GeoData; import cgeo.geocaching.storage.DataStore; import cgeo.geocaching.ui.CacheDetailsCreator; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; public class WaypointPopupFragment extends AbstractDialogFragment { @Bind(R.id.actionbar_title) protected TextView actionBarTitle; @Bind(R.id.waypoint_details_list) protected LinearLayout waypointDetailsLayout; @Bind(R.id.edit) protected Button buttonEdit; @Bind(R.id.details_list) protected LinearLayout cacheDetailsLayout; private int waypointId = 0; private Waypoint waypoint = null; private TextView waypointDistance = null; @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.waypoint_popup, container, false); initCustomActionBar(v); ButterKnife.bind(this,v); return v; } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); waypointId = getArguments().getInt(WAYPOINT_ARG); } @Override protected void onUpdateGeoData(final GeoData geo) { if (waypoint != null) { final Geopoint coordinates = waypoint.getCoords(); if (coordinates != null) { waypointDistance.setText(Units.getDistanceFromKilometers(geo.getCoords().distanceTo(coordinates))); waypointDistance.bringToFront(); } } } @Override protected void init() { super.init(); waypoint = DataStore.loadWaypoint(waypointId); if (waypoint == null) { Log.e("WaypointPopupFragment.init: unable to get waypoint " + waypointId); getActivity().finish(); return; } try { if (StringUtils.isNotBlank(waypoint.getName())) { setTitle(waypoint.getName()); } else { setTitle(waypoint.getGeocode()); } actionBarTitle.setCompoundDrawablesWithIntrinsicBounds(Compatibility.getDrawable(getResources(), waypoint.getWaypointType().markerId), null, null, null); //getSupportActionBar().setIcon(getResources().getDrawable(waypoint.getWaypointType().markerId)); details = new CacheDetailsCreator(getActivity(), waypointDetailsLayout); //Waypoint geocode details.add(R.string.cache_geocode, waypoint.getPrefix() + waypoint.getGeocode().substring(2)); details.addDistance(waypoint, waypointDistance); waypointDistance = details.getValueView(); details.add(R.string.waypoint_note, waypoint.getNote()); buttonEdit.setOnClickListener(new OnClickListener() { @Override public void onClick(final View arg0) { EditWaypointActivity.startActivityEditWaypoint(getActivity(), cache, waypoint.getId()); getActivity().finish(); } }); details = new CacheDetailsCreator(getActivity(), cacheDetailsLayout); details.add(R.string.cache_name, cache.getName()); addCacheDetails(); } catch (final Exception e) { Log.e("WaypointPopup.init", e); } } @Override public void navigateTo() { NavigationAppFactory.startDefaultNavigationApplication(1, getActivity(), waypoint); } /** * Tries to navigate to the {@link Geocache} of this activity. */ @Override public void startDefaultNavigation2() { if (waypoint == null || waypoint.getCoords() == null) { showToast(res.getString(R.string.cache_coordinates_no)); return; } NavigationAppFactory.startDefaultNavigationApplication(2, getActivity(), waypoint); getActivity().finish(); } @Override public void showNavigationMenu() { NavigationAppFactory.showNavigationMenu(getActivity(), null, waypoint, null); } @Override protected Geopoint getCoordinates() { if (waypoint == null) { return null; } return waypoint.getCoords(); } public static DialogFragment newInstance(final String geocode, final int waypointId) { final Bundle args = new Bundle(); args.putInt(WAYPOINT_ARG, waypointId); args.putString(GEOCODE_ARG, geocode); final DialogFragment f = new WaypointPopupFragment(); f.setArguments(args); f.setStyle(DialogFragment.STYLE_NO_TITLE,0); return f; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-eventbridge/src/main/java/com/amazonaws/services/eventbridge/model/DisableRuleResult.java
2316
/* * 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.eventbridge.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/eventbridge-2015-10-07/DisableRule" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DisableRuleResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DisableRuleResult == false) return false; DisableRuleResult other = (DisableRuleResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public DisableRuleResult clone() { try { return (DisableRuleResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowablePublish.java
16009
/* * Copyright (c) 2016-present, RxJava 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 io.reactivex.rxjava3.internal.operators.flowable; import java.util.concurrent.atomic.*; import org.reactivestreams.*; import io.reactivex.rxjava3.core.FlowableSubscriber; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.exceptions.*; import io.reactivex.rxjava3.flowables.ConnectableFlowable; import io.reactivex.rxjava3.functions.Consumer; import io.reactivex.rxjava3.internal.fuseable.*; import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper; import io.reactivex.rxjava3.internal.util.*; import io.reactivex.rxjava3.operators.QueueSubscription; import io.reactivex.rxjava3.operators.SimpleQueue; import io.reactivex.rxjava3.operators.SpscArrayQueue; import io.reactivex.rxjava3.plugins.RxJavaPlugins; /** * Shares a single underlying connection to the upstream Publisher * and multicasts events to all subscribed subscribers until the upstream * completes or the connection is disposed. * <p> * The difference to FlowablePublish is that when the upstream terminates, * late subscribers will receive that terminal event until the connection is * disposed and the ConnectableFlowable is reset to its fresh state. * * @param <T> the element type * @since 2.2.10 */ public final class FlowablePublish<T> extends ConnectableFlowable<T> implements HasUpstreamPublisher<T> { final Publisher<T> source; final int bufferSize; final AtomicReference<PublishConnection<T>> current; public FlowablePublish(Publisher<T> source, int bufferSize) { this.source = source; this.bufferSize = bufferSize; this.current = new AtomicReference<>(); } @Override public Publisher<T> source() { return source; } @Override public void connect(Consumer<? super Disposable> connection) { PublishConnection<T> conn; boolean doConnect = false; for (;;) { conn = current.get(); if (conn == null || conn.isDisposed()) { PublishConnection<T> fresh = new PublishConnection<>(current, bufferSize); if (!current.compareAndSet(conn, fresh)) { continue; } conn = fresh; } doConnect = !conn.connect.get() && conn.connect.compareAndSet(false, true); break; } try { connection.accept(conn); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); throw ExceptionHelper.wrapOrThrow(ex); } if (doConnect) { source.subscribe(conn); } } @Override protected void subscribeActual(Subscriber<? super T> s) { PublishConnection<T> conn; for (;;) { conn = current.get(); // don't create a fresh connection if the current is disposed if (conn == null) { PublishConnection<T> fresh = new PublishConnection<>(current, bufferSize); if (!current.compareAndSet(conn, fresh)) { continue; } conn = fresh; } break; } InnerSubscription<T> inner = new InnerSubscription<>(s, conn); s.onSubscribe(inner); if (conn.add(inner)) { if (inner.isCancelled()) { conn.remove(inner); } else { conn.drain(); } return; } Throwable ex = conn.error; if (ex != null) { inner.downstream.onError(ex); } else { inner.downstream.onComplete(); } } @Override public void reset() { PublishConnection<T> conn = current.get(); if (conn != null && conn.isDisposed()) { current.compareAndSet(conn, null); } } static final class PublishConnection<T> extends AtomicInteger implements FlowableSubscriber<T>, Disposable { private static final long serialVersionUID = -1672047311619175801L; final AtomicReference<PublishConnection<T>> current; final AtomicReference<Subscription> upstream; final AtomicBoolean connect; final AtomicReference<InnerSubscription<T>[]> subscribers; final int bufferSize; volatile SimpleQueue<T> queue; int sourceMode; volatile boolean done; Throwable error; int consumed; @SuppressWarnings("rawtypes") static final InnerSubscription[] EMPTY = new InnerSubscription[0]; @SuppressWarnings("rawtypes") static final InnerSubscription[] TERMINATED = new InnerSubscription[0]; @SuppressWarnings("unchecked") PublishConnection(AtomicReference<PublishConnection<T>> current, int bufferSize) { this.current = current; this.upstream = new AtomicReference<>(); this.connect = new AtomicBoolean(); this.bufferSize = bufferSize; this.subscribers = new AtomicReference<>(EMPTY); } @SuppressWarnings("unchecked") @Override public void dispose() { subscribers.getAndSet(TERMINATED); current.compareAndSet(this, null); SubscriptionHelper.cancel(upstream); } @Override public boolean isDisposed() { return subscribers.get() == TERMINATED; } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.setOnce(this.upstream, s)) { if (s instanceof QueueSubscription) { @SuppressWarnings("unchecked") QueueSubscription<T> qs = (QueueSubscription<T>) s; int m = qs.requestFusion(QueueSubscription.ANY | QueueSubscription.BOUNDARY); if (m == QueueSubscription.SYNC) { sourceMode = m; queue = qs; done = true; drain(); return; } if (m == QueueSubscription.ASYNC) { sourceMode = m; queue = qs; s.request(bufferSize); return; } } queue = new SpscArrayQueue<>(bufferSize); s.request(bufferSize); } } @Override public void onNext(T t) { // we expect upstream to honor backpressure requests if (sourceMode == QueueSubscription.NONE && !queue.offer(t)) { onError(new MissingBackpressureException("Prefetch queue is full?!")); return; } // since many things can happen concurrently, we have a common dispatch // loop to act on the current state serially drain(); } @Override public void onError(Throwable t) { if (done) { RxJavaPlugins.onError(t); } else { error = t; done = true; drain(); } } @Override public void onComplete() { done = true; drain(); } void drain() { if (getAndIncrement() != 0) { return; } int missed = 1; SimpleQueue<T> queue = this.queue; int consumed = this.consumed; int limit = this.bufferSize - (this.bufferSize >> 2); boolean async = this.sourceMode != QueueSubscription.SYNC; outer: for (;;) { if (queue != null) { long minDemand = Long.MAX_VALUE; boolean hasDemand = false; InnerSubscription<T>[] consumers = subscribers.get(); for (InnerSubscription<T> inner : consumers) { long request = inner.get(); if (request != Long.MIN_VALUE) { hasDemand = true; minDemand = Math.min(request - inner.emitted, minDemand); } } if (!hasDemand) { minDemand = 0L; } while (minDemand != 0L) { boolean d = done; T v; try { v = queue.poll(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.get().cancel(); queue.clear(); done = true; signalError(ex); return; } boolean empty = v == null; if (checkTerminated(d, empty)) { return; } if (empty) { break; } for (InnerSubscription<T> inner : consumers) { if (!inner.isCancelled()) { inner.downstream.onNext(v); inner.emitted++; } } if (async && ++consumed == limit) { consumed = 0; upstream.get().request(limit); } minDemand--; if (consumers != subscribers.get()) { continue outer; } } if (checkTerminated(done, queue.isEmpty())) { return; } } this.consumed = consumed; missed = addAndGet(-missed); if (missed == 0) { break; } if (queue == null) { queue = this.queue; } } } @SuppressWarnings("unchecked") boolean checkTerminated(boolean isDone, boolean isEmpty) { if (isDone && isEmpty) { Throwable ex = error; if (ex != null) { signalError(ex); } else { for (InnerSubscription<T> inner : subscribers.getAndSet(TERMINATED)) { if (!inner.isCancelled()) { inner.downstream.onComplete(); } } } return true; } return false; } @SuppressWarnings("unchecked") void signalError(Throwable ex) { for (InnerSubscription<T> inner : subscribers.getAndSet(TERMINATED)) { if (!inner.isCancelled()) { inner.downstream.onError(ex); } } } boolean add(InnerSubscription<T> inner) { // the state can change so we do a CAS loop to achieve atomicity for (;;) { // get the current producer array InnerSubscription<T>[] c = subscribers.get(); // if this subscriber-to-source reached a terminal state by receiving // an onError or onComplete, just refuse to add the new producer if (c == TERMINATED) { return false; } // we perform a copy-on-write logic int len = c.length; @SuppressWarnings("unchecked") InnerSubscription<T>[] u = new InnerSubscription[len + 1]; System.arraycopy(c, 0, u, 0, len); u[len] = inner; // try setting the subscribers array if (subscribers.compareAndSet(c, u)) { return true; } // if failed, some other operation succeeded (another add, remove or termination) // so retry } } @SuppressWarnings("unchecked") void remove(InnerSubscription<T> inner) { // the state can change so we do a CAS loop to achieve atomicity for (;;) { // let's read the current subscribers array InnerSubscription<T>[] c = subscribers.get(); int len = c.length; // if it is either empty or terminated, there is nothing to remove so we quit if (len == 0) { break; } // let's find the supplied producer in the array // although this is O(n), we don't expect too many child subscribers in general int j = -1; for (int i = 0; i < len; i++) { if (c[i] == inner) { j = i; break; } } // we didn't find it so just quit if (j < 0) { return; } // we do copy-on-write logic here InnerSubscription<T>[] u; // we don't create a new empty array if producer was the single inhabitant // but rather reuse an empty array if (len == 1) { u = EMPTY; } else { // otherwise, create a new array one less in size u = new InnerSubscription[len - 1]; // copy elements being before the given producer System.arraycopy(c, 0, u, 0, j); // copy elements being after the given producer System.arraycopy(c, j + 1, u, j, len - j - 1); } // try setting this new array as if (subscribers.compareAndSet(c, u)) { break; } // if we failed, it means something else happened // (a concurrent add/remove or termination), we need to retry } } } static final class InnerSubscription<T> extends AtomicLong implements Subscription { private static final long serialVersionUID = 2845000326761540265L; final Subscriber<? super T> downstream; final PublishConnection<T> parent; long emitted; InnerSubscription(Subscriber<? super T> downstream, PublishConnection<T> parent) { this.downstream = downstream; this.parent = parent; } @Override public void request(long n) { if (SubscriptionHelper.validate(n)) { BackpressureHelper.addCancel(this, n); parent.drain(); } } @Override public void cancel() { if (getAndSet(Long.MIN_VALUE) != Long.MIN_VALUE) { parent.remove(this); parent.drain(); } } public boolean isCancelled() { return get() == Long.MIN_VALUE; } } }
apache-2.0
EvilMcJerkface/crate
server/src/main/java/io/crate/analyze/relations/select/SelectAnalyzer.java
5828
/* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.analyze.relations.select; import io.crate.analyze.OutputNameFormatter; import io.crate.analyze.expressions.ExpressionAnalysisContext; import io.crate.analyze.expressions.ExpressionAnalyzer; import io.crate.analyze.relations.AnalyzedRelation; import io.crate.analyze.validator.SelectSymbolValidator; import io.crate.expression.symbol.AliasSymbol; import io.crate.expression.symbol.Symbol; import io.crate.expression.symbol.Symbols; import io.crate.metadata.ColumnIdent; import io.crate.metadata.RelationName; import io.crate.sql.tree.AllColumns; import io.crate.sql.tree.DefaultTraversalVisitor; import io.crate.sql.tree.QualifiedName; import io.crate.sql.tree.SelectItem; import io.crate.sql.tree.SingleColumn; import java.util.List; import java.util.Locale; import java.util.Map; public class SelectAnalyzer { public static final InnerVisitor INSTANCE = new InnerVisitor(); public static SelectAnalysis analyzeSelectItems(List<SelectItem> selectItems, Map<RelationName, AnalyzedRelation> sources, ExpressionAnalyzer expressionAnalyzer, ExpressionAnalysisContext expressionAnalysisContext) { SelectAnalysis selectAnalysis = new SelectAnalysis( selectItems.size(), sources, expressionAnalyzer, expressionAnalysisContext); selectItems.forEach(x -> x.accept(INSTANCE, selectAnalysis)); SelectSymbolValidator.validate(selectAnalysis.outputSymbols()); return selectAnalysis; } private static class InnerVisitor extends DefaultTraversalVisitor<Void, SelectAnalysis> { @Override protected Void visitSingleColumn(SingleColumn node, SelectAnalysis context) { Symbol symbol = context.toSymbol(node.getExpression()); String alias = node.getAlias(); if (alias != null) { context.add(new ColumnIdent(alias), new AliasSymbol(alias, symbol)); } else { context.add(new ColumnIdent(OutputNameFormatter.format(node.getExpression())), symbol); } return null; } @Override protected Void visitAllColumns(AllColumns node, SelectAnalysis context) { if (node.getPrefix().isPresent()) { // prefix is either: <tableOrAlias>.* or <schema>.<table> QualifiedName prefix = node.getPrefix().get(); AnalyzedRelation relation = context.sources().get(RelationName.of(prefix, null)); if (relation != null) { addAllFieldsFromRelation(context, relation); return null; } int matches = 0; if (prefix.getParts().size() == 1) { // e.g. select mytable.* from foo.mytable; prefix is mytable, source is [foo, mytable] // if prefix matches second part of qualified name this is okay String prefixName = prefix.getParts().get(0); for (Map.Entry<RelationName, AnalyzedRelation> entry : context.sources().entrySet()) { RelationName relationName = entry.getKey(); // schema.table if (relationName.schema() != null && prefixName.equals(relationName.name())) { addAllFieldsFromRelation(context, entry.getValue()); matches++; } } } switch (matches) { case 0: throw new IllegalArgumentException(String.format(Locale.ENGLISH, "The relation \"%s\" is not in the FROM clause.", prefix)); case 1: return null; // yay found something default: // e.g. select mytable.* from foo.mytable, bar.mytable throw new IllegalArgumentException(String.format(Locale.ENGLISH, "The referenced relation \"%s\" is ambiguous.", prefix)); } } else { for (AnalyzedRelation relation : context.sources().values()) { addAllFieldsFromRelation(context, relation); } } return null; } private static void addAllFieldsFromRelation(SelectAnalysis context, AnalyzedRelation relation) { for (Symbol field : relation.outputs()) { var columnIdent = Symbols.pathFromSymbol(field); if (!columnIdent.isSystemColumn()) { context.add(Symbols.pathFromSymbol(field), field); } } } } }
apache-2.0
blackcathacker/kc.preclean
coeus-code/src/main/java/org/kuali/coeus/common/budget/impl/calculator/BudgetCalculationServiceImpl.java
56670
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-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.kuali.coeus.common.budget.impl.calculator; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.common.budget.api.rate.RateClassType; import org.kuali.coeus.common.budget.framework.calculator.*; import org.kuali.coeus.common.budget.framework.query.QueryList; import org.kuali.coeus.sys.api.model.ScaleTwoDecimal; import org.kuali.kra.award.budget.AwardBudgetLineItemCalculatedAmountExt; import org.kuali.coeus.common.budget.framework.query.operator.And; import org.kuali.coeus.common.budget.framework.query.operator.Equals; import org.kuali.coeus.common.budget.framework.core.category.BudgetCategoryType; import org.kuali.coeus.common.budget.framework.core.*; import org.kuali.coeus.common.budget.framework.distribution.BudgetDistributionService; import org.kuali.coeus.common.budget.framework.core.BudgetDocument; import org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetLineItem; import org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetLineItemCalculatedAmount; import org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetRateAndBase; import org.kuali.coeus.common.budget.framework.period.BudgetPeriod; import org.kuali.coeus.common.budget.framework.personnel.BudgetPersonnelCalculatedAmount; import org.kuali.coeus.common.budget.framework.personnel.BudgetPersonnelDetails; import org.kuali.coeus.common.budget.framework.personnel.BudgetPersonnelRateAndBase; import org.kuali.coeus.common.budget.framework.rate.RateClass; import org.kuali.coeus.common.budget.framework.rate.RateType; import org.kuali.coeus.common.budget.framework.core.BudgetForm; import org.kuali.coeus.propdev.impl.hierarchy.HierarchyStatusConstants; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.kns.util.KNSGlobalVariables; import org.kuali.rice.kns.web.struts.form.KualiForm; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.MessageMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.util.*; /** * This class implements all methods declared in BudgetCalculationService */ @Component("budgetCalculationService") public class BudgetCalculationServiceImpl implements BudgetCalculationService { @Autowired @Qualifier("businessObjectService") private BusinessObjectService businessObjectService; @Autowired @Qualifier("budgetDistributionService") private BudgetDistributionService budgetDistributionService; @Autowired @Qualifier("parameterService") private ParameterService parameterService; @Override public void calculateBudget(Budget budget){ List<BudgetPeriod> budgetPeriods = budget.getBudgetPeriods(); String ohRateClassCodePrevValue = null; BudgetForm form = getBudgetFormFromGlobalVariables(); for (BudgetPeriod budgetPeriod : budgetPeriods) { if(isCalculationRequired(budget,budgetPeriod)){ String workOhCode = null; if(budget.getOhRateClassCode()!=null && form!=null && budget.getBudgetPeriods().size() > budgetPeriod.getBudgetPeriod()){ workOhCode = form.getOhRateClassCodePrevValue(); } calculateBudgetPeriod(budget, budgetPeriod); if(budget.getOhRateClassCode()!=null && form!=null && budget.getBudgetPeriods().size() > budgetPeriod.getBudgetPeriod()){ // this should be set at the last period, otherwise, only the first period will be updated properly because lots of places check prevohrateclass ohRateClassCodePrevValue = form.getOhRateClassCodePrevValue(); form.setOhRateClassCodePrevValue(workOhCode); } } } if (form!=null && form.getOhRateClassCodePrevValue() == null && ohRateClassCodePrevValue != null) { // if not all periods are calculated, then this code has potential to be null, and this will force // to create calamts again form.setOhRateClassCodePrevValue(ohRateClassCodePrevValue); } if(budgetPeriods!=null && !budgetPeriods.isEmpty()){ syncCostsToBudget(budget); } } /** * Checks if a calculation is required where Budget periods must be synced in line items. * * @param budgetPeriod the current budget period. * * @return true if calculation is required false if not */ protected boolean isCalculationRequired(Budget budget, final BudgetPeriod budgetPeriod){ assert budgetPeriod != null : "The budget period is null"; boolean budgetLineItemDeleted = budget.isBudgetLineItemDeleted(); if(getBudgetCommonService(budget).isRateOverridden(budgetPeriod)){ return false; } if (StringUtils.equals(budgetPeriod.getBudget().getBudgetParent().getHierarchyStatus(), HierarchyStatusConstants.Parent.code())) { return true; } final boolean isLineItemsEmpty = budgetPeriod.getBudgetLineItems().isEmpty(); if(isLineItemsEmpty && !budgetLineItemDeleted){ final Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("budgetId", budgetPeriod.getBudgetId()); fieldValues.put("budgetPeriod", budgetPeriod.getBudgetPeriod()); @SuppressWarnings("unchecked") final Collection<BudgetLineItem> deletedLineItems = this.businessObjectService.findMatching(BudgetLineItem.class, fieldValues); return !deletedLineItems.isEmpty(); } return true; } protected void copyLineItemToPersonnelDetails(BudgetLineItem budgetLineItem, BudgetPersonnelDetails budgetPersonnelDetails) { budgetPersonnelDetails.setBudgetId(budgetLineItem.getBudgetId()); budgetPersonnelDetails.setBudgetPeriod(budgetLineItem.getBudgetPeriod()); budgetPersonnelDetails.setLineItemNumber(budgetLineItem.getLineItemNumber()); budgetPersonnelDetails.setCostElement(budgetLineItem.getCostElement()); budgetPersonnelDetails.setCostElementBO(budgetLineItem.getCostElementBO()); budgetPersonnelDetails.setApplyInRateFlag(budgetLineItem.getApplyInRateFlag()); budgetPersonnelDetails.setOnOffCampusFlag(budgetLineItem.getOnOffCampusFlag()); } @Override public void calculateBudgetLineItem(Budget budget,BudgetPersonnelDetails budgetLineItem){ new PersonnelLineItemCalculator(budget,budgetLineItem).calculate(); } @Override public void calculateBudgetLineItem(Budget budget,BudgetLineItem budgetLineItem){ BudgetLineItem budgetLineItemToCalc = budgetLineItem; List<BudgetPersonnelDetails> budgetPersonnelDetList = budgetLineItemToCalc.getBudgetPersonnelDetailsList(); if(budgetLineItemToCalc.isBudgetPersonnelLineItemDeleted() || (budgetPersonnelDetList!=null && !budgetPersonnelDetList.isEmpty())){ updatePersonnelBudgetRate(budgetLineItemToCalc); ScaleTwoDecimal personnelLineItemTotal = ScaleTwoDecimal.ZERO; ScaleTwoDecimal personnelTotalCostSharing = ScaleTwoDecimal.ZERO; Map<String, ScaleTwoDecimal> totalCalculatedCost = new HashMap<String, ScaleTwoDecimal> (); Map<String, ScaleTwoDecimal> totalCalculatedCostSharing = new HashMap<String, ScaleTwoDecimal> (); ScaleTwoDecimal newTotalUrAmount = ScaleTwoDecimal.ZERO; budgetLineItem.getBudgetRateAndBaseList().clear(); int rateNumber = 0; boolean resetTotalUnderRecovery = false; ScaleTwoDecimal calcDirectCost = ScaleTwoDecimal.ZERO; ScaleTwoDecimal calcIndirectCost = ScaleTwoDecimal.ZERO; ScaleTwoDecimal calcTotalCostSharing = ScaleTwoDecimal.ZERO; for (BudgetPersonnelDetails budgetPersonnelDetails : budgetPersonnelDetList) { copyLineItemToPersonnelDetails(budgetLineItemToCalc, budgetPersonnelDetails); new PersonnelLineItemCalculator(budget,budgetPersonnelDetails).calculate(); personnelLineItemTotal = personnelLineItemTotal.add(budgetPersonnelDetails.getLineItemCost()); personnelTotalCostSharing = personnelTotalCostSharing.add(budgetPersonnelDetails.getCostSharingAmount()); newTotalUrAmount = newTotalUrAmount.add(budgetPersonnelDetails.getUnderrecoveryAmount()); resetTotalUnderRecovery = true; List<BudgetPersonnelCalculatedAmount> calAmts = budgetPersonnelDetails.getBudgetCalculatedAmounts(); if (CollectionUtils.isNotEmpty(calAmts)) { String rateKey; for (BudgetPersonnelCalculatedAmount personnelCalAmt :calAmts) { rateKey = personnelCalAmt.getRateClassCode()+":"+personnelCalAmt.getRateTypeCode(); if (!totalCalculatedCost.containsKey(rateKey)) { totalCalculatedCost.put(rateKey, personnelCalAmt.getCalculatedCost()); totalCalculatedCostSharing.put(rateKey, personnelCalAmt.getCalculatedCostSharing()); } else { ScaleTwoDecimal value = totalCalculatedCost.get(rateKey); value = value.add(personnelCalAmt.getCalculatedCost()); totalCalculatedCost.put(rateKey, value); value = totalCalculatedCostSharing.get(rateKey); value = value.add(personnelCalAmt.getCalculatedCostSharing()); totalCalculatedCostSharing.put(rateKey, value); } if (personnelCalAmt.getRateClass() == null) { personnelCalAmt.refreshReferenceObject("rateClass"); } if (!personnelCalAmt.getRateClass().getRateClassTypeCode().equals(RateClassType.OVERHEAD.getRateClassType())) { calcDirectCost = calcDirectCost.add(personnelCalAmt.getCalculatedCost()); } else { calcIndirectCost = calcIndirectCost.add(personnelCalAmt.getCalculatedCost()); } calcTotalCostSharing = calcTotalCostSharing.add(personnelCalAmt.getCalculatedCostSharing()); } } populateRateAndBase(budgetLineItem,budgetPersonnelDetails,rateNumber); } if (resetTotalUnderRecovery) { budgetLineItem.setUnderrecoveryAmount(newTotalUrAmount); } budgetLineItem.setLineItemCost(personnelLineItemTotal); budgetLineItem.setCostSharingAmount(personnelTotalCostSharing); budgetLineItem.setDirectCost(calcDirectCost.add(personnelLineItemTotal)); budgetLineItem.setTotalCostSharingAmount(calcTotalCostSharing.add(personnelTotalCostSharing)); budgetLineItem.setIndirectCost(calcIndirectCost); boolean lineItemCalcAmntsOutOfDate = false; if (budgetLineItem.getBudgetCalculatedAmounts().size() == totalCalculatedCost.size()) { for (BudgetLineItemCalculatedAmount lineItemCalAmt : budgetLineItem.getBudgetLineItemCalculatedAmounts()) { String rateKey = lineItemCalAmt.getRateClassCode()+":"+lineItemCalAmt.getRateTypeCode(); if (!totalCalculatedCost.containsKey(rateKey)) { lineItemCalcAmntsOutOfDate = true; break; } } } else { lineItemCalcAmntsOutOfDate = true; } if (lineItemCalcAmntsOutOfDate) { rePopulateCalculatedAmount(budget, budgetLineItemToCalc); } List <BudgetLineItemCalculatedAmount> budgetLineItemCalculatedAmounts = budgetLineItem.getBudgetLineItemCalculatedAmounts(); if (CollectionUtils.isNotEmpty(budgetLineItemCalculatedAmounts)) { String rateKey; for (BudgetLineItemCalculatedAmount lineItemCalAmt : budgetLineItemCalculatedAmounts) { rateKey = lineItemCalAmt.getRateClassCode()+":"+lineItemCalAmt.getRateTypeCode(); if (totalCalculatedCost.containsKey(rateKey)) { lineItemCalAmt.setCalculatedCost(totalCalculatedCost.get(rateKey)); lineItemCalAmt.setCalculatedCostSharing(totalCalculatedCostSharing.get(rateKey)); } } } } else { new LineItemCalculator(budget,budgetLineItem).calculate(); } } protected void populateRateAndBase(BudgetLineItem bli, BudgetPersonnelDetails budgetPersonnelDetails,int rateNumber) { List<BudgetRateAndBase> budgetRateAndBaseList = bli.getBudgetRateAndBaseList(); List<BudgetPersonnelRateAndBase> budgetPersonnelRateBaseList = budgetPersonnelDetails.getBudgetPersonnelRateAndBaseList(); for (BudgetPersonnelRateAndBase budgetPersonnelRateAndBase : budgetPersonnelRateBaseList) { BudgetRateAndBase budgetRateBase = new BudgetRateAndBase(); ScaleTwoDecimal appliedRate = budgetPersonnelRateAndBase.getAppliedRate(); budgetRateBase.setAppliedRate(ScaleTwoDecimal.returnZeroIfNull(appliedRate)); ScaleTwoDecimal calculatedCost = budgetPersonnelRateAndBase.getCalculatedCost(); ScaleTwoDecimal calculatedCostSharing = budgetPersonnelRateAndBase.getCalculatedCostSharing(); budgetRateBase.setBaseCostSharing(budgetPersonnelRateAndBase.getBaseCostSharing()); budgetRateBase.setBaseCost(budgetPersonnelRateAndBase.getSalaryRequested()); budgetRateBase.setBudgetPeriodId(budgetPersonnelRateAndBase.getBudgetPeriodId()); budgetRateBase.setBudgetPeriod(budgetPersonnelRateAndBase.getBudgetPeriod()); budgetRateBase.setCalculatedCost(calculatedCost); budgetRateBase.setCalculatedCostSharing(calculatedCostSharing); budgetRateBase.setEndDate(budgetPersonnelRateAndBase.getEndDate()); budgetRateBase.setLineItemNumber(budgetPersonnelRateAndBase.getLineItemNumber()); budgetRateBase.setOnOffCampusFlag(budgetPersonnelRateAndBase.getOnOffCampusFlag()); budgetRateBase.setBudgetId(budgetPersonnelRateAndBase.getBudgetId()); budgetRateBase.setRateClassCode(budgetPersonnelRateAndBase.getRateClassCode()); budgetRateBase.setRateNumber(++rateNumber); budgetRateBase.setRateTypeCode(budgetPersonnelRateAndBase.getRateTypeCode()); budgetRateBase.setStartDate(budgetPersonnelRateAndBase.getStartDate()); budgetRateAndBaseList.add(budgetRateBase); } } @Override public void populateCalculatedAmount(Budget budget,BudgetLineItem budgetLineItem){ new LineItemCalculator(budget,budgetLineItem).populateCalculatedAmountLineItems(); } @Override public void populateCalculatedAmount(Budget budget,BudgetPersonnelDetails budgetPersonnelDetails){ new PersonnelLineItemCalculator(budget,budgetPersonnelDetails).populateCalculatedAmountLineItems(); } @Override public void calculateBudgetPeriod(Budget budget, BudgetPeriod budgetPeriod){ if (isCalculationRequired(budget, budgetPeriod)){ new BudgetPeriodCalculator().calculate(budget, budgetPeriod); } } /** * Syncs the calculated costs in the budget document with the calculated costs in the budget * periods. If the certain costs are not positive then lists on items related to those costs * are also cleared and reset (i.e. UnrecoveredFandAs). * This method modifies the passed in Budget. * * @param budget the budget document */ protected void syncCostsToBudget(final Budget budget){ assert budget != null : "The budget was null"; this.initCostDependentItems(budget); this.ensureBudgetPeriodHasSyncedCosts(budget); this.setBudgetCostsFromPeriods(budget); } /** * Initializes items that are dependent on a cost value. (i.e. UnrecoveredFandAs) * This method modifies the passed in Budget. * * @param budget the budget document */ protected void initCostDependentItems(final Budget budget) { assert budget != null : "The budget was null"; if (!this.isPositiveTotalUnderreoveryAmount(budget)) { this.initUnrecoveredFandAs(budget); } if (!this.isPositiveTotalCostSharingAmount(budget)) { this.initCostSharing(budget); } } /** * Clears and initializes the UnrecoveredFandAs in a budget document. * This method modifies the passed in Budget. * * @param document the budget document. */ protected void initUnrecoveredFandAs(final Budget document) { assert document != null : "the document was null"; document.getBudgetUnrecoveredFandAs().clear(); this.getBudgetDistributionService().initializeUnrecoveredFandACollectionDefaults(document); } /** * Clears and initializes the CostSharing in a budget document. * This method modifies the passed in Budget. * * @param document the budget document. */ protected void initCostSharing(final Budget document) { assert document != null : "the document was null"; document.getBudgetCostShares().clear(); this.getBudgetDistributionService().initializeCostSharingCollectionDefaults(document); } /** * Ensures that a budget period has synced costs with other budget objects (i.e. line items) * */ protected void ensureBudgetPeriodHasSyncedCosts(final Budget budget) { assert budget != null : "the document was null"; for (final BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) { if (this.isCalculationRequired(budget, budgetPeriod)) { this.setBudgetPeriodCostsFromLineItems(budgetPeriod); } } } /** * * This method sets the budget document's costs from the budget periods' costs. * This method modifies the passed in budget document. * * @param budget the budget document to set the costs on. */ protected void setBudgetCostsFromPeriods(final Budget budget) { assert budget != null : "The document is null"; budget.setTotalDirectCost(budget.getSumDirectCostAmountFromPeriods()); budget.setTotalIndirectCost(budget.getSumIndirectCostAmountFromPeriods()); budget.setTotalCost(budget.getSumTotalCostAmountFromPeriods()); budget.setUnderrecoveryAmount(budget.getSumUnderreoveryAmountFromPeriods()); budget.setCostSharingAmount(budget.getSumCostSharingAmountFromPeriods()); } /** * * This method sets the budget period costs from the line item costs. * This method modifies the passed in budget period. * * @param budgetPeriod the budget periods to set the costs on. */ protected void setBudgetPeriodCostsFromLineItems(final BudgetPeriod budgetPeriod) { assert budgetPeriod != null : "The period is null"; budgetPeriod.setTotalDirectCost(budgetPeriod.getSumDirectCostAmountFromLineItems()); budgetPeriod.setTotalIndirectCost(budgetPeriod.getSumIndirectCostAmountFromLineItems()); budgetPeriod.setTotalCost(budgetPeriod.getSumTotalCostAmountFromLineItems()); budgetPeriod.setUnderrecoveryAmount(budgetPeriod.getSumUnderreoveryAmountFromLineItems()); budgetPeriod.setCostSharingAmount(budgetPeriod.getSumTotalCostSharingAmountFromLineItems()); } /** * Checks if a positive Total Underrecoverary Amount exists in a line item or in a budget period. * @param document The budget Document * @return true if positive. */ protected final boolean isPositiveTotalUnderreoveryAmount(final Budget document) { assert document != null : "The periods is null"; ScaleTwoDecimal lineItemsAmount = ScaleTwoDecimal.ZERO; for (final BudgetPeriod budgetPeriod : document.getBudgetPeriods()) { lineItemsAmount = lineItemsAmount.add(budgetPeriod.getSumUnderreoveryAmountFromLineItems()); } return lineItemsAmount.isPositive() || document.getSumUnderreoveryAmountFromPeriods().isPositive(); } /** * Checks if a positive Total CostSharing Amount exists in a line item or in a budget period. * @param document The budget Document * @return true if positive. */ protected final boolean isPositiveTotalCostSharingAmount(final Budget document) { assert document != null : "The document is null"; ScaleTwoDecimal lineItemsAmount = ScaleTwoDecimal.ZERO; for (final BudgetPeriod budgetPeriod : document.getBudgetPeriods()) { lineItemsAmount = lineItemsAmount.add(budgetPeriod.getSumTotalCostSharingAmountFromLineItems()); } return lineItemsAmount.isPositive() || document.getSumCostSharingAmountFromPeriods().isPositive(); } protected SortedMap<BudgetCategoryType, List<CostElement>> categorizeObjectCodesByCategory(Budget budget) { SortedMap<CostElement, List<ScaleTwoDecimal>> objectCodeTotals = budget.getObjectCodeTotals(); SortedMap<BudgetCategoryType, List<CostElement>> objectCodeListByBudgetCategoryType = new TreeMap<BudgetCategoryType, List<CostElement>>(); for(CostElement objectCode : objectCodeTotals.keySet()) { objectCode.refreshReferenceObject("budgetCategory"); if(objectCode.getBudgetCategory() != null) { objectCode.getBudgetCategory().refreshReferenceObject("budgetCategoryType"); objectCode.setBudgetCategoryTypeCode(objectCode.getBudgetCategory().getBudgetCategoryTypeCode()); } if(!objectCodeListByBudgetCategoryType.containsKey(objectCode.getBudgetCategory().getBudgetCategoryType())) { List<CostElement> filteredObjectCodes = filterObjectCodesByBudgetCategoryType(objectCodeTotals.keySet(), objectCode.getBudgetCategoryTypeCode()); objectCodeListByBudgetCategoryType.put(objectCode.getBudgetCategory().getBudgetCategoryType(), filteredObjectCodes); } } return objectCodeListByBudgetCategoryType; } protected BudgetCategoryType getPersonnelCategoryType() { final Map<String, String> primaryKeys = new HashMap<String, String>(); primaryKeys.put("budgetCategoryTypeCode", "P"); return this.getBusinessObjectService().findByPrimaryKey(BudgetCategoryType.class, primaryKeys); } @Override public void calculateBudgetSummaryTotals(Budget budget){ calculateBudgetTotals(budget); //Categorize all Object Codes per their Category Type SortedMap<BudgetCategoryType, List<CostElement>> objectCodeListByBudgetCategoryType = categorizeObjectCodesByCategory(budget); SortedMap<CostElement, List<BudgetPersonnelDetails>> objectCodeUniquePersonnelList = new TreeMap<CostElement, List<BudgetPersonnelDetails>>(); SortedMap<String, List<ScaleTwoDecimal>> objectCodePersonnelSalaryTotals = new TreeMap<String, List<ScaleTwoDecimal>>(); SortedMap<String, List<ScaleTwoDecimal>> objectCodePersonnelFringeTotals = new TreeMap<String, List<ScaleTwoDecimal>>(); //Temp collections for maintaining Sub Section Totals SortedSet<String> objectCodePersonnelSalaryTotalsByPeriod = new TreeSet<String>(); SortedSet<String> objectCodePersonnelFringeTotalsByPeriod = new TreeSet<String>(); SortedMap<RateType, List<ScaleTwoDecimal>> personnelCalculatedExpenseTotals = new TreeMap<RateType, List<ScaleTwoDecimal>>(); SortedMap<RateType, List<ScaleTwoDecimal>> nonPersonnelCalculatedExpenseTotals = new TreeMap<RateType, List<ScaleTwoDecimal>>(); List <ScaleTwoDecimal> periodSummarySalaryTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { periodSummarySalaryTotals.add(i, ScaleTwoDecimal.ZERO); } List <ScaleTwoDecimal> periodSummaryFringeTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { periodSummaryFringeTotals.add(i, ScaleTwoDecimal.ZERO); } SortedMap<String, List<ScaleTwoDecimal>> subTotalsBySubSection = new TreeMap<String, List<ScaleTwoDecimal>>(); subTotalsBySubSection.put("personnelSalaryTotals", periodSummarySalaryTotals); subTotalsBySubSection.put("personnelFringeTotals", periodSummaryFringeTotals); //Loop thru the Personnel Object Codes - to calculate Salary, Fringe Totals etc.. per person BudgetCategoryType personnelCategory = getPersonnelCategoryType(); List<CostElement> personnelObjectCodes = objectCodeListByBudgetCategoryType.get(personnelCategory); if(CollectionUtils.isNotEmpty(personnelObjectCodes)) { for(CostElement personnelCostElement : personnelObjectCodes) { if(!objectCodeUniquePersonnelList.containsKey(personnelCostElement)) { objectCodeUniquePersonnelList.put(personnelCostElement, new ArrayList<BudgetPersonnelDetails>()); } for (BudgetPeriod budgetPeriod: budget.getBudgetPeriods()) { budgetPeriod.setBudget(budget); QueryList lineItemQueryList = new QueryList(); lineItemQueryList.addAll(budgetPeriod.getBudgetLineItems()); Equals objectCodeEquals = new Equals("costElement", personnelCostElement.getCostElement()); QueryList<BudgetLineItem> filteredLineItems = lineItemQueryList.filter(objectCodeEquals); QueryList personnelQueryList = new QueryList(); //Loop thru the matching Line Items to gather personnel info for(BudgetLineItem matchingLineItem : filteredLineItems) { personnelQueryList.addAll(matchingLineItem.getBudgetPersonnelDetailsList()); } int matchingLineItemIndex = 0; for(BudgetLineItem matchingLineItem : filteredLineItems) { for(BudgetPersonnelDetails budgetPersonnelDetails : matchingLineItem.getBudgetPersonnelDetailsList()) { budgetPersonnelDetails.refreshReferenceObject("budgetPerson"); Equals personIdEquals = new Equals("personId", budgetPersonnelDetails.getPersonId()); QueryList personOccurrencesForSameObjectCode = personnelQueryList.filter(personIdEquals); //Calculate the Salary Totals for each Person ScaleTwoDecimal personSalaryTotalsForCurrentPeriod = personOccurrencesForSameObjectCode.sumObjects("salaryRequested"); if (!objectCodePersonnelSalaryTotals.containsKey(matchingLineItem.getCostElement()+","+budgetPersonnelDetails.getPersonId())) { objectCodeUniquePersonnelList.get(matchingLineItem.getCostElementBO()).add(budgetPersonnelDetails); // set up for all periods and put into map List <ScaleTwoDecimal> periodTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { periodTotals.add(i, ScaleTwoDecimal.ZERO); } objectCodePersonnelSalaryTotals.put(matchingLineItem.getCostElement()+","+budgetPersonnelDetails.getPersonId(), periodTotals); } //Setting the total lines here - so that they'll be set just once for a unique person within an Object Code objectCodePersonnelSalaryTotals.get(matchingLineItem.getCostElement()+","+budgetPersonnelDetails.getPersonId()).set(budgetPeriod.getBudgetPeriod() - 1, personSalaryTotalsForCurrentPeriod); if (objectCodePersonnelSalaryTotalsByPeriod.add(budgetPeriod.getBudgetPeriod().toString() + ","+ matchingLineItem.getCostElement()+","+budgetPersonnelDetails.getPersonId())) { subTotalsBySubSection.get("personnelSalaryTotals").set(budgetPeriod.getBudgetPeriod() - 1, ((ScaleTwoDecimal) (subTotalsBySubSection.get("personnelSalaryTotals").get(budgetPeriod.getBudgetPeriod() - 1))).add(personSalaryTotalsForCurrentPeriod)); } //Calculate the Fringe Totals for each Person if (!objectCodePersonnelFringeTotals.containsKey(matchingLineItem.getCostElement()+","+budgetPersonnelDetails.getPersonId())) { // set up for all periods and put into map List <ScaleTwoDecimal> periodFringeTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { periodFringeTotals.add(i, ScaleTwoDecimal.ZERO); } objectCodePersonnelFringeTotals.put(matchingLineItem.getCostElement()+","+budgetPersonnelDetails.getPersonId(), periodFringeTotals); } ScaleTwoDecimal personFringeTotalsForCurrentPeriod = ScaleTwoDecimal.ZERO; //Calculate the Fringe Totals for that Person (cumulative fringe for all occurrences of the person) for(Object person : personOccurrencesForSameObjectCode) { BudgetPersonnelDetails personOccurrence = (BudgetPersonnelDetails) person; for(BudgetPersonnelCalculatedAmount calcExpenseAmount : personOccurrence.getBudgetPersonnelCalculatedAmounts()) { calcExpenseAmount.refreshReferenceObject("rateClass"); //Check for Employee Benefits RateClassType if(calcExpenseAmount.getRateClass().getRateClassTypeCode().equalsIgnoreCase("E")) { personFringeTotalsForCurrentPeriod = personFringeTotalsForCurrentPeriod.add(calcExpenseAmount.getCalculatedCost()); } } } objectCodePersonnelFringeTotals.get(matchingLineItem.getCostElement()+","+budgetPersonnelDetails.getPersonId()).set(budgetPeriod.getBudgetPeriod() - 1, personFringeTotalsForCurrentPeriod); if (objectCodePersonnelFringeTotalsByPeriod.add(budgetPeriod.getBudgetPeriod().toString() + ","+ matchingLineItem.getCostElement()+","+budgetPersonnelDetails.getPersonId())) { subTotalsBySubSection.get("personnelFringeTotals").set(budgetPeriod.getBudgetPeriod() - 1, ((ScaleTwoDecimal) (subTotalsBySubSection.get("personnelFringeTotals").get(budgetPeriod.getBudgetPeriod() - 1))).add(personFringeTotalsForCurrentPeriod)); } } //Need to handle the Summary Items - if any if(CollectionUtils.isEmpty(matchingLineItem.getBudgetPersonnelDetailsList())) { //Include Summary Item Salary (Line Item Cost) if (!objectCodePersonnelSalaryTotals.containsKey(matchingLineItem.getCostElement())) { // set up for all periods and put into map List <ScaleTwoDecimal> periodTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { periodTotals.add(i, ScaleTwoDecimal.ZERO); } objectCodePersonnelSalaryTotals.put(matchingLineItem.getCostElement(), periodTotals); } objectCodePersonnelSalaryTotals.get(matchingLineItem.getCostElement()).set(budgetPeriod.getBudgetPeriod() - 1, ((ScaleTwoDecimal) objectCodePersonnelSalaryTotals.get(matchingLineItem.getCostElement()).get(budgetPeriod.getBudgetPeriod() - 1)).add(matchingLineItem.getLineItemCost())); //Include Summary Item Fringe Amt ScaleTwoDecimal summaryFringeTotalsForCurrentPeriod = ScaleTwoDecimal.ZERO; if (!objectCodePersonnelFringeTotals.containsKey(matchingLineItem.getCostElement())) { // set up for all periods and put into map List <ScaleTwoDecimal> periodFringeTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { periodFringeTotals.add(i, ScaleTwoDecimal.ZERO); } objectCodePersonnelFringeTotals.put(matchingLineItem.getCostElement(), periodFringeTotals); } for(BudgetLineItemCalculatedAmount lineItemCalculatedAmount : matchingLineItem.getBudgetLineItemCalculatedAmounts()) { lineItemCalculatedAmount.refreshReferenceObject("rateClass"); //Check for Employee Benefits RateClassType if(lineItemCalculatedAmount.getRateClass().getRateClassTypeCode().equalsIgnoreCase("E")) { summaryFringeTotalsForCurrentPeriod = summaryFringeTotalsForCurrentPeriod.add(lineItemCalculatedAmount.getCalculatedCost()); } } objectCodePersonnelFringeTotals.get(matchingLineItem.getCostElement()).set(budgetPeriod.getBudgetPeriod() - 1, ((ScaleTwoDecimal) objectCodePersonnelFringeTotals.get(matchingLineItem.getCostElement()).get(budgetPeriod.getBudgetPeriod() - 1)).add(summaryFringeTotalsForCurrentPeriod)); //if(matchingLineItemIndex == filteredLineItems.size()-1) { subTotalsBySubSection.get("personnelSalaryTotals").set(budgetPeriod.getBudgetPeriod() - 1, ((ScaleTwoDecimal) (subTotalsBySubSection.get("personnelSalaryTotals").get(budgetPeriod.getBudgetPeriod() - 1))).add((ScaleTwoDecimal) (objectCodePersonnelSalaryTotals.get(matchingLineItem.getCostElement()).get(budgetPeriod.getBudgetPeriod()-1)))); subTotalsBySubSection.get("personnelFringeTotals").set(budgetPeriod.getBudgetPeriod() - 1, ((ScaleTwoDecimal) (subTotalsBySubSection.get("personnelFringeTotals").get(budgetPeriod.getBudgetPeriod() - 1))).add((ScaleTwoDecimal) (objectCodePersonnelFringeTotals.get(matchingLineItem.getCostElement()).get(budgetPeriod.getBudgetPeriod()-1)))); //} } matchingLineItemIndex++; } } //Budget Period Looping Ends here } //Personnel Object Code Looping Ends here } budget.setBudgetSummaryTotals(subTotalsBySubSection); personnelCalculatedExpenseTotals = calculateExpenseTotals(budget, true); nonPersonnelCalculatedExpenseTotals = calculateExpenseTotals(budget, false); budget.setObjectCodeListByBudgetCategoryType(objectCodeListByBudgetCategoryType); budget.setObjectCodePersonnelList(objectCodeUniquePersonnelList); budget.setObjectCodePersonnelSalaryTotals(objectCodePersonnelSalaryTotals); budget.setObjectCodePersonnelFringeTotals(objectCodePersonnelFringeTotals); budget.setPersonnelCalculatedExpenseTotals(personnelCalculatedExpenseTotals); budget.setNonPersonnelCalculatedExpenseTotals(nonPersonnelCalculatedExpenseTotals); calculateNonPersonnelSummaryTotals(budget); populateBudgetPeriodSummaryCalcAmounts(budget); } @SuppressWarnings("unchecked") protected BudgetCommonService<BudgetParent> getBudgetCommonService(Budget budget) { return BudgetCommonServiceFactory.createInstance(budget.getBudgetParent()); } private boolean isRateOveridden(Budget budget,BudgetPeriod budgetPeriod){ BudgetCommonService<BudgetParent> budgetService = getBudgetCommonService(budget); return budgetService.isRateOverridden(budgetPeriod); } private void populateBudgetPeriodSummaryCalcAmounts(Budget budget) { List<BudgetPeriod> budgetPeriods = budget.getBudgetPeriods(); for (BudgetPeriod budgetPeriod : budgetPeriods) { if(!isRateOveridden(budget,budgetPeriod)){ getBudgetCommonService(budget).populateSummaryCalcAmounts(budget,budgetPeriod); } } } protected void calculateNonPersonnelSummaryTotals(Budget budget) { for(BudgetCategoryType budgetCategoryType : budget.getObjectCodeListByBudgetCategoryType().keySet()) { if(!StringUtils.equals(budgetCategoryType.getCode(), "P")) { List <ScaleTwoDecimal> nonPersonnelTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { nonPersonnelTotals.add(i, ScaleTwoDecimal.ZERO); } budget.getBudgetSummaryTotals().put(budgetCategoryType.getCode(), nonPersonnelTotals); List<CostElement> objectCodes = budget.getObjectCodeListByBudgetCategoryType().get(budgetCategoryType); for(CostElement objectCode : objectCodes) { if (!StringUtils.equalsIgnoreCase(objectCode.getCostElement(), getParameterService().getParameterValueAsString(BudgetDocument.class, "proposalHierarchySubProjectIndirectCostElement"))) { List<ScaleTwoDecimal> objectCodePeriodTotals = budget.getObjectCodeTotals().get(objectCode); for(BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) { budget.getBudgetSummaryTotals().get(budgetCategoryType.getCode()).set(budgetPeriod.getBudgetPeriod() - 1, ((ScaleTwoDecimal) (budget.getBudgetSummaryTotals().get(budgetCategoryType.getCode()).get(budgetPeriod.getBudgetPeriod() - 1))).add(objectCodePeriodTotals.get(budgetPeriod.getBudgetPeriod() - 1))); } } } } } } protected List<CostElement> filterObjectCodesByBudgetCategoryType(Set<CostElement> objectCodes, String budgetCategoryType) { List<CostElement> filteredObjectCodes = new ArrayList<CostElement>(); for(CostElement costElement : objectCodes) { if(costElement.getBudgetCategory().getBudgetCategoryTypeCode().equalsIgnoreCase(budgetCategoryType)) { filteredObjectCodes.add(costElement); } } return filteredObjectCodes; } protected SortedMap<RateType, List<ScaleTwoDecimal>> calculateExpenseTotals(Budget budget, boolean personnelFlag){ SortedMap<RateType, List<ScaleTwoDecimal>> calculatedExpenseTotals = new TreeMap <RateType, List<ScaleTwoDecimal>> (); List <ScaleTwoDecimal> calculatedDirectCostSummaryTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { calculatedDirectCostSummaryTotals.add(i, ScaleTwoDecimal.ZERO); } String totalsMapKey = null; if(personnelFlag) { totalsMapKey = "personnelCalculatedExpenseSummaryTotals"; } else { totalsMapKey = "nonPersonnelCalculatedExpenseSummaryTotals"; } budget.getBudgetSummaryTotals().put(totalsMapKey, calculatedDirectCostSummaryTotals); for (BudgetPeriod budgetPeriod: budget.getBudgetPeriods()) { for (BudgetLineItem budgetLineItem : budgetPeriod.getBudgetLineItems()) { if((personnelFlag && StringUtils.equals(budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), "P")) || (!personnelFlag && !StringUtils.equals(budgetLineItem.getCostElementBO().getBudgetCategory().getBudgetCategoryTypeCode(), "P")) ) { // get calculated expenses QueryList lineItemCalcAmtQueryList = new QueryList(); lineItemCalcAmtQueryList.addAll(budgetLineItem.getBudgetLineItemCalculatedAmounts()); List <RateType> rateTypes = new ArrayList<RateType>(); for ( Object item : budgetLineItem.getBudgetLineItemCalculatedAmounts()) { BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmount = (BudgetLineItemCalculatedAmount) item; RateType rateType = createRateType(budgetLineItemCalculatedAmount); RateClass rateClass = null; if(rateType != null) { rateType.refreshReferenceObject("rateClass"); rateClass = rateType.getRateClass(); } if (((personnelFlag && rateClass != null && !StringUtils.equals(rateClass.getRateClassTypeCode(), "E")) || !personnelFlag) && !rateTypes.contains(rateType)) { rateTypes.add(rateType); Equals equalsRC = new Equals("rateClassCode", budgetLineItemCalculatedAmount.getRateClassCode()); Equals equalsRT = new Equals("rateTypeCode", budgetLineItemCalculatedAmount.getRateTypeCode()); And RCandRT = new And(equalsRC, equalsRT); ScaleTwoDecimal rateTypeTotalInThisPeriod = lineItemCalcAmtQueryList.sumObjects("calculatedCost", RCandRT); if (!calculatedExpenseTotals.containsKey(rateType)) { List <ScaleTwoDecimal> rateTypePeriodTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { rateTypePeriodTotals.add(i, ScaleTwoDecimal.ZERO); } calculatedExpenseTotals.put(rateType, rateTypePeriodTotals); } calculatedExpenseTotals.get(rateType).set(budgetPeriod.getBudgetPeriod() - 1,((ScaleTwoDecimal)calculatedExpenseTotals.get(rateType).get(budgetPeriod.getBudgetPeriod() - 1)).add(rateTypeTotalInThisPeriod)); if(!StringUtils.equals(rateClass.getRateClassTypeCode(), RateClassType.OVERHEAD.getRateClassType())) { budget.getBudgetSummaryTotals().get(totalsMapKey).set(budgetPeriod.getBudgetPeriod() - 1, ((ScaleTwoDecimal) (budget.getBudgetSummaryTotals().get(totalsMapKey).get(budgetPeriod.getBudgetPeriod() - 1))).add(rateTypeTotalInThisPeriod)); } budgetPeriod.setExpenseTotal(budgetPeriod.getExpenseTotal().add(rateTypeTotalInThisPeriod)); } } } } } return calculatedExpenseTotals; } protected RateType createRateType(BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmount) { RateType rateType = new RateType(); rateType.setRateClassCode(budgetLineItemCalculatedAmount.getRateClassCode()); rateType.setRateTypeCode(budgetLineItemCalculatedAmount.getRateTypeCode()); rateType.setDescription(budgetLineItemCalculatedAmount.getRateTypeDescription()); rateType.setRateClass(budgetLineItemCalculatedAmount.getRateClass()); return rateType; } @SuppressWarnings("unchecked") protected void calculateBudgetTotals(Budget budget){ // do we need to cache the totals ? SortedMap<CostElement, List<ScaleTwoDecimal>> objectCodeTotals = new TreeMap <CostElement, List<ScaleTwoDecimal>> (); SortedMap<RateType, List<ScaleTwoDecimal>> calculatedExpenseTotals = new TreeMap <RateType, List<ScaleTwoDecimal>> (); for (BudgetPeriod budgetPeriod: budget.getBudgetPeriods()) { List <CostElement> objectCodes = new ArrayList<CostElement>(); QueryList lineItemQueryList = new QueryList(); lineItemQueryList.addAll(budgetPeriod.getBudgetLineItems()); budgetPeriod.setExpenseTotal(ScaleTwoDecimal.ZERO); // probably need to add '0' to the period that has no such object code or ratetype ? for (BudgetLineItem budgetLineItem : budgetPeriod.getBudgetLineItems()) { if (budgetLineItem.getCostElementBO() == null) { budgetLineItem.refreshReferenceObject("costElementBO"); } CostElement costElement = budgetLineItem.getCostElementBO(); if (!objectCodes.contains(costElement)) { objectCodes.add(costElement); Equals equalsCostElement = new Equals("costElement", budgetLineItem.getCostElement()); ScaleTwoDecimal objectCodeTotalInThisPeriod = lineItemQueryList.sumObjects("lineItemCost", equalsCostElement); if (!objectCodeTotals.containsKey(costElement)) { // set up for all periods and put into map List <ScaleTwoDecimal> periodTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { periodTotals.add(i, ScaleTwoDecimal.ZERO); } objectCodeTotals.put(costElement, periodTotals); } objectCodeTotals.get(costElement).set(budgetPeriod.getBudgetPeriod() - 1, objectCodeTotalInThisPeriod); budgetPeriod.setExpenseTotal(budgetPeriod.getExpenseTotal().add(objectCodeTotalInThisPeriod)); } // get calculated expenses QueryList lineItemCalcAmtQueryList = new QueryList(); lineItemCalcAmtQueryList.addAll(budgetLineItem.getBudgetLineItemCalculatedAmounts()); List <RateType> rateTypes = new ArrayList<RateType>(); for ( Object item : budgetLineItem.getBudgetLineItemCalculatedAmounts()) { BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmount = (BudgetLineItemCalculatedAmount) item; RateType rateType = createRateType(budgetLineItemCalculatedAmount); if (!rateTypes.contains(rateType)) { rateTypes.add(rateType); Equals equalsRC = new Equals("rateClassCode", budgetLineItemCalculatedAmount.getRateClassCode()); Equals equalsRT = new Equals("rateTypeCode", budgetLineItemCalculatedAmount.getRateTypeCode()); And RCandRT = new And(equalsRC, equalsRT); ScaleTwoDecimal rateTypeTotalInThisPeriod = lineItemCalcAmtQueryList.sumObjects("calculatedCost", RCandRT); if (!calculatedExpenseTotals.containsKey(rateType)) { List <ScaleTwoDecimal> rateTypePeriodTotals = new ArrayList<ScaleTwoDecimal>(); for (int i = 0; i < budget.getBudgetPeriods().size(); i++) { rateTypePeriodTotals.add(i, ScaleTwoDecimal.ZERO); } calculatedExpenseTotals.put(rateType, rateTypePeriodTotals); } calculatedExpenseTotals.get(rateType).set(budgetPeriod.getBudgetPeriod() - 1,((ScaleTwoDecimal)calculatedExpenseTotals.get(rateType).get(budgetPeriod.getBudgetPeriod() - 1)).add(rateTypeTotalInThisPeriod)); budgetPeriod.setExpenseTotal(budgetPeriod.getExpenseTotal().add(rateTypeTotalInThisPeriod)); } } } } budget.setObjectCodeTotals(objectCodeTotals); budget.setCalculatedExpenseTotals(calculatedExpenseTotals); } @Override public void syncToPeriodCostLimit(Budget budget, BudgetPeriod budgetPeriod, BudgetLineItem budgetLineItem) { BudgetPeriodCalculator periodCalculator = new BudgetPeriodCalculator(); periodCalculator.syncToPeriodCostLimit(budget, budgetPeriod, budgetLineItem); List<String> errors = periodCalculator.getErrorMessages(); MessageMap errorMap = GlobalVariables.getMessageMap(); if(!errors.isEmpty()){ for (String error : errors) { errorMap.putError("document.budgetPeriod[" + (budgetPeriod.getBudgetPeriod() - 1) + "].budgetLineItem["+ (budgetLineItem.getLineItemNumber() - 1) +"].lineItemCost", error); } } } @Override public void syncToPeriodDirectCostLimit(Budget budget, BudgetPeriod budgetPeriod, BudgetLineItem budgetLineItem) { BudgetPeriodCalculator periodCalculator = new BudgetPeriodCalculator(); periodCalculator.syncToPeriodDirectCostLimit(budget, budgetPeriod, budgetLineItem); List<String> errors = periodCalculator.getErrorMessages(); MessageMap errorMap = GlobalVariables.getMessageMap(); if(!errors.isEmpty()){ for (String error : errors) { errorMap.putError("document.budgetPeriod[" + (budgetPeriod.getBudgetPeriod() - 1) + "].budgetLineItem["+ (budgetLineItem.getLineItemNumber() - 1) +"].lineItemCost", error); } } } @Override public void applyToLaterPeriods(Budget budget, BudgetPeriod budgetPeriod, BudgetLineItem budgetLineItem) { BudgetPeriodCalculator periodCalculator = new BudgetPeriodCalculator(); periodCalculator.applyToLaterPeriods(budget, budgetPeriod, budgetLineItem); List<String> errors = periodCalculator.getErrorMessages(); if(!errors.isEmpty()){ MessageMap errorMap = GlobalVariables.getMessageMap(); for (String error : errors) { errorMap.putError("document.budgetPeriod[" + (budgetPeriod.getBudgetPeriod() - 1) + "].budgetLineItem["+ (budgetLineItem.getLineItemNumber() - 1) +"].costElement",error); } } } public BusinessObjectService getBusinessObjectService() { return businessObjectService; } public void setBusinessObjectService(BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } /** * Gets the budgetDistributionService attribute. * @return Returns the budgetDistributionService. */ public BudgetDistributionService getBudgetDistributionService() { return this.budgetDistributionService; } /** * Sets the budgetDistributionService attribute value. * @param service The budgetDistributionService to set. */ public void setBudgetDistributionService(BudgetDistributionService service) { this.budgetDistributionService = service; } public ParameterService getParameterService() { return parameterService; } public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } @Override public void rePopulateCalculatedAmount(Budget budget, BudgetLineItem budgetLineItem) { budgetLineItem.getBudgetCalculatedAmounts().clear(); new LineItemCalculator(budget,budgetLineItem).setCalculatedAmounts(budget, budgetLineItem); } @Override public void rePopulateCalculatedAmount(Budget budget, BudgetPersonnelDetails newBudgetPersonnelDetails) { newBudgetPersonnelDetails.getBudgetCalculatedAmounts().clear(); new PersonnelLineItemCalculator(budget,newBudgetPersonnelDetails).setCalculatedAmounts(budget, newBudgetPersonnelDetails); } @Override public void updatePersonnelBudgetRate(BudgetLineItem budgetLineItem){ int j = 0; for(BudgetPersonnelDetails budgetPersonnelDetails: budgetLineItem.getBudgetPersonnelDetailsList()){ if(budgetPersonnelDetails.getCostElement()==null){ budgetPersonnelDetails.setCostElement(budgetLineItem.getCostElement()); budgetPersonnelDetails.setCostElementBO(budgetLineItem.getCostElementBO()); } j=0; for(BudgetPersonnelCalculatedAmount budgetPersonnelCalculatedAmount:budgetPersonnelDetails.getBudgetPersonnelCalculatedAmounts()){ Boolean updatedApplyRateFlag = null; for (BudgetLineItemCalculatedAmount budgetLineItemCalculatedAmout : budgetLineItem.getBudgetLineItemCalculatedAmounts()) { if(budgetLineItemCalculatedAmout.getRateClassCode().equalsIgnoreCase(budgetPersonnelCalculatedAmount.getRateClassCode()) && budgetLineItemCalculatedAmout.getRateTypeCode().equalsIgnoreCase(budgetPersonnelCalculatedAmount.getRateTypeCode())) { updatedApplyRateFlag = budgetLineItemCalculatedAmout.getApplyRateFlag(); } } budgetPersonnelCalculatedAmount.setApplyRateFlag(updatedApplyRateFlag); j++; } } } @Override public BudgetForm getBudgetFormFromGlobalVariables() { BudgetForm budgetForm = null; KualiForm form = KNSGlobalVariables.getKualiForm(); if (form != null && form instanceof BudgetForm) { budgetForm = (BudgetForm)form; } return budgetForm; } protected void addBudgetLimits(List<ScaleTwoDecimal> budgetLimits, AwardBudgetLineItemCalculatedAmountExt awardCalcAmt, boolean isPrevBudget) { if (isPrevBudget) { budgetLimits.set(1, budgetLimits.get(1).add(awardCalcAmt.getCalculatedCost())); } else { budgetLimits.set(0, budgetLimits.get(0).add(awardCalcAmt.getCalculatedCost())); } budgetLimits.set(2, budgetLimits.get(2).add(awardCalcAmt.getCalculatedCost())); } }
apache-2.0
Siberis/AtomisProtocol
src/main/java/core/service/NodeService.java
6142
package core.service; import com.google.common.collect.Sets; import core.broker.MessageBrokerWrapper; import core.documentdb.DocumentDBWrapper; import core.entity.NodeHierarchy; import core.entity.NodeStructure; import core.graphdb.GraphDBWrapper; import core.heartbeat.HeartbeatReq; import core.heartbeat.HeartbeatRes; import core.message.*; import java.lang.reflect.ParameterizedType; import java.util.Map; import java.util.Set; /** * Created by siberis on 11/8/2016. */ public abstract class NodeService<D extends NodeStructure, G extends NodeHierarchy> implements Service { private Map<Long, String> extensionCache; private Set<Long> enableMessages = Sets.newHashSet(); private Map<Long, NewExtension> extensionServices; private Class<D> documentClass; private Class<G> graphClass; public NodeService(Map<Long, String> extensionCache, Map<Long, NewExtension> extensionServices) { this.extensionCache = extensionCache; this.extensionServices = extensionServices; documentClass = (Class<D>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; graphClass = (Class<G>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[1]; } public NodeService(Map<Long, String> extensionCache, Map<Long, NewExtension> extensionServices, Class<D> documentClass, Class<G> graphClass) { this.extensionCache = extensionCache; this.extensionServices = extensionServices; this.documentClass = documentClass; this.graphClass = graphClass; } @Override public void handleException(AtomisException e, String targetTopic, int stateId) { System.out.println("Error occurs: " + e.getMessage()); MessageBrokerWrapper.sendResponse(this, new ProcessingException<>(e, targetTopic), targetTopic, stateId); } public Map<Long, String> getExtensionCache() { return extensionCache; } public void setExtensionCache(Map<Long, String> extensionCache) { this.extensionCache = extensionCache; } public Map<Long, NewExtension> getExtensionServices() { return extensionServices; } public void setExtensionServices(Map<Long, NewExtension> extensionServices) { this.extensionServices = extensionServices; } public <T extends MessagePayload> boolean receiveNodeMessage(T payload, String targetTopic, int stateId) { if (payload instanceof HeartbeatReq) { MessageBrokerWrapper.sendMessage(new HeartbeatRes(getServiceId())); } else if (payload instanceof UnavailableService) { unavailableService((UnavailableService) payload); } else if (payload instanceof AvailableService) { availableService((AvailableService) payload); } else if (payload instanceof NewExtension) { addNewExtension((NewExtension) payload); } else if (payload instanceof NewExtensionForNode) { addExtensionType((NewExtensionForNode) payload, targetTopic, stateId); } else if (payload instanceof EnableMessages) { enableMessages((EnableMessages) payload); } else { return !enableMessages.contains(payload.getTypeId()); } return true; } private <T extends MessagePayload> void enableMessages(EnableMessages msg) { if (msg.getServiceOnId() != null && msg.getServiceOnId().equals(getServiceId())) { enableMessages.addAll(msg.getMessages()); MessageBrokerWrapper.startFull(); } else if (msg.getServiceOffId() != null && msg.getServiceOffId().equals(getServiceId())) { enableMessages.removeAll(msg.getMessages()); MessageBrokerWrapper.startFull(); } } @Override public void receiveUnknownMessage(Long typeId, String rawPayload, String targetTopic, int stateId) { System.out.println("Unknown message received : (id:" + typeId + ",value:" + rawPayload + ")"); } private void availableService(AvailableService payload) { NewExtension ext = extensionServices.get(payload.getServiceId()); if (ext != null) addNewExtension(ext); } protected void addExtensionType(NewExtensionForNode payload, String targetTopic, int stateId) { D task = DocumentDBWrapper.get(documentClass, payload.getNodeId()); task.getExtensions().add(payload.getExtType()); DocumentDBWrapper.save(task); } protected void addNewExtension(NewExtension extension) { extensionCache.put(extension.getType(), extension.getTopic()); extensionServices.put(extension.getServiceId(), extension); } protected abstract void processServiceUnavailable(Long extensionType, Long serviceId); protected void unavailableService(UnavailableService serviceUnavailable) { NewExtension entry = getExtensionServices().get(serviceUnavailable.getServiceId()); if (entry != null) { getExtensionCache().remove(entry.getType()); processServiceUnavailable(entry.getType(), entry.getServiceId()); } } /** * Possible problems with transactions 3x save on different databases */ protected D createNode(D nodeData, G nodeHierarchy, String parentKey) { D node = DocumentDBWrapper.save(nodeData); G hierarchy = nodeHierarchy; hierarchy.setStructureId(node.getId().toHexString()); if (parentKey != null) { D parent = DocumentDBWrapper.get(documentClass, parentKey); if (parent != null) { G parentNode = GraphDBWrapper.get(graphClass, parent.getHierarchyId()); if (hierarchy.getParents() != null) { hierarchy.getParents().add(parentNode); } else { hierarchy.setParents(Sets.newHashSet(parentNode)); } } } hierarchy = GraphDBWrapper.save(hierarchy); node.setHierarchyId(hierarchy.getId()); node = DocumentDBWrapper.save(node); return node; } }
apache-2.0
j-coll/java-common-libs
commons-datastore/commons-datastore-core/src/main/java/org/opencb/commons/datastore/core/Query.java
2556
package org.opencb.commons.datastore.core; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; /** * @author Jacobo Coll &lt;jacobo167@gmail.com&gt; */ public class Query extends ObjectMap { public Query() { } public Query(int size) { super(size); } public Query(String key, Object value) { super(key, value); } public Query(Map<String, Object> map) { super(map); } public Query(String json) { super(json); } public <E extends Enum<E> & QueryParam> void validate(Class<E> enumType) throws EnumConstantNotPresentException, NumberFormatException { Objects.requireNonNull(enumType); Map<String, E> enumFields = Arrays.asList(enumType.getEnumConstants()).stream().collect( Collectors.toMap(queryParam -> queryParam.key(), Function.<E>identity())); for (Map.Entry<String, Object> entry : entrySet()) { if (!enumFields.containsKey(entry.getKey())) { throw new EnumConstantNotPresentException(enumType, entry.getKey()); } else { QueryParam queryParam = enumFields.get(entry.getKey()); switch (queryParam.type()) { case TEXT: put(queryParam.key(), getString(queryParam.key())); break; case TEXT_ARRAY: put(queryParam.key(), getAsStringList(queryParam.key())); break; case INTEGER: put(queryParam.key(), getLong(queryParam.key())); break; case INTEGER_ARRAY: put(queryParam.key(), getAsLongList(queryParam.key())); break; case DECIMAL: put(queryParam.key(), getDouble(queryParam.key())); break; case DECIMAL_ARRAY: put(queryParam.key(), getAsDoubleList(queryParam.key())); break; case BOOLEAN: put(queryParam.key(), getBoolean(queryParam.key())); break; default: break; } } } } @Override public Query append(String key, Object value) { return (Query) super.append(key, value); } }
apache-2.0
bigswitch/BeaconMirror
net.beaconcontroller.web/src/main/java/net/beaconcontroller/web/view/layout/Layout.java
943
package net.beaconcontroller.web.view.layout; import java.util.LinkedHashMap; import java.util.Map; import net.beaconcontroller.web.view.Renderable; import net.beaconcontroller.web.view.section.Section; /** * * * @author David Erickson (derickso@stanford.edu) */ public abstract class Layout implements Renderable { protected static String RESOURCE_PATH = "/WEB-INF/jsp/view/layout/"; protected Map<Section, Object> sections = new LinkedHashMap<Section, Object>(); /** * @return the sections */ public Map<Section, Object> getSections() { return sections; } /** * @param sections the sections to set */ public void setSections(Map<Section, Object> sections) { this.sections = sections; } /** * * @param section * @param hint */ public void addSection(Section section, Object hint) { this.sections.put(section, hint); } }
apache-2.0
consulo/consulo
modules/web/web-ui-impl-client/src/main/java/consulo/web/gwt/client/ui/GwtIntBoxImplConnector.java
1464
/* * Copyright 2013-2020 consulo.io * * 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 consulo.web.gwt.client.ui; import com.vaadin.client.StyleConstants; import com.vaadin.client.communication.StateChangeEvent; import com.vaadin.client.ui.AbstractComponentConnector; import com.vaadin.shared.ui.Connect; /** * @author VISTALL * @since 2020-05-10 */ @Connect(canonicalName = "consulo.ui.web.internal.WebIntBoxImpl.Vaadin") public class GwtIntBoxImplConnector extends AbstractComponentConnector { @Override protected void updateWidgetStyleNames() { super.updateWidgetStyleNames(); setWidgetStyleName(StyleConstants.UI_WIDGET, false); } @Override public void onStateChanged(StateChangeEvent stateChangeEvent) { super.onStateChanged(stateChangeEvent); getWidget().setValue(Integer.parseInt(getState().caption)); } @Override public GwtIntBoxImpl getWidget() { return (GwtIntBoxImpl)super.getWidget(); } }
apache-2.0
rhtconsulting/fuse-quickstarts
karaf/jpa/src/main/java/org/redhat/consulting/fusequickstarts/karaf/jpa/model/Person.java
828
package org.redhat.consulting.fusequickstarts.karaf.jpa.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Person { @Id @GeneratedValue private long id; private String name; public Person(){ } public Person(String pName){ this.name = pName; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static String generateName(){ return "SomeName"; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + "]"; } }
apache-2.0
hortonworks/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/reactor/api/event/kerberos/KeytabConfigurationFailed.java
304
package com.sequenceiq.cloudbreak.reactor.api.event.kerberos; import com.sequenceiq.cloudbreak.reactor.api.event.StackFailureEvent; public class KeytabConfigurationFailed extends StackFailureEvent { public KeytabConfigurationFailed(Long stackId, Exception ex) { super(stackId, ex); } }
apache-2.0
open-erp-systems/erp-backend
erp-library/src/main/java/com.jukusoft/erp/lib/cache/impl/LocalMemoryCache.java
2439
package com.jukusoft.erp.lib.cache.impl; import com.jukusoft.erp.lib.cache.ICache; import com.jukusoft.erp.lib.logging.ILogging; import io.vertx.core.json.JsonObject; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class LocalMemoryCache implements ICache { //map with all cache entries protected Map<String,JsonObject> cacheMap = new ConcurrentHashMap<>(); //map with last access date (unix timestamp) protected Map<String,Long> accessMap = new ConcurrentHashMap<>(); //time to live for cache objects (30 seconds) protected long TTL = 30 * 1000; public LocalMemoryCache (ILogging logger) { // } @Override public void put(String key, JsonObject data) { if (data == null) { throw new NullPointerException("json object cannot be null."); } this.cacheMap.put(key, data); //update last access timestamp this.accessMap.put(key, System.currentTimeMillis()); } @Override public void remove(String key) { this.cacheMap.remove(key); this.accessMap.remove(key); } @Override public void removeAll() { this.cacheMap.clear(); this.accessMap.clear(); } @Override public boolean contains(String key) { return this.cacheMap.get(key) != null; } @Override public JsonObject get(String key) { JsonObject value = this.cacheMap.get(key); if (value != null) { this.accessMap.put(key, System.currentTimeMillis()); } return value; } @Override public void cleanUp() { //get current unix timestamp long now = System.currentTimeMillis(); //list with all keys to remove List<String> removeKeys = new ArrayList<>(); //iterate through all entries for (Map.Entry<String,Long> entry : this.accessMap.entrySet()) { //check, if cache entry is outdated if (entry.getValue() + TTL < now) { //add entry to temporary list to avoid ConcurrentModificationException removeKeys.add(entry.getKey()); } } //iterate through list with all entries, which should be removed from cache for (String key : removeKeys) { //remove entry from cache this.remove(key); } } }
apache-2.0
OSEHRA/komet
citation-editor-plugin/src/main/java/schemas/docbook/Listitem.java
29375
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.01.11 at 02:39:34 PM EST // package schemas.docbook; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded"> * &lt;element ref="{http://docbook.org/ns/docbook}itemizedlist"/> * &lt;element ref="{http://docbook.org/ns/docbook}orderedlist"/> * &lt;element ref="{http://docbook.org/ns/docbook}procedure"/> * &lt;element ref="{http://docbook.org/ns/docbook}simplelist"/> * &lt;element ref="{http://docbook.org/ns/docbook}variablelist"/> * &lt;element ref="{http://docbook.org/ns/docbook}segmentedlist"/> * &lt;element ref="{http://docbook.org/ns/docbook}glosslist"/> * &lt;element ref="{http://docbook.org/ns/docbook}bibliolist"/> * &lt;element ref="{http://docbook.org/ns/docbook}calloutlist"/> * &lt;element ref="{http://docbook.org/ns/docbook}qandaset"/> * &lt;element ref="{http://docbook.org/ns/docbook}example"/> * &lt;element ref="{http://docbook.org/ns/docbook}figure"/> * &lt;element ref="{http://docbook.org/ns/docbook}table"/> * &lt;element ref="{http://docbook.org/ns/docbook}equation"/> * &lt;element ref="{http://docbook.org/ns/docbook}informalexample"/> * &lt;element ref="{http://docbook.org/ns/docbook}informalfigure"/> * &lt;element ref="{http://docbook.org/ns/docbook}informaltable"/> * &lt;element ref="{http://docbook.org/ns/docbook}informalequation"/> * &lt;element ref="{http://docbook.org/ns/docbook}sidebar"/> * &lt;element ref="{http://docbook.org/ns/docbook}blockquote"/> * &lt;element ref="{http://docbook.org/ns/docbook}address"/> * &lt;element ref="{http://docbook.org/ns/docbook}epigraph"/> * &lt;element ref="{http://docbook.org/ns/docbook}mediaobject"/> * &lt;element ref="{http://docbook.org/ns/docbook}screenshot"/> * &lt;element ref="{http://docbook.org/ns/docbook}task"/> * &lt;element ref="{http://docbook.org/ns/docbook}productionset"/> * &lt;element ref="{http://docbook.org/ns/docbook}constraintdef"/> * &lt;element ref="{http://docbook.org/ns/docbook}msgset"/> * &lt;element ref="{http://docbook.org/ns/docbook}screen"/> * &lt;element ref="{http://docbook.org/ns/docbook}literallayout"/> * &lt;element ref="{http://docbook.org/ns/docbook}programlistingco"/> * &lt;element ref="{http://docbook.org/ns/docbook}screenco"/> * &lt;element ref="{http://docbook.org/ns/docbook}programlisting"/> * &lt;element ref="{http://docbook.org/ns/docbook}synopsis"/> * &lt;element ref="{http://docbook.org/ns/docbook}bridgehead"/> * &lt;element ref="{http://docbook.org/ns/docbook}remark"/> * &lt;element ref="{http://docbook.org/ns/docbook}revhistory"/> * &lt;element ref="{http://docbook.org/ns/docbook}indexterm"/> * &lt;element ref="{http://docbook.org/ns/docbook}funcsynopsis"/> * &lt;element ref="{http://docbook.org/ns/docbook}classsynopsis"/> * &lt;element ref="{http://docbook.org/ns/docbook}methodsynopsis"/> * &lt;element ref="{http://docbook.org/ns/docbook}constructorsynopsis"/> * &lt;element ref="{http://docbook.org/ns/docbook}destructorsynopsis"/> * &lt;element ref="{http://docbook.org/ns/docbook}fieldsynopsis"/> * &lt;element ref="{http://docbook.org/ns/docbook}cmdsynopsis"/> * &lt;element ref="{http://docbook.org/ns/docbook}caution"/> * &lt;element ref="{http://docbook.org/ns/docbook}important"/> * &lt;element ref="{http://docbook.org/ns/docbook}note"/> * &lt;element ref="{http://docbook.org/ns/docbook}tip"/> * &lt;element ref="{http://docbook.org/ns/docbook}warning"/> * &lt;element ref="{http://docbook.org/ns/docbook}anchor"/> * &lt;element ref="{http://docbook.org/ns/docbook}para"/> * &lt;element ref="{http://docbook.org/ns/docbook}formalpara"/> * &lt;element ref="{http://docbook.org/ns/docbook}simpara"/> * &lt;element ref="{http://docbook.org/ns/docbook}annotation"/> * &lt;/choice> * &lt;attGroup ref="{http://docbook.org/ns/docbook}db.common.linking.attributes"/> * &lt;attGroup ref="{http://docbook.org/ns/docbook}db.common.attributes"/> * &lt;attribute name="role" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> * &lt;attribute name="override" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "itemizedlistsAndOrderedlistsAndProcedures" }) @XmlRootElement(name = "listitem") public class Listitem { @XmlElements({ @XmlElement(name = "itemizedlist", type = Itemizedlist.class), @XmlElement(name = "orderedlist", type = Orderedlist.class), @XmlElement(name = "procedure", type = Procedure.class), @XmlElement(name = "simplelist", type = Simplelist.class), @XmlElement(name = "variablelist", type = Variablelist.class), @XmlElement(name = "segmentedlist", type = Segmentedlist.class), @XmlElement(name = "glosslist", type = Glosslist.class), @XmlElement(name = "bibliolist", type = Bibliolist.class), @XmlElement(name = "calloutlist", type = Calloutlist.class), @XmlElement(name = "qandaset", type = Qandaset.class), @XmlElement(name = "example", type = Example.class), @XmlElement(name = "figure", type = Figure.class), @XmlElement(name = "table", type = Table.class), @XmlElement(name = "equation", type = Equation.class), @XmlElement(name = "informalexample", type = Informalexample.class), @XmlElement(name = "informalfigure", type = Informalfigure.class), @XmlElement(name = "informaltable", type = Informaltable.class), @XmlElement(name = "informalequation", type = Informalequation.class), @XmlElement(name = "sidebar", type = Sidebar.class), @XmlElement(name = "blockquote", type = Blockquote.class), @XmlElement(name = "address", type = Address.class), @XmlElement(name = "epigraph", type = Epigraph.class), @XmlElement(name = "mediaobject", type = Mediaobject.class), @XmlElement(name = "screenshot", type = Screenshot.class), @XmlElement(name = "task", type = Task.class), @XmlElement(name = "productionset", type = Productionset.class), @XmlElement(name = "constraintdef", type = Constraintdef.class), @XmlElement(name = "msgset", type = Msgset.class), @XmlElement(name = "screen", type = Screen.class), @XmlElement(name = "literallayout", type = Literallayout.class), @XmlElement(name = "programlistingco", type = Programlistingco.class), @XmlElement(name = "screenco", type = Screenco.class), @XmlElement(name = "programlisting", type = Programlisting.class), @XmlElement(name = "synopsis", type = Synopsis.class), @XmlElement(name = "bridgehead", type = Bridgehead.class), @XmlElement(name = "remark", type = Remark.class), @XmlElement(name = "revhistory", type = Revhistory.class), @XmlElement(name = "indexterm", type = Indexterm.class), @XmlElement(name = "funcsynopsis", type = Funcsynopsis.class), @XmlElement(name = "classsynopsis", type = Classsynopsis.class), @XmlElement(name = "methodsynopsis", type = Methodsynopsis.class), @XmlElement(name = "constructorsynopsis", type = Constructorsynopsis.class), @XmlElement(name = "destructorsynopsis", type = Destructorsynopsis.class), @XmlElement(name = "fieldsynopsis", type = Fieldsynopsis.class), @XmlElement(name = "cmdsynopsis", type = Cmdsynopsis.class), @XmlElement(name = "caution", type = Caution.class), @XmlElement(name = "important", type = Important.class), @XmlElement(name = "note", type = Note.class), @XmlElement(name = "tip", type = Tip.class), @XmlElement(name = "warning", type = Warning.class), @XmlElement(name = "anchor", type = Anchor.class), @XmlElement(name = "para", type = Para.class), @XmlElement(name = "formalpara", type = Formalpara.class), @XmlElement(name = "simpara", type = Simpara.class), @XmlElement(name = "annotation", type = Annotation.class) }) protected List<Object> itemizedlistsAndOrderedlistsAndProcedures; @XmlAttribute(name = "role") @XmlSchemaType(name = "anySimpleType") protected String role; @XmlAttribute(name = "override") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String override; @XmlAttribute(name = "linkend") @XmlIDREF @XmlSchemaType(name = "IDREF") protected Object linkend; @XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String href; @XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String xlinkType; @XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String xlinkRole; @XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String arcrole; @XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String xlinkTitle; @XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String show; @XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String actuate; @XmlAttribute(name = "id", namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute(name = "version") @XmlSchemaType(name = "anySimpleType") protected String commonVersion; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anySimpleType") protected String xmlLang; @XmlAttribute(name = "base", namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anySimpleType") protected String base; @XmlAttribute(name = "remap") @XmlSchemaType(name = "anySimpleType") protected String remap; @XmlAttribute(name = "xreflabel") @XmlSchemaType(name = "anySimpleType") protected String xreflabel; @XmlAttribute(name = "revisionflag") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String revisionflag; @XmlAttribute(name = "dir") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String dir; @XmlAttribute(name = "arch") @XmlSchemaType(name = "anySimpleType") protected String arch; @XmlAttribute(name = "audience") @XmlSchemaType(name = "anySimpleType") protected String audience; @XmlAttribute(name = "condition") @XmlSchemaType(name = "anySimpleType") protected String condition; @XmlAttribute(name = "conformance") @XmlSchemaType(name = "anySimpleType") protected String conformance; @XmlAttribute(name = "os") @XmlSchemaType(name = "anySimpleType") protected String os; @XmlAttribute(name = "revision") @XmlSchemaType(name = "anySimpleType") protected String commonRevision; @XmlAttribute(name = "security") @XmlSchemaType(name = "anySimpleType") protected String security; @XmlAttribute(name = "userlevel") @XmlSchemaType(name = "anySimpleType") protected String userlevel; @XmlAttribute(name = "vendor") @XmlSchemaType(name = "anySimpleType") protected String vendor; @XmlAttribute(name = "wordsize") @XmlSchemaType(name = "anySimpleType") protected String wordsize; @XmlAttribute(name = "annotations") @XmlSchemaType(name = "anySimpleType") protected String annotations; /** * Gets the value of the itemizedlistsAndOrderedlistsAndProcedures property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the itemizedlistsAndOrderedlistsAndProcedures property. * * <p> * For example, to add a new item, do as follows: * <pre> * getItemizedlistsAndOrderedlistsAndProcedures().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Itemizedlist } * {@link Orderedlist } * {@link Procedure } * {@link Simplelist } * {@link Variablelist } * {@link Segmentedlist } * {@link Glosslist } * {@link Bibliolist } * {@link Calloutlist } * {@link Qandaset } * {@link Example } * {@link Figure } * {@link Table } * {@link Equation } * {@link Informalexample } * {@link Informalfigure } * {@link Informaltable } * {@link Informalequation } * {@link Sidebar } * {@link Blockquote } * {@link Address } * {@link Epigraph } * {@link Mediaobject } * {@link Screenshot } * {@link Task } * {@link Productionset } * {@link Constraintdef } * {@link Msgset } * {@link Screen } * {@link Literallayout } * {@link Programlistingco } * {@link Screenco } * {@link Programlisting } * {@link Synopsis } * {@link Bridgehead } * {@link Remark } * {@link Revhistory } * {@link Indexterm } * {@link Funcsynopsis } * {@link Classsynopsis } * {@link Methodsynopsis } * {@link Constructorsynopsis } * {@link Destructorsynopsis } * {@link Fieldsynopsis } * {@link Cmdsynopsis } * {@link Caution } * {@link Important } * {@link Note } * {@link Tip } * {@link Warning } * {@link Anchor } * {@link Para } * {@link Formalpara } * {@link Simpara } * {@link Annotation } * * */ public List<Object> getItemizedlistsAndOrderedlistsAndProcedures() { if (itemizedlistsAndOrderedlistsAndProcedures == null) { itemizedlistsAndOrderedlistsAndProcedures = new ArrayList<Object>(); } return this.itemizedlistsAndOrderedlistsAndProcedures; } /** * Gets the value of the role property. * * @return * possible object is * {@link String } * */ public String getRole() { return role; } /** * Sets the value of the role property. * * @param value * allowed object is * {@link String } * */ public void setRole(String value) { this.role = value; } /** * Gets the value of the override property. * * @return * possible object is * {@link String } * */ public String getOverride() { return override; } /** * Sets the value of the override property. * * @param value * allowed object is * {@link String } * */ public void setOverride(String value) { this.override = value; } /** * Gets the value of the linkend property. * * @return * possible object is * {@link Object } * */ public Object getLinkend() { return linkend; } /** * Sets the value of the linkend property. * * @param value * allowed object is * {@link Object } * */ public void setLinkend(Object value) { this.linkend = value; } /** * Gets the value of the href property. * * @return * possible object is * {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is * {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the xlinkType property. * * @return * possible object is * {@link String } * */ public String getXlinkType() { return xlinkType; } /** * Sets the value of the xlinkType property. * * @param value * allowed object is * {@link String } * */ public void setXlinkType(String value) { this.xlinkType = value; } /** * Gets the value of the xlinkRole property. * * @return * possible object is * {@link String } * */ public String getXlinkRole() { return xlinkRole; } /** * Sets the value of the xlinkRole property. * * @param value * allowed object is * {@link String } * */ public void setXlinkRole(String value) { this.xlinkRole = value; } /** * Gets the value of the arcrole property. * * @return * possible object is * {@link String } * */ public String getArcrole() { return arcrole; } /** * Sets the value of the arcrole property. * * @param value * allowed object is * {@link String } * */ public void setArcrole(String value) { this.arcrole = value; } /** * Gets the value of the xlinkTitle property. * * @return * possible object is * {@link String } * */ public String getXlinkTitle() { return xlinkTitle; } /** * Sets the value of the xlinkTitle property. * * @param value * allowed object is * {@link String } * */ public void setXlinkTitle(String value) { this.xlinkTitle = value; } /** * Gets the value of the show property. * * @return * possible object is * {@link String } * */ public String getShow() { return show; } /** * Sets the value of the show property. * * @param value * allowed object is * {@link String } * */ public void setShow(String value) { this.show = value; } /** * Gets the value of the actuate property. * * @return * possible object is * {@link String } * */ public String getActuate() { return actuate; } /** * Sets the value of the actuate property. * * @param value * allowed object is * {@link String } * */ public void setActuate(String value) { this.actuate = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the commonVersion property. * * @return * possible object is * {@link String } * */ public String getCommonVersion() { return commonVersion; } /** * Sets the value of the commonVersion property. * * @param value * allowed object is * {@link String } * */ public void setCommonVersion(String value) { this.commonVersion = value; } /** * Gets the value of the xmlLang property. * * @return * possible object is * {@link String } * */ public String getXmlLang() { return xmlLang; } /** * Sets the value of the xmlLang property. * * @param value * allowed object is * {@link String } * */ public void setXmlLang(String value) { this.xmlLang = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the remap property. * * @return * possible object is * {@link String } * */ public String getRemap() { return remap; } /** * Sets the value of the remap property. * * @param value * allowed object is * {@link String } * */ public void setRemap(String value) { this.remap = value; } /** * Gets the value of the xreflabel property. * * @return * possible object is * {@link String } * */ public String getXreflabel() { return xreflabel; } /** * Sets the value of the xreflabel property. * * @param value * allowed object is * {@link String } * */ public void setXreflabel(String value) { this.xreflabel = value; } /** * Gets the value of the revisionflag property. * * @return * possible object is * {@link String } * */ public String getRevisionflag() { return revisionflag; } /** * Sets the value of the revisionflag property. * * @param value * allowed object is * {@link String } * */ public void setRevisionflag(String value) { this.revisionflag = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link String } * */ public String getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link String } * */ public void setDir(String value) { this.dir = value; } /** * Gets the value of the arch property. * * @return * possible object is * {@link String } * */ public String getArch() { return arch; } /** * Sets the value of the arch property. * * @param value * allowed object is * {@link String } * */ public void setArch(String value) { this.arch = value; } /** * Gets the value of the audience property. * * @return * possible object is * {@link String } * */ public String getAudience() { return audience; } /** * Sets the value of the audience property. * * @param value * allowed object is * {@link String } * */ public void setAudience(String value) { this.audience = value; } /** * Gets the value of the condition property. * * @return * possible object is * {@link String } * */ public String getCondition() { return condition; } /** * Sets the value of the condition property. * * @param value * allowed object is * {@link String } * */ public void setCondition(String value) { this.condition = value; } /** * Gets the value of the conformance property. * * @return * possible object is * {@link String } * */ public String getConformance() { return conformance; } /** * Sets the value of the conformance property. * * @param value * allowed object is * {@link String } * */ public void setConformance(String value) { this.conformance = value; } /** * Gets the value of the os property. * * @return * possible object is * {@link String } * */ public String getOs() { return os; } /** * Sets the value of the os property. * * @param value * allowed object is * {@link String } * */ public void setOs(String value) { this.os = value; } /** * Gets the value of the commonRevision property. * * @return * possible object is * {@link String } * */ public String getCommonRevision() { return commonRevision; } /** * Sets the value of the commonRevision property. * * @param value * allowed object is * {@link String } * */ public void setCommonRevision(String value) { this.commonRevision = value; } /** * Gets the value of the security property. * * @return * possible object is * {@link String } * */ public String getSecurity() { return security; } /** * Sets the value of the security property. * * @param value * allowed object is * {@link String } * */ public void setSecurity(String value) { this.security = value; } /** * Gets the value of the userlevel property. * * @return * possible object is * {@link String } * */ public String getUserlevel() { return userlevel; } /** * Sets the value of the userlevel property. * * @param value * allowed object is * {@link String } * */ public void setUserlevel(String value) { this.userlevel = value; } /** * Gets the value of the vendor property. * * @return * possible object is * {@link String } * */ public String getVendor() { return vendor; } /** * Sets the value of the vendor property. * * @param value * allowed object is * {@link String } * */ public void setVendor(String value) { this.vendor = value; } /** * Gets the value of the wordsize property. * * @return * possible object is * {@link String } * */ public String getWordsize() { return wordsize; } /** * Sets the value of the wordsize property. * * @param value * allowed object is * {@link String } * */ public void setWordsize(String value) { this.wordsize = value; } /** * Gets the value of the annotations property. * * @return * possible object is * {@link String } * */ public String getAnnotations() { return annotations; } /** * Sets the value of the annotations property. * * @param value * allowed object is * {@link String } * */ public void setAnnotations(String value) { this.annotations = value; } }
apache-2.0
jiangjiguang/lib-java
src/com/jiangjg/lib/JavaConcurrencyinPractice/TH4/VisualComponent.java
819
package com.jiangjg.lib.JavaConcurrencyinPractice.TH4; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; //½«Ḭ̈߳²È«ÐÔίÍиø¶à¸ö״̬±äÁ¿ public class VisualComponent { private final List<KeyListener> keyListeners = new CopyOnWriteArrayList<KeyListener>(); private final List<MouseListener> mouseListeners = new CopyOnWriteArrayList<MouseListener>(); public void addKeyListeners(KeyListener listener){ keyListeners.add(listener); } public void addMouseListeners(MouseListener listener){ mouseListeners.add(listener); } public void removeKeyListener(KeyListener listener){ keyListeners.remove(listener); } public void removeMouseListeners(MouseListener listener){ mouseListeners.remove(listener); } }
apache-2.0
isandlaTech/cohorte-devtools
org.cohorte.eclipse.javax.swing.exporter/src/javax/swing/colorchooser/Toto.java
180
/** * File: Toto.java * Author: "Thomas Calmant" * Date: 25 août 2011 */ package javax.swing.colorchooser; /** * @author "Thomas Calmant" * */ public class Toto { }
apache-2.0
jwcarman/Wicketopia
joda/src/main/java/org/wicketopia/joda/JodaPlugin.java
3803
/* * Copyright (c) 2011 Carman Consulting, 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.wicketopia.joda; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import org.wicketopia.Wicketopia; import org.wicketopia.WicketopiaPlugin; import org.wicketopia.joda.provider.editor.JodaTextFieldProvider; import org.wicketopia.joda.provider.viewer.JodaLabelProvider; import org.wicketopia.joda.util.format.JodaFormatSupport; import org.wicketopia.joda.util.translator.DateTimeTranslator; import org.wicketopia.joda.util.translator.DateTimeTranslators; import java.sql.Timestamp; import java.util.Date; /** * @since 1.0 */ public class JodaPlugin implements WicketopiaPlugin { //---------------------------------------------------------------------------------------------------------------------- // Fields //---------------------------------------------------------------------------------------------------------------------- public static final String LOCAL_DATE_TYPE = "joda-local-date"; public static final String LOCAL_TIME_TYPE = "joda-local-time"; public static final String DATE_TIME_TYPE = "joda-date-time"; public static final String JAVA_DATE_TYPE = "joda-java-date"; public static final String JDBC_DATE_TYPE = "joda-jdbc-date"; public static final String JDBC_TIMESTAMP_TYPE = "joda-jdbc-timestamp"; //---------------------------------------------------------------------------------------------------------------------- // WicketopiaPlugin Implementation //---------------------------------------------------------------------------------------------------------------------- @Override public void initialize(Wicketopia wicketopia) { registerType(wicketopia, DATE_TIME_TYPE, DateTime.class, DateTimeTranslators.noOpTranslator(), "SS"); registerType(wicketopia, LOCAL_DATE_TYPE, LocalDate.class, DateTimeTranslators.localDateTranslator(), "S-"); registerType(wicketopia, LOCAL_TIME_TYPE, LocalTime.class, DateTimeTranslators.localTimeTranslator(), "-S"); registerType(wicketopia, JAVA_DATE_TYPE, Date.class, DateTimeTranslators.javaDateTranslator(), "S-"); registerType(wicketopia, JDBC_DATE_TYPE, java.sql.Date.class, DateTimeTranslators.jdbcDateTranslator(), "S-"); registerType(wicketopia, JDBC_TIMESTAMP_TYPE, Timestamp.class, DateTimeTranslators.jdbcTimestampTranslator(), "SS"); } //---------------------------------------------------------------------------------------------------------------------- // Other Methods //---------------------------------------------------------------------------------------------------------------------- public <T> void registerType(Wicketopia wicketopia, String typeName, Class<T> propertyType, DateTimeTranslator<T> translator, String style) { final JodaFormatSupport<T> formatSupport = new JodaFormatSupport<T>(translator, style); wicketopia.addViewerTypeOverride(propertyType, typeName); wicketopia.addPropertyViewerProvider(typeName, new JodaLabelProvider<T>(formatSupport)); wicketopia.addEditorTypeOverride(propertyType, typeName); wicketopia.addPropertyEditorProvider(typeName, new JodaTextFieldProvider<T>(formatSupport)); } }
apache-2.0
davi19/SmartFrotas
src/view/PesquisaViagens.java
9746
package view; import Controle.ControleDeViagemControle; import java.sql.Date; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; public class PesquisaViagens extends javax.swing.JDialog { private String codControle; private String nomeMotorista; private String placaVeiculo; private String kmSaida; private String kmEntrada; private Date dataSaida; private Date dataEntrada; public String getCodControle() { return codControle; } public String getNomeMotorista() { return nomeMotorista; } public String getPlacaVeiculo() { return placaVeiculo; } public String getKmSaida() { return kmSaida; } public String getKmEntrada() { return kmEntrada; } public Date getDataSaida() { return dataSaida; } public Date getDataEntrada() { return dataEntrada; } ControleDeViagemControle controleDeViagemControle; TelaAberturaViagem telaAberturaViagem; public PesquisaViagens(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setLocationRelativeTo(null); controleDeViagemControle = new ControleDeViagemControle(); telaAberturaViagem = new TelaAberturaViagem(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { labelPesquisarViagens = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tabelaControle = new javax.swing.JTable(); textoPesquisaControle = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Pesquisar Viagem"); labelPesquisarViagens.setText("Digite o nome do Motorista"); tabelaControle.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Código", "Motorista", "Placa Veiculo", "KM Saida", "KM Entrada", "Data Saida", "Data Entrada" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tabelaControle.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tabelaControleMouseClicked(evt); } }); jScrollPane1.setViewportView(tabelaControle); textoPesquisaControle.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { textoPesquisaControleKeyReleased(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(labelPesquisarViagens) .addGap(554, 622, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(textoPesquisaControle, javax.swing.GroupLayout.PREFERRED_SIZE, 550, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(labelPesquisarViagens) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textoPesquisaControle, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void tabelaControleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaControleMouseClicked int indiceLinha = tabelaControle.getSelectedRow(); codControle = tabelaControle.getValueAt(indiceLinha, 0).toString(); nomeMotorista = tabelaControle.getValueAt(indiceLinha, 1).toString(); placaVeiculo = tabelaControle.getValueAt(indiceLinha, 2).toString(); kmSaida = tabelaControle.getValueAt(indiceLinha, 3).toString(); kmEntrada = tabelaControle.getValueAt(indiceLinha, 4).toString(); dataSaida = Date.valueOf(tabelaControle.getValueAt(indiceLinha, 5).toString()); dataEntrada = Date.valueOf(tabelaControle.getValueAt(indiceLinha, 6).toString()); dispose(); }//GEN-LAST:event_tabelaControleMouseClicked private void textoPesquisaControleKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textoPesquisaControleKeyReleased try{ Vector cabecalho = new Vector(); cabecalho.add("Código"); cabecalho.add("Motorista"); cabecalho.add("Placa Veículo"); cabecalho.add("km Saida"); cabecalho.add("km Entrada"); cabecalho.add("Data Saida"); cabecalho.add("Data Entrada"); if(!textoPesquisaControle.getText().equals("")){ DefaultTableModel nv = new DefaultTableModel(controleDeViagemControle.Pesquisar(textoPesquisaControle.getText()),cabecalho); tabelaControle.setModel(nv); }else{ DefaultTableModel nv = new DefaultTableModel(new Vector(),cabecalho); tabelaControle.setModel(nv); } }catch(Exception ex){ JOptionPane.showMessageDialog(this, "ERRO AO PESQUISAR" + ex.getMessage()); } }//GEN-LAST:event_textoPesquisaControleKeyReleased /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PesquisaViagens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PesquisaViagens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PesquisaViagens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PesquisaViagens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { PesquisaViagens dialog = new PesquisaViagens(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel labelPesquisarViagens; private javax.swing.JTable tabelaControle; private javax.swing.JTextField textoPesquisaControle; // End of variables declaration//GEN-END:variables }
apache-2.0
knonderful/sc2-toolkit
replay/src/main/java/sc2toolkit/replay/model/PlayerColor.java
3167
/* * Project Scelight * * Copyright (c) 2013 Andras Belicza <iczaaa@gmail.com> * * This software is the property of Andras Belicza. * Copying, modifying, distributing, refactoring without the author's permission * is prohibited and protected by Law. */ package sc2toolkit.replay.model; import java.awt.Color; import javax.swing.Icon; /** * Player color. * * @author Andras Belicza */ public enum PlayerColor { /** * Unknown. */ UNKNOWN("Unknown", new Color(150, 150, 150)), /** * Red. */ RED("Red", new Color(180, 20, 30)), /** * Blue. */ BLUE("Blue", new Color(0, 66, 255)), /** * Teal. */ TEAL("Teal", new Color(28, 167, 234)), /** * Purple. */ PURPLE("Purple", new Color(84, 0, 129)), /** * Yellow. */ YELLOW("Yellow", new Color(235, 225, 41)), /** * Orange. */ ORANGE("Orange", new Color(254, 138, 14)), /** * Green. */ GREEN("Green", new Color(22, 128, 0)), /** * Light pink. */ LIGHT_PINK("Light Pink", new Color(204, 166, 252)), /** * Violet. */ VIOLET("Violet", new Color(31, 1, 201)), /** * Light gray. */ LIGHT_GRAY("Light Gray", new Color(82, 84, 148)), /** * Dark green. */ DARK_GREEN("Dark Green", new Color(16, 98, 70)), /** * Brown. */ BROWN("Brown", new Color(78, 42, 4)), /** * Light green. */ LIGHT_GREEN("Light Green", new Color(150, 255, 145)), /** * Dark gray. */ DARK_GRAY("Dark Gray", new Color(35, 35, 35)), /** * Pink. */ PINK("Pink", new Color(229, 91, 176)); /** * Text value of the player color. */ public final String text; /** * Party color value used for {@link AttributesEvents#A_PARTY_COLOR}. */ public final String partyColor; /** * Color value of this player color. */ public final Color color; /** * A darker color value of this player color. */ public final Color darkerColor; /** * A brighter color value of this player color. */ public final Color brighterColor; /** * Creates a new {@link Color}. * * @param text text value * @param color {@link Color} value of this player color */ private PlayerColor(final String text, final Color color) { this.text = text; this.color = color; // Color.darker() is not enough: darkerColor = new Color(color.getRed() / 2, color.getGreen() / 2, color.getBlue() / 2); brighterColor = new Color(127 + darkerColor.getRed(), 127 + darkerColor.getGreen(), 127 + darkerColor.getBlue()); final int ordinalPlusOne = ordinal() + 1; partyColor = ordinalPlusOne < 10 ? "tc0" + ordinalPlusOne : "tc" + ordinalPlusOne; } public Color getColor() { return color; } public Color getDarkerColor() { return darkerColor; } public Color getBrighterColor() { return brighterColor; } @Override public String toString() { return text; } /** * Cache of the values array. */ public static final PlayerColor[] VALUES = values(); }
apache-2.0
mhajas/keycloak
testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestApplicationResourceProvider.java
8459
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.testsuite.rest; import org.jboss.resteasy.annotations.cache.NoCache; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.keycloak.common.util.HtmlUtils; import org.keycloak.jose.jws.JWSInput; import org.keycloak.jose.jws.JWSInputException; import org.keycloak.models.KeycloakSession; import org.keycloak.representations.adapters.action.LogoutAction; import org.keycloak.representations.adapters.action.PushNotBeforeAction; import org.keycloak.representations.adapters.action.TestAvailabilityAction; import org.keycloak.services.resource.RealmResourceProvider; import org.keycloak.services.resources.RealmsResource; import org.keycloak.testsuite.rest.resource.TestingOIDCEndpointsApplicationResource; import org.keycloak.utils.MediaType; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> * @author Stan Silvert ssilvert@redhat.com (C) 2016 Red Hat Inc. */ public class TestApplicationResourceProvider implements RealmResourceProvider { private KeycloakSession session; private final BlockingQueue<LogoutAction> adminLogoutActions; private final BlockingQueue<PushNotBeforeAction> adminPushNotBeforeActions; private final BlockingQueue<TestAvailabilityAction> adminTestAvailabilityAction; private final TestApplicationResourceProviderFactory.OIDCClientData oidcClientData; public TestApplicationResourceProvider(KeycloakSession session, BlockingQueue<LogoutAction> adminLogoutActions, BlockingQueue<PushNotBeforeAction> adminPushNotBeforeActions, BlockingQueue<TestAvailabilityAction> adminTestAvailabilityAction, TestApplicationResourceProviderFactory.OIDCClientData oidcClientData) { this.session = session; this.adminLogoutActions = adminLogoutActions; this.adminPushNotBeforeActions = adminPushNotBeforeActions; this.adminTestAvailabilityAction = adminTestAvailabilityAction; this.oidcClientData = oidcClientData; } @POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/admin/k_logout") public void adminLogout(String data) throws JWSInputException { adminLogoutActions.add(new JWSInput(data).readJsonContent(LogoutAction.class)); } @POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/admin/k_push_not_before") public void adminPushNotBefore(String data) throws JWSInputException { adminPushNotBeforeActions.add(new JWSInput(data).readJsonContent(PushNotBeforeAction.class)); } @POST @Consumes(MediaType.TEXT_PLAIN_UTF_8) @Path("/admin/k_test_available") public void testAvailable(String data) throws JWSInputException { adminTestAvailabilityAction.add(new JWSInput(data).readJsonContent(TestAvailabilityAction.class)); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/poll-admin-logout") public LogoutAction getAdminLogoutAction() throws InterruptedException { return adminLogoutActions.poll(10, TimeUnit.SECONDS); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/poll-admin-not-before") public PushNotBeforeAction getAdminPushNotBefore() throws InterruptedException { return adminPushNotBeforeActions.poll(10, TimeUnit.SECONDS); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/poll-test-available") public TestAvailabilityAction getTestAvailable() throws InterruptedException { return adminTestAvailabilityAction.poll(10, TimeUnit.SECONDS); } @POST @Path("/clear-admin-actions") public Response clearAdminActions() { adminLogoutActions.clear(); adminPushNotBeforeActions.clear(); return Response.noContent().build(); } @POST @Consumes(javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML_UTF_8) @Path("/{action}") public String post(@PathParam("action") String action, MultivaluedMap<String, String> formParams) { String title = "APP_REQUEST"; if (action.equals("auth")) { title = "AUTH_RESPONSE"; } else if (action.equals("logout")) { title = "LOGOUT_REQUEST"; } StringBuilder sb = new StringBuilder(); sb.append("<html><head><title>" + title + "</title></head><body>"); sb.append("<b>Form parameters: </b><br>"); for (String paramName : formParams.keySet()) { sb.append(paramName).append(": ").append("<span id=\"") .append(paramName).append("\">") .append(HtmlUtils.escapeAttribute(formParams.getFirst(paramName))) .append("</span><br>"); } sb.append("<br>"); UriBuilder base = UriBuilder.fromUri("/auth"); sb.append("<a href=\"" + RealmsResource.accountUrl(base).build("test").toString() + "\" id=\"account\">account</a>"); sb.append("</body></html>"); return sb.toString(); } @GET @Produces(MediaType.TEXT_HTML_UTF_8) @Path("/{action}") public String get(@PathParam("action") String action) { //String requestUri = session.getContext().getUri().getRequestUri().toString(); String title = "APP_REQUEST"; if (action.equals("auth")) { title = "AUTH_RESPONSE"; } else if (action.equals("logout")) { title = "LOGOUT_REQUEST"; } StringBuilder sb = new StringBuilder(); sb.append("<html><head><title>" + title + "</title></head><body>"); UriBuilder base = UriBuilder.fromUri("/auth"); sb.append("<a href=\"" + RealmsResource.accountUrl(base).build("test").toString() + "\" id=\"account\">account</a>"); sb.append("</body></html>"); return sb.toString(); } @GET @NoCache @Produces(MediaType.TEXT_HTML_UTF_8) @Path("/get-account-profile") public String getAccountProfile(@QueryParam("token") String token, @QueryParam("account-uri") String accountUri) { StringBuilder sb = new StringBuilder(); sb.append("function getProfile() {\n"); sb.append(" var req = new XMLHttpRequest();\n"); sb.append(" req.open('GET', '" + accountUri + "', false);\n"); if (token != null) { sb.append(" req.setRequestHeader('Authorization', 'Bearer " + token + "');\n"); } sb.append(" req.setRequestHeader('Accept', 'application/json');\n"); sb.append(" req.send(null);\n"); sb.append(" document.getElementById('profileOutput').innerHTML=\"<span id='innerOutput'>\" + req.status + '///' + req.responseText; + \"</span>\"\n"); sb.append("}"); String jsScript = sb.toString(); sb = new StringBuilder(); sb.append("<html><head><title>Account Profile JS Test</title><script>\n") .append(jsScript) .append( "</script></head>\n") .append("<body onload='getProfile()'><div id='profileOutput'></div></body>") .append("</html>"); return sb.toString(); } @Path("/oidc-client-endpoints") public TestingOIDCEndpointsApplicationResource getTestingOIDCClientEndpoints() { return new TestingOIDCEndpointsApplicationResource(oidcClientData); } @Override public Object getResource() { return this; } @Override public void close() { } }
apache-2.0
elenore233/LeetCode
LeetCode/src/_001_Two_Sum/Solution.java
1185
package _001_Two_Sum; import java.util.HashMap; import java.util.Map; /* Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. UPDATE (2016/2/13): The return format had been changed to zero-based indices. Please read the above updated description carefully. */ public class Solution { public static int[] twoSum(int[] nums, int target) { // 创建一个map用来映射值和索引。 Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { // 如果遍历过的值中有当前值的另一半,则配对成功。 if (map.containsKey(target - nums[i])) { return new int[] {map.get(target - nums[i]), i}; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } public static void main(String[] args) { int[] result = twoSum(new int[]{11, 7, 2, 15}, 9); System.out.println(result[0] + " " + result[1]); } }
apache-2.0
nextalk/webim-java
src/webim/client/Base64.java
86834
package webim.client; /** * <p>Encodes and decodes to and from Base64 notation.</p> * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> * * <p>Example:</p> * * <code>String encoded = Base64.encode( myByteArray );</code> * <br /> * <code>byte[] myByteArray = Base64.decode( encoded );</code> * * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass * several pieces of information to the encoder. In the "higher level" methods such as * encodeBytes( bytes, options ) the options parameter can be used to indicate such * things as first gzipping the bytes before encoding them, not inserting linefeeds, * and encoding using the URL-safe and Ordered dialects.</p> * * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, * Section 2.1, implementations should not add line feeds unless explicitly told * to do so. I've got Base64 set to this behavior now, although earlier versions * broke lines by default.</p> * * <p>The constants defined in Base64 can be OR-ed together to combine options, so you * might make a call like this:</p> * * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code> * <p>to compress the data before encoding it and then making the output have newline characters.</p> * <p>Also...</p> * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code> * * * * <p> * Change Log: * </p> * <ul> * <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the * value 01111111, which is an invalid base 64 character but should not * throw an ArrayIndexOutOfBoundsException either. Led to discovery of * mishandling (or potential for better handling) of other bad input * characters. You should now get an IOException if you try decoding * something that has bad characters in it.</li> * <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded * string ended in the last column; the buffer was not properly shrunk and * contained an extra (null) byte that made it into the string.</li> * <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size * was wrong for files of size 31, 34, and 37 bytes.</li> * <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing * the Base64.OutputStream closed the Base64 encoding (by padding with equals * signs) too soon. Also added an option to suppress the automatic decoding * of gzipped streams. Also added experimental support for specifying a * class loader when using the * {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)} * method.</li> * <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java * footprint with its CharEncoders and so forth. Fixed some javadocs that were * inconsistent. Removed imports and specified things like java.io.IOException * explicitly inline.</li> * <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the * final encoded data will be so that the code doesn't have to create two output * arrays: an oversized initial one and then a final, exact-sized one. Big win * when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not * using the gzip options which uses a different mechanism with streams and stuff).</li> * <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some * similar helper methods to be more efficient with memory by not returning a * String but just a byte array.</li> * <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments * and bug fixes queued up and finally executed. Thanks to everyone who sent * me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else. * Much bad coding was cleaned up including throwing exceptions where necessary * instead of returning null values or something similar. Here are some changes * that may affect you: * <ul> * <li><em>Does not break lines, by default.</em> This is to keep in compliance with * <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li> * <li><em>Throws exceptions instead of returning null values.</em> Because some operations * (especially those that may permit the GZIP option) use IO streams, there * is a possiblity of an java.io.IOException being thrown. After some discussion and * thought, I've changed the behavior of the methods to throw java.io.IOExceptions * rather than return null if ever there's an error. I think this is more * appropriate, though it will require some changes to your code. Sorry, * it should have been done this way to begin with.</li> * <li><em>Removed all references to System.out, System.err, and the like.</em> * Shame on me. All I can say is sorry they were ever there.</li> * <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed * such as when passed arrays are null or offsets are invalid.</li> * <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings. * This was especially annoying before for people who were thorough in their * own projects and then had gobs of javadoc warnings on this file.</li> * </ul> * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug * when using very small files (~&lt; 40 bytes).</li> * <li>v2.2 - Added some helper methods for encoding/decoding directly from * one file to the next. Also added a main() method to support command line * encoding/decoding from one file to the next. Also added these Base64 dialects: * <ol> * <li>The default is RFC3548 format.</li> * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates * URL and file name friendly format as described in Section 4 of RFC3548. * http://www.faqs.org/rfcs/rfc3548.html</li> * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates * URL and file name friendly format that preserves lexical ordering as described * in http://www.faqs.org/qa/rfcc-1940.html</li> * </ol> * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a> * for contributing the new Base64 dialects. * </li> * * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added * some convenience methods for reading and writing to and from files.</li> * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).</li> * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.</li> * <li>v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (<tt>int</tt>s that you "OR" together).</li> * <li>v1.5.1 - Fixed bug when decompressing and decoding to a * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).</li> * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.</li> * <li>v1.4 - Added helper methods to read/write files.</li> * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.3.7 */ public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding in first bit. Value is one. */ public final static int ENCODE = 1; /** Specify decoding in first bit. Value is zero. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed in second bit. Value is two. */ public final static int GZIP = 2; /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */ public final static int DONT_GUNZIP = 4; /** Do break lines when encoding. Value is 8. */ public final static int DO_BREAK_LINES = 8; /** * Encode using Base64-like encoding that is URL- and Filename-safe as described * in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * It is important to note that data encoded this way is <em>not</em> officially valid Base64, * or at the very least should not be called Base64 without also specifying that is * was encoded using the URL- and Filename-safe dialect. */ public final static int URL_SAFE = 16; /** * Encode using the special "ordered" dialect of Base64 described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ public final static int ORDERED = 32; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "US-ASCII"; private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ /** The 64 valid Base64 values. */ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ private final static byte[] _STANDARD_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] _STANDARD_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ /** * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." */ private final static byte[] _URL_SAFE_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' }; /** * Used in decoding URL- and Filename-safe dialects of Base64. */ private final static byte[] _URL_SAFE_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ /** * I don't get the point of this technique, but someone requested it, * and it is described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ private final static byte[] _ORDERED_ALPHABET = { (byte)'-', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'_', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' }; /** * Used in decoding the "ordered" dialect of Base64. */ private final static byte[] _ORDERED_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ /** * Returns one of the _SOMETHING_ALPHABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getAlphabet( int options ) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_ALPHABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_ALPHABET; } else { return _STANDARD_ALPHABET; } } // end getAlphabet /** * Returns one of the _SOMETHING_DECODABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED and URL_SAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getDecodabet( int options ) { if( (options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_DECODABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_DECODABET; } else { return _STANDARD_DECODABET; } } // end getAlphabet /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); return b4; } // end encode3to4 /** * <p>Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>.</p> * <p>This is the lowest level of the encoding methods with * all possible parameters.</p> * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options ) { byte[] ALPHABET = getAlphabet( options ); // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> ByteBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); encoded.put(enc4); } // end input remaining } /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> CharBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); for( int i = 0; i < 4; i++ ){ encoded.put( (char)(enc4[i] & 0xFF) ); } } // end input remaining } /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @throws java.io.IOException if there is an error * @throws NullPointerException if serializedObject is null * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) throws java.io.IOException { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @return The data in Base64-encoded form * @throws NullPointerException if source array is null * @since 1.4 */ public static String encodeBytes( byte[] source ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * <p>As of v 2.3, if there is an error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @return The Base64-encoded data as a String * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes( source, off, len, NO_OPTIONS ); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { byte[] encoded = encodeBytesToBytes( source, off, len, options ); // Return value according to relevant encoding. try { return new String( encoded, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( encoded ); } // end catch } // end encodeBytes /** * Similar to {@link #encodeBytes(byte[])} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @return The Base64-encoded data as a byte[] (of ASCII characters) * @throws NullPointerException if source array is null * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source ) { byte[] encoded = null; try { encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); } catch( java.io.IOException ex ) { assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); } return encoded; } /** * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } // end encodeBytesToBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * <p>This is the lowest level of the decoding methods with * all possible parameters.</p> * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param options alphabet type is pulled from this (standard, url-safe, ordered) * @return the number of decoded bytes converted * @throws NullPointerException if source or destination arrays are null * @throws IllegalArgumentException if srcOffset or destOffset are invalid * or there is not enough room in the array. * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Source array was null." ); } // end if if( destination == null ){ throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if byte[] DECODABET = getDecodabet( options ); // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; } } // end decodeToBytes /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @return decoded data * @since 2.3.1 */ public static byte[] decode( byte[] source ) throws java.io.IOException { byte[] decoded = null; // try { decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); // } catch( java.io.IOException ex ) { // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); // } return decoded; } /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @param options Can specify options such as alphabet type to use * @return decoded data * @throws java.io.IOException If bogus characters exist in source data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len, int options ) throws java.io.IOException { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Cannot decode null source array." ); } // end if if( off < 0 || off + len > source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); } // end if if( len == 0 ){ return new byte[0]; }else if( len < 4 ){ throw new IllegalArgumentException( "Base64-encoded string must have at least four characters, but length specified was " + len ); } // end if byte[] DECODABET = getDecodabet( options ); int len34 = len * 3 / 4; // Estimate on array size byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; // Keep track of where we're writing byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space int b4Posn = 0; // Keep track of four byte input buffer int i = 0; // Source array counter byte sbiDecode = 0; // Special value from DECODABET for( i = off; i < off+len; i++ ) { // Loop through source sbiDecode = DECODABET[ source[i]&0xFF ]; // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = source[i]; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( source[i] == EQUALS_SIGN ) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { // There's a bad input character in the Base64 stream. throw new java.io.IOException( String.format( "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @throws java.io.IOException If there is a problem * @since 1.4 */ public static byte[] decode( String s ) throws java.io.IOException { return decode( s, NO_OPTIONS ); } /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @param options encode options such as URL_SAFE * @return the decoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if <tt>s</tt> is null * @since 1.4 */ public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 1.5 */ public static Object decodeToObject( String encodedObject ) throws java.io.IOException, java.lang.ClassNotFoundException { return decodeToObject(encodedObject,NO_OPTIONS,null); } /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * If <tt>loader</tt> is not null, it will be the class loader * used when deserializing. * * @param encodedObject The Base64 data to decode * @param options Various parameters related to decoding * @param loader Optional class loader to use in deserializing classes. * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 2.3.4 */ public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if dataToEncode is null * @since 2.1 */ public static void encodeToFile( byte[] dataToEncode, String filename ) throws java.io.IOException { if( dataToEncode == null ){ throw new NullPointerException( "Data to encode was null." ); } // end iff Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end encodeToFile /** * Convenience method for decoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @throws java.io.IOException if there is an error * @since 2.1 */ public static void decodeToFile( String dataToDecode, String filename ) throws java.io.IOException { Base64.OutputStream bos = null; try{ bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading encoded data * @return decoded byte array * @throws java.io.IOException if there is an error * @since 2.1 */ public static byte[] decodeFromFile( String filename ) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading binary data * @return base64-encoded string * @throws java.io.IOException if there is an error * @since 2.1 */ public static String encodeFromFile( String filename ) throws java.io.IOException { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /** * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void encodeFileToFile( String infile, String outfile ) throws java.io.IOException { String encoded = Base64.encodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end encodeFileToFile /** * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void decodeFileToFile( String infile, String outfile ) throws java.io.IOException { byte[] decoded = Base64.decodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( decoded ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end decodeFileToFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters private int options; // Record options used to create the stream. private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.options = options; // Record for later this.breakLines = (options & DO_BREAK_LINES) > 0; this.encode = (options & ENCODE) > 0; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; this.decodabet = getDecodabet(options); } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ @Override public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } else { break; // out of for loop } // end else: end of stream } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; // Must be end of stream } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) { break; // Reads a -1 if end of stream } // end if: end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0, options ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ){ return -1; } // end if: got data if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) { position = -1; } // end if: end return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ @Override public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); if( b >= 0 ) { dest[off + i] = (byte) b; } else if( i == 0 ) { return -1; } else { break; // Out of 'for' loop } // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; private int options; // Record for later private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DO_BREAK_LINES) != 0; this.encode = (options & ENCODE) != 0; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; this.options = options; this.decodabet = getDecodabet(options); } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ @Override public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to encode. this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { this.out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to output. int len = Base64.decode4to3( buffer, 0, b4, 0, options ); out.write( b4, 0, len ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ @Override public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. * @throws java.io.IOException if there's an error. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position, options ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ @Override public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @throws java.io.IOException if there's an error flushing * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64
apache-2.0
CymricNPG/abattle
ABattle.Communication/xtend-gen/net/npg/abattle/communication/command/impl/CommandStore.java
2402
package net.npg.abattle.communication.command.impl; import java.util.List; import net.npg.abattle.communication.command.CommandType; import net.npg.abattle.communication.command.GameCommand; import org.eclipse.xtend.lib.Data; import org.eclipse.xtext.xbase.lib.Pure; import org.eclipse.xtext.xbase.lib.util.ToStringHelper; @Data @SuppressWarnings("all") class CommandStore { private final CommandType _commandType; private final GameCommand _command; private final List<Integer> _destination; public CommandStore(final CommandType commandType, final GameCommand command, final List<Integer> destination) { super(); this._commandType = commandType; this._command = command; this._destination = destination; } @Override @Pure public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this._commandType== null) ? 0 : this._commandType.hashCode()); result = prime * result + ((this._command== null) ? 0 : this._command.hashCode()); result = prime * result + ((this._destination== null) ? 0 : this._destination.hashCode()); return result; } @Override @Pure public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CommandStore other = (CommandStore) obj; if (this._commandType == null) { if (other._commandType != null) return false; } else if (!this._commandType.equals(other._commandType)) return false; if (this._command == null) { if (other._command != null) return false; } else if (!this._command.equals(other._command)) return false; if (this._destination == null) { if (other._destination != null) return false; } else if (!this._destination.equals(other._destination)) return false; return true; } @Override @Pure public String toString() { String result = new ToStringHelper().toString(this); return result; } @Pure public CommandType getCommandType() { return this._commandType; } @Pure public GameCommand getCommand() { return this._command; } @Pure public List<Integer> getDestination() { return this._destination; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/DBInstanceAutomatedBackupQuotaExceededException.java
1428
/* * 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.rds.model; import javax.annotation.Generated; /** * <p> * The quota for retained automated backups was exceeded. This prevents you from retaining any additional automated * backups. The retained automated backups quota is the same as your DB Instance quota. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DBInstanceAutomatedBackupQuotaExceededException extends com.amazonaws.services.rds.model.AmazonRDSException { private static final long serialVersionUID = 1L; /** * Constructs a new DBInstanceAutomatedBackupQuotaExceededException with the specified error message. * * @param message * Describes the error encountered. */ public DBInstanceAutomatedBackupQuotaExceededException(String message) { super(message); } }
apache-2.0