repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
topsale/leesite
leesite-module/src/main/java/com/funtl/leesite/common/web/CKFinderConfig.java
3125
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.funtl.leesite.common.web; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import com.ckfinder.connector.configuration.Configuration; import com.ckfinder.connector.data.AccessControlLevel; import com.ckfinder.connector.utils.AccessControlUtil; import com.funtl.leesite.common.config.Global; import com.funtl.leesite.modules.sys.security.SystemAuthorizingRealm.Principal; import com.funtl.leesite.modules.sys.utils.UserUtils; /** * CKFinder配置 * * @author Lusifer * @version 2014-06-25 */ public class CKFinderConfig extends Configuration { public CKFinderConfig(ServletConfig servletConfig) { super(servletConfig); } @Override protected Configuration createConfigurationInstance() { Principal principal = (Principal) UserUtils.getPrincipal(); if (principal == null) { return new CKFinderConfig(this.servletConf); } boolean isView = true;//UserUtils.getSubject().isPermitted("cms:ckfinder:view"); boolean isUpload = true;//UserUtils.getSubject().isPermitted("cms:ckfinder:upload"); boolean isEdit = true;//UserUtils.getSubject().isPermitted("cms:ckfinder:edit"); AccessControlLevel alc = this.getAccessConrolLevels().get(0); alc.setFolderView(isView); alc.setFolderCreate(isEdit); alc.setFolderRename(isEdit); alc.setFolderDelete(isEdit); alc.setFileView(isView); alc.setFileUpload(isUpload); alc.setFileRename(isEdit); alc.setFileDelete(isEdit); // for (AccessControlLevel a : this.getAccessConrolLevels()){ // System.out.println(a.getRole()+", "+a.getResourceType()+", "+a.getFolder() // +", "+a.isFolderView()+", "+a.isFolderCreate()+", "+a.isFolderRename()+", "+a.isFolderDelete() // +", "+a.isFileView()+", "+a.isFileUpload()+", "+a.isFileRename()+", "+a.isFileDelete()); // } AccessControlUtil.getInstance(this).loadACLConfig(); try { // Principal principal = (Principal)SecurityUtils.getSubject().getPrincipal(); // this.baseURL = ServletContextFactory.getServletContext().getContextPath()+"/userfiles/"+principal+"/"; this.baseURL = Servlets.getRequest().getContextPath() + Global.USERFILES_BASE_URL + principal + "/"; this.baseDir = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + principal + "/"; } catch (Exception e) { throw new RuntimeException(e); } return new CKFinderConfig(this.servletConf); } @Override public boolean checkAuthentication(final HttpServletRequest request) { return UserUtils.getPrincipal() != null; } }
apache-2.0
boalang/compiler
src/compiled-proto/boa/types/Diff.java
99398
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: diff.proto package boa.types; public final class Diff { private Diff() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface ChangedFileOrBuilder extends com.google.protobuf.MessageOrBuilder { // required .boa.types.ChangeKind change = 1; /** * <code>required .boa.types.ChangeKind change = 1;</code> * * <pre> ** The kind of change for this file * </pre> */ boolean hasChange(); /** * <code>required .boa.types.ChangeKind change = 1;</code> * * <pre> ** The kind of change for this file * </pre> */ boa.types.Shared.ChangeKind getChange(); // required .boa.types.ChangedFile.FileKind kind = 2; /** * <code>required .boa.types.ChangedFile.FileKind kind = 2;</code> * * <pre> ** The kind of file * </pre> */ boolean hasKind(); /** * <code>required .boa.types.ChangedFile.FileKind kind = 2;</code> * * <pre> ** The kind of file * </pre> */ boa.types.Diff.ChangedFile.FileKind getKind(); // required string name = 3; /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ boolean hasName(); /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ java.lang.String getName(); /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ com.google.protobuf.ByteString getNameBytes(); // required uint64 key = 4; /** * <code>required uint64 key = 4;</code> * * <pre> ** @exclude * </pre> */ boolean hasKey(); /** * <code>required uint64 key = 4;</code> * * <pre> ** @exclude * </pre> */ long getKey(); // required bool ast = 5; /** * <code>required bool ast = 5;</code> * * <pre> ** @exclude Indicates if this file has a corresponding parsed AST or not * </pre> */ boolean hasAst(); /** * <code>required bool ast = 5;</code> * * <pre> ** @exclude Indicates if this file has a corresponding parsed AST or not * </pre> */ boolean getAst(); // optional .boa.types.CommentsRoot comments = 6; /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ boolean hasComments(); /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ boa.types.Ast.CommentsRoot getComments(); /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ boa.types.Ast.CommentsRootOrBuilder getCommentsOrBuilder(); // repeated .boa.types.ChangeKind changes = 7; /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ java.util.List<boa.types.Shared.ChangeKind> getChangesList(); /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ int getChangesCount(); /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ boa.types.Shared.ChangeKind getChanges(int index); // repeated string previous_names = 8; /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ java.util.List<java.lang.String> getPreviousNamesList(); /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ int getPreviousNamesCount(); /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ java.lang.String getPreviousNames(int index); /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ com.google.protobuf.ByteString getPreviousNamesBytes(int index); // repeated int32 previous_versions = 9; /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ java.util.List<java.lang.Integer> getPreviousVersionsList(); /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ int getPreviousVersionsCount(); /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ int getPreviousVersions(int index); // repeated int32 previous_indices = 10; /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ java.util.List<java.lang.Integer> getPreviousIndicesList(); /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ int getPreviousIndicesCount(); /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ int getPreviousIndices(int index); } /** * Protobuf type {@code boa.types.ChangedFile} * * <pre> ** A file committed in a Revision * </pre> */ public static final class ChangedFile extends com.google.protobuf.GeneratedMessage implements ChangedFileOrBuilder { // Use ChangedFile.newBuilder() to construct. private ChangedFile(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private ChangedFile(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final ChangedFile defaultInstance; public static ChangedFile getDefaultInstance() { return defaultInstance; } public ChangedFile getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ChangedFile( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { int rawValue = input.readEnum(); boa.types.Shared.ChangeKind value = boa.types.Shared.ChangeKind.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(1, rawValue); } else { bitField0_ |= 0x00000001; change_ = value; } break; } case 16: { int rawValue = input.readEnum(); boa.types.Diff.ChangedFile.FileKind value = boa.types.Diff.ChangedFile.FileKind.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(2, rawValue); } else { bitField0_ |= 0x00000002; kind_ = value; } break; } case 26: { bitField0_ |= 0x00000004; name_ = input.readBytes(); break; } case 32: { bitField0_ |= 0x00000008; key_ = input.readUInt64(); break; } case 40: { bitField0_ |= 0x00000010; ast_ = input.readBool(); break; } case 50: { boa.types.Ast.CommentsRoot.Builder subBuilder = null; if (((bitField0_ & 0x00000020) == 0x00000020)) { subBuilder = comments_.toBuilder(); } comments_ = input.readMessage(boa.types.Ast.CommentsRoot.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(comments_); comments_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000020; break; } case 56: { int rawValue = input.readEnum(); boa.types.Shared.ChangeKind value = boa.types.Shared.ChangeKind.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(7, rawValue); } else { if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) { changes_ = new java.util.ArrayList<boa.types.Shared.ChangeKind>(); mutable_bitField0_ |= 0x00000040; } changes_.add(value); } break; } case 58: { int length = input.readRawVarint32(); int oldLimit = input.pushLimit(length); while(input.getBytesUntilLimit() > 0) { int rawValue = input.readEnum(); boa.types.Shared.ChangeKind value = boa.types.Shared.ChangeKind.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(7, rawValue); } else { if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) { changes_ = new java.util.ArrayList<boa.types.Shared.ChangeKind>(); mutable_bitField0_ |= 0x00000040; } changes_.add(value); } } input.popLimit(oldLimit); break; } case 66: { if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) { previousNames_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000080; } previousNames_.add(input.readBytes()); break; } case 72: { if (!((mutable_bitField0_ & 0x00000100) == 0x00000100)) { previousVersions_ = new java.util.ArrayList<java.lang.Integer>(); mutable_bitField0_ |= 0x00000100; } previousVersions_.add(input.readInt32()); break; } case 74: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); if (!((mutable_bitField0_ & 0x00000100) == 0x00000100) && input.getBytesUntilLimit() > 0) { previousVersions_ = new java.util.ArrayList<java.lang.Integer>(); mutable_bitField0_ |= 0x00000100; } while (input.getBytesUntilLimit() > 0) { previousVersions_.add(input.readInt32()); } input.popLimit(limit); break; } case 80: { if (!((mutable_bitField0_ & 0x00000200) == 0x00000200)) { previousIndices_ = new java.util.ArrayList<java.lang.Integer>(); mutable_bitField0_ |= 0x00000200; } previousIndices_.add(input.readInt32()); break; } case 82: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); if (!((mutable_bitField0_ & 0x00000200) == 0x00000200) && input.getBytesUntilLimit() > 0) { previousIndices_ = new java.util.ArrayList<java.lang.Integer>(); mutable_bitField0_ |= 0x00000200; } while (input.getBytesUntilLimit() > 0) { previousIndices_.add(input.readInt32()); } input.popLimit(limit); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000040) == 0x00000040)) { changes_ = java.util.Collections.unmodifiableList(changes_); } if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) { previousNames_ = new com.google.protobuf.UnmodifiableLazyStringList(previousNames_); } if (((mutable_bitField0_ & 0x00000100) == 0x00000100)) { previousVersions_ = java.util.Collections.unmodifiableList(previousVersions_); } if (((mutable_bitField0_ & 0x00000200) == 0x00000200)) { previousIndices_ = java.util.Collections.unmodifiableList(previousIndices_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return boa.types.Diff.internal_static_boa_types_ChangedFile_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return boa.types.Diff.internal_static_boa_types_ChangedFile_fieldAccessorTable .ensureFieldAccessorsInitialized( boa.types.Diff.ChangedFile.class, boa.types.Diff.ChangedFile.Builder.class); } public static com.google.protobuf.Parser<ChangedFile> PARSER = new com.google.protobuf.AbstractParser<ChangedFile>() { public ChangedFile parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ChangedFile(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<ChangedFile> getParserForType() { return PARSER; } /** * Protobuf enum {@code boa.types.ChangedFile.FileKind} * * <pre> ** Describes the kind of the file * </pre> */ public enum FileKind implements com.google.protobuf.ProtocolMessageEnum { /** * <code>OTHER = 0;</code> * * <pre> ** The file's type was unknown * </pre> */ OTHER(0, 0), /** * <code>BINARY = 1;</code> * * <pre> ** The file represents a binary file * </pre> */ BINARY(1, 1), /** * <code>TEXT = 2;</code> * * <pre> ** The file represents a text file * </pre> */ TEXT(2, 2), /** * <code>XML = 3;</code> * * <pre> ** The file represents an XML file * </pre> */ XML(3, 3), /** * <code>SOURCE_JAVA_ERROR = 100;</code> * * <pre> ** The file represents a Java source file that had a parse error * </pre> */ SOURCE_JAVA_ERROR(4, 100), /** * <code>SOURCE_JAVA_JLS2 = 102;</code> * * <pre> ** The file represents a Java source file that parsed without error as JLS2 * </pre> */ SOURCE_JAVA_JLS2(5, 102), /** * <code>SOURCE_JAVA_JLS3 = 103;</code> * * <pre> ** The file represents a Java source file that parsed without error as JLS3 * </pre> */ SOURCE_JAVA_JLS3(6, 103), /** * <code>SOURCE_JAVA_JLS4 = 104;</code> * * <pre> ** The file represents a Java source file that parsed without error as JLS4 * </pre> */ SOURCE_JAVA_JLS4(7, 104), /** * <code>SOURCE_JAVA_JLS8 = 108;</code> * * <pre> ** The file represents a Java source file that parsed without error as JLS8 * </pre> */ SOURCE_JAVA_JLS8(8, 108), /** * <code>SOURCE_CS_ERROR = 200;</code> * * <pre> ** @exclude TODO * </pre> */ SOURCE_CS_ERROR(14, 200), /** * <code>SOURCE_CS_CS1 = 201;</code> * * <pre> ** @exclude TODO * </pre> */ SOURCE_CS_CS1(15, 201), /** * <code>SOURCE_CS_CS2 = 202;</code> * * <pre> ** @exclude TODO * </pre> */ SOURCE_CS_CS2(16, 202), /** * <code>SOURCE_CS_CS3 = 203;</code> * * <pre> ** @exclude TODO * </pre> */ SOURCE_CS_CS3(17, 203), /** * <code>SOURCE_CS_CS4 = 204;</code> * * <pre> ** @exclude TODO * </pre> */ SOURCE_CS_CS4(18, 204), /** * <code>SOURCE_CS_CS5 = 205;</code> * * <pre> ** @exclude TODO * </pre> */ SOURCE_CS_CS5(19, 205), /** * <code>SOURCE_JS_ERROR = 300;</code> * * <pre> ** The file represents a JavaScript source file that had a parse error * </pre> */ SOURCE_JS_ERROR(26, 300), /** * <code>SOURCE_JS_ES1 = 301;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES1 * </pre> */ SOURCE_JS_ES1(27, 301), /** * <code>SOURCE_JS_ES2 = 302;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES2 * </pre> */ SOURCE_JS_ES2(28, 302), /** * <code>SOURCE_JS_ES3 = 303;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES3 * </pre> */ SOURCE_JS_ES3(29, 303), /** * <code>SOURCE_JS_ES5 = 304;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES5 * </pre> */ SOURCE_JS_ES5(30, 304), /** * <code>SOURCE_JS_ES6 = 305;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES6 * </pre> */ SOURCE_JS_ES6(31, 305), /** * <code>SOURCE_JS_ES7 = 306;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES7 * </pre> */ SOURCE_JS_ES7(32, 306), /** * <code>SOURCE_JS_ES8 = 307;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES8 * </pre> */ SOURCE_JS_ES8(33, 307), /** * <code>SOURCE_PHP_ERROR = 400;</code> * * <pre> ** The file represents a PHP source file that had a parse error * </pre> */ SOURCE_PHP_ERROR(35, 400), /** * <code>SOURCE_PHP5 = 401;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES1 * </pre> */ SOURCE_PHP5(36, 401), /** * <code>SOURCE_PHP5_3 = 402;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES2 * </pre> */ SOURCE_PHP5_3(37, 402), /** * <code>SOURCE_PHP5_4 = 403;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES3 * </pre> */ SOURCE_PHP5_4(38, 403), /** * <code>SOURCE_PHP5_5 = 404;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES5 * </pre> */ SOURCE_PHP5_5(39, 404), /** * <code>SOURCE_PHP5_6 = 405;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES6 * </pre> */ SOURCE_PHP5_6(40, 405), /** * <code>SOURCE_PHP7_0 = 406;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES7 * </pre> */ SOURCE_PHP7_0(41, 406), /** * <code>SOURCE_PHP7_1 = 407;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES8 * </pre> */ SOURCE_PHP7_1(42, 407), /** * <code>SOURCE_HTML_ERROR = 500;</code> * * <pre> ** The file represents an HTML source file that had a parse error * </pre> */ SOURCE_HTML_ERROR(44, 500), /** * <code>Source_HTML = 501;</code> * * <pre> ** The file represents an HTML source file that parsed without error * </pre> */ Source_HTML(45, 501), /** * <code>SOURCE_XML_ERROR = 600;</code> * * <pre> ** The file represents an XML source file that had a parse error * </pre> */ SOURCE_XML_ERROR(47, 600), /** * <code>Source_XML = 601;</code> * * <pre> ** The file represents an HTML source file that parsed without error * </pre> */ Source_XML(48, 601), /** * <code>SOURCE_CSS_ERROR = 700;</code> * * <pre> ** The file represents an CSS source file that had a parse error * </pre> */ SOURCE_CSS_ERROR(50, 700), /** * <code>Source_CSS = 701;</code> * * <pre> ** The file represents an CSS source file that parsed without error * </pre> */ Source_CSS(51, 701), ; /** * <code>JAVA_ERROR = 100;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind JAVA_ERROR = SOURCE_JAVA_ERROR; /** * <code>JLS2 = 102;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind JLS2 = SOURCE_JAVA_JLS2; /** * <code>JLS3 = 103;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind JLS3 = SOURCE_JAVA_JLS3; /** * <code>JLS4 = 104;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind JLS4 = SOURCE_JAVA_JLS4; /** * <code>JLS8 = 108;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind JLS8 = SOURCE_JAVA_JLS8; /** * <code>CS_ERROR = 200;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind CS_ERROR = SOURCE_CS_ERROR; /** * <code>CS1 = 201;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind CS1 = SOURCE_CS_CS1; /** * <code>CS2 = 202;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind CS2 = SOURCE_CS_CS2; /** * <code>CS3 = 203;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind CS3 = SOURCE_CS_CS3; /** * <code>CS4 = 204;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind CS4 = SOURCE_CS_CS4; /** * <code>CS5 = 205;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind CS5 = SOURCE_CS_CS5; /** * <code>JS_ERROR = 300;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind JS_ERROR = SOURCE_JS_ERROR; /** * <code>PHP_ERROR = 400;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind PHP_ERROR = SOURCE_PHP_ERROR; /** * <code>HTML_ERROR = 500;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind HTML_ERROR = SOURCE_HTML_ERROR; /** * <code>XML_ERROR = 600;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind XML_ERROR = SOURCE_XML_ERROR; /** * <code>CSS_ERROR = 700;</code> * * <pre> ** @exclude * </pre> */ public static final FileKind CSS_ERROR = SOURCE_CSS_ERROR; /** * <code>OTHER = 0;</code> * * <pre> ** The file's type was unknown * </pre> */ public static final int OTHER_VALUE = 0; /** * <code>BINARY = 1;</code> * * <pre> ** The file represents a binary file * </pre> */ public static final int BINARY_VALUE = 1; /** * <code>TEXT = 2;</code> * * <pre> ** The file represents a text file * </pre> */ public static final int TEXT_VALUE = 2; /** * <code>XML = 3;</code> * * <pre> ** The file represents an XML file * </pre> */ public static final int XML_VALUE = 3; /** * <code>SOURCE_JAVA_ERROR = 100;</code> * * <pre> ** The file represents a Java source file that had a parse error * </pre> */ public static final int SOURCE_JAVA_ERROR_VALUE = 100; /** * <code>SOURCE_JAVA_JLS2 = 102;</code> * * <pre> ** The file represents a Java source file that parsed without error as JLS2 * </pre> */ public static final int SOURCE_JAVA_JLS2_VALUE = 102; /** * <code>SOURCE_JAVA_JLS3 = 103;</code> * * <pre> ** The file represents a Java source file that parsed without error as JLS3 * </pre> */ public static final int SOURCE_JAVA_JLS3_VALUE = 103; /** * <code>SOURCE_JAVA_JLS4 = 104;</code> * * <pre> ** The file represents a Java source file that parsed without error as JLS4 * </pre> */ public static final int SOURCE_JAVA_JLS4_VALUE = 104; /** * <code>SOURCE_JAVA_JLS8 = 108;</code> * * <pre> ** The file represents a Java source file that parsed without error as JLS8 * </pre> */ public static final int SOURCE_JAVA_JLS8_VALUE = 108; /** * <code>JAVA_ERROR = 100;</code> * * <pre> ** @exclude * </pre> */ public static final int JAVA_ERROR_VALUE = 100; /** * <code>JLS2 = 102;</code> * * <pre> ** @exclude * </pre> */ public static final int JLS2_VALUE = 102; /** * <code>JLS3 = 103;</code> * * <pre> ** @exclude * </pre> */ public static final int JLS3_VALUE = 103; /** * <code>JLS4 = 104;</code> * * <pre> ** @exclude * </pre> */ public static final int JLS4_VALUE = 104; /** * <code>JLS8 = 108;</code> * * <pre> ** @exclude * </pre> */ public static final int JLS8_VALUE = 108; /** * <code>SOURCE_CS_ERROR = 200;</code> * * <pre> ** @exclude TODO * </pre> */ public static final int SOURCE_CS_ERROR_VALUE = 200; /** * <code>SOURCE_CS_CS1 = 201;</code> * * <pre> ** @exclude TODO * </pre> */ public static final int SOURCE_CS_CS1_VALUE = 201; /** * <code>SOURCE_CS_CS2 = 202;</code> * * <pre> ** @exclude TODO * </pre> */ public static final int SOURCE_CS_CS2_VALUE = 202; /** * <code>SOURCE_CS_CS3 = 203;</code> * * <pre> ** @exclude TODO * </pre> */ public static final int SOURCE_CS_CS3_VALUE = 203; /** * <code>SOURCE_CS_CS4 = 204;</code> * * <pre> ** @exclude TODO * </pre> */ public static final int SOURCE_CS_CS4_VALUE = 204; /** * <code>SOURCE_CS_CS5 = 205;</code> * * <pre> ** @exclude TODO * </pre> */ public static final int SOURCE_CS_CS5_VALUE = 205; /** * <code>CS_ERROR = 200;</code> * * <pre> ** @exclude * </pre> */ public static final int CS_ERROR_VALUE = 200; /** * <code>CS1 = 201;</code> * * <pre> ** @exclude * </pre> */ public static final int CS1_VALUE = 201; /** * <code>CS2 = 202;</code> * * <pre> ** @exclude * </pre> */ public static final int CS2_VALUE = 202; /** * <code>CS3 = 203;</code> * * <pre> ** @exclude * </pre> */ public static final int CS3_VALUE = 203; /** * <code>CS4 = 204;</code> * * <pre> ** @exclude * </pre> */ public static final int CS4_VALUE = 204; /** * <code>CS5 = 205;</code> * * <pre> ** @exclude * </pre> */ public static final int CS5_VALUE = 205; /** * <code>SOURCE_JS_ERROR = 300;</code> * * <pre> ** The file represents a JavaScript source file that had a parse error * </pre> */ public static final int SOURCE_JS_ERROR_VALUE = 300; /** * <code>SOURCE_JS_ES1 = 301;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES1 * </pre> */ public static final int SOURCE_JS_ES1_VALUE = 301; /** * <code>SOURCE_JS_ES2 = 302;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES2 * </pre> */ public static final int SOURCE_JS_ES2_VALUE = 302; /** * <code>SOURCE_JS_ES3 = 303;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES3 * </pre> */ public static final int SOURCE_JS_ES3_VALUE = 303; /** * <code>SOURCE_JS_ES5 = 304;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES5 * </pre> */ public static final int SOURCE_JS_ES5_VALUE = 304; /** * <code>SOURCE_JS_ES6 = 305;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES6 * </pre> */ public static final int SOURCE_JS_ES6_VALUE = 305; /** * <code>SOURCE_JS_ES7 = 306;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES7 * </pre> */ public static final int SOURCE_JS_ES7_VALUE = 306; /** * <code>SOURCE_JS_ES8 = 307;</code> * * <pre> ** The file represents a JavaScript source file that parsed without error as ES8 * </pre> */ public static final int SOURCE_JS_ES8_VALUE = 307; /** * <code>JS_ERROR = 300;</code> * * <pre> ** @exclude * </pre> */ public static final int JS_ERROR_VALUE = 300; /** * <code>SOURCE_PHP_ERROR = 400;</code> * * <pre> ** The file represents a PHP source file that had a parse error * </pre> */ public static final int SOURCE_PHP_ERROR_VALUE = 400; /** * <code>SOURCE_PHP5 = 401;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES1 * </pre> */ public static final int SOURCE_PHP5_VALUE = 401; /** * <code>SOURCE_PHP5_3 = 402;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES2 * </pre> */ public static final int SOURCE_PHP5_3_VALUE = 402; /** * <code>SOURCE_PHP5_4 = 403;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES3 * </pre> */ public static final int SOURCE_PHP5_4_VALUE = 403; /** * <code>SOURCE_PHP5_5 = 404;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES5 * </pre> */ public static final int SOURCE_PHP5_5_VALUE = 404; /** * <code>SOURCE_PHP5_6 = 405;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES6 * </pre> */ public static final int SOURCE_PHP5_6_VALUE = 405; /** * <code>SOURCE_PHP7_0 = 406;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES7 * </pre> */ public static final int SOURCE_PHP7_0_VALUE = 406; /** * <code>SOURCE_PHP7_1 = 407;</code> * * <pre> ** The file represents a PHP source file that parsed without error as ES8 * </pre> */ public static final int SOURCE_PHP7_1_VALUE = 407; /** * <code>PHP_ERROR = 400;</code> * * <pre> ** @exclude * </pre> */ public static final int PHP_ERROR_VALUE = 400; /** * <code>SOURCE_HTML_ERROR = 500;</code> * * <pre> ** The file represents an HTML source file that had a parse error * </pre> */ public static final int SOURCE_HTML_ERROR_VALUE = 500; /** * <code>Source_HTML = 501;</code> * * <pre> ** The file represents an HTML source file that parsed without error * </pre> */ public static final int Source_HTML_VALUE = 501; /** * <code>HTML_ERROR = 500;</code> * * <pre> ** @exclude * </pre> */ public static final int HTML_ERROR_VALUE = 500; /** * <code>SOURCE_XML_ERROR = 600;</code> * * <pre> ** The file represents an XML source file that had a parse error * </pre> */ public static final int SOURCE_XML_ERROR_VALUE = 600; /** * <code>Source_XML = 601;</code> * * <pre> ** The file represents an HTML source file that parsed without error * </pre> */ public static final int Source_XML_VALUE = 601; /** * <code>XML_ERROR = 600;</code> * * <pre> ** @exclude * </pre> */ public static final int XML_ERROR_VALUE = 600; /** * <code>SOURCE_CSS_ERROR = 700;</code> * * <pre> ** The file represents an CSS source file that had a parse error * </pre> */ public static final int SOURCE_CSS_ERROR_VALUE = 700; /** * <code>Source_CSS = 701;</code> * * <pre> ** The file represents an CSS source file that parsed without error * </pre> */ public static final int Source_CSS_VALUE = 701; /** * <code>CSS_ERROR = 700;</code> * * <pre> ** @exclude * </pre> */ public static final int CSS_ERROR_VALUE = 700; public final int getNumber() { return value; } public static FileKind valueOf(int value) { switch (value) { case 0: return OTHER; case 1: return BINARY; case 2: return TEXT; case 3: return XML; case 100: return SOURCE_JAVA_ERROR; case 102: return SOURCE_JAVA_JLS2; case 103: return SOURCE_JAVA_JLS3; case 104: return SOURCE_JAVA_JLS4; case 108: return SOURCE_JAVA_JLS8; case 200: return SOURCE_CS_ERROR; case 201: return SOURCE_CS_CS1; case 202: return SOURCE_CS_CS2; case 203: return SOURCE_CS_CS3; case 204: return SOURCE_CS_CS4; case 205: return SOURCE_CS_CS5; case 300: return SOURCE_JS_ERROR; case 301: return SOURCE_JS_ES1; case 302: return SOURCE_JS_ES2; case 303: return SOURCE_JS_ES3; case 304: return SOURCE_JS_ES5; case 305: return SOURCE_JS_ES6; case 306: return SOURCE_JS_ES7; case 307: return SOURCE_JS_ES8; case 400: return SOURCE_PHP_ERROR; case 401: return SOURCE_PHP5; case 402: return SOURCE_PHP5_3; case 403: return SOURCE_PHP5_4; case 404: return SOURCE_PHP5_5; case 405: return SOURCE_PHP5_6; case 406: return SOURCE_PHP7_0; case 407: return SOURCE_PHP7_1; case 500: return SOURCE_HTML_ERROR; case 501: return Source_HTML; case 600: return SOURCE_XML_ERROR; case 601: return Source_XML; case 700: return SOURCE_CSS_ERROR; case 701: return Source_CSS; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<FileKind> internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap<FileKind> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<FileKind>() { public FileKind findValueByNumber(int number) { return FileKind.valueOf(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return boa.types.Diff.ChangedFile.getDescriptor().getEnumTypes().get(0); } private static final FileKind[] VALUES = { OTHER, BINARY, TEXT, XML, SOURCE_JAVA_ERROR, SOURCE_JAVA_JLS2, SOURCE_JAVA_JLS3, SOURCE_JAVA_JLS4, SOURCE_JAVA_JLS8, JAVA_ERROR, JLS2, JLS3, JLS4, JLS8, SOURCE_CS_ERROR, SOURCE_CS_CS1, SOURCE_CS_CS2, SOURCE_CS_CS3, SOURCE_CS_CS4, SOURCE_CS_CS5, CS_ERROR, CS1, CS2, CS3, CS4, CS5, SOURCE_JS_ERROR, SOURCE_JS_ES1, SOURCE_JS_ES2, SOURCE_JS_ES3, SOURCE_JS_ES5, SOURCE_JS_ES6, SOURCE_JS_ES7, SOURCE_JS_ES8, JS_ERROR, SOURCE_PHP_ERROR, SOURCE_PHP5, SOURCE_PHP5_3, SOURCE_PHP5_4, SOURCE_PHP5_5, SOURCE_PHP5_6, SOURCE_PHP7_0, SOURCE_PHP7_1, PHP_ERROR, SOURCE_HTML_ERROR, Source_HTML, HTML_ERROR, SOURCE_XML_ERROR, Source_XML, XML_ERROR, SOURCE_CSS_ERROR, Source_CSS, CSS_ERROR, }; public static FileKind valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private FileKind(int index, int value) { this.index = index; this.value = value; } // @@protoc_insertion_point(enum_scope:boa.types.ChangedFile.FileKind) } private int bitField0_; // required .boa.types.ChangeKind change = 1; public static final int CHANGE_FIELD_NUMBER = 1; private boa.types.Shared.ChangeKind change_; /** * <code>required .boa.types.ChangeKind change = 1;</code> * * <pre> ** The kind of change for this file * </pre> */ public boolean hasChange() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .boa.types.ChangeKind change = 1;</code> * * <pre> ** The kind of change for this file * </pre> */ public boa.types.Shared.ChangeKind getChange() { return change_; } // required .boa.types.ChangedFile.FileKind kind = 2; public static final int KIND_FIELD_NUMBER = 2; private boa.types.Diff.ChangedFile.FileKind kind_; /** * <code>required .boa.types.ChangedFile.FileKind kind = 2;</code> * * <pre> ** The kind of file * </pre> */ public boolean hasKind() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required .boa.types.ChangedFile.FileKind kind = 2;</code> * * <pre> ** The kind of file * </pre> */ public boa.types.Diff.ChangedFile.FileKind getKind() { return kind_; } // required string name = 3; public static final int NAME_FIELD_NUMBER = 3; private java.lang.Object name_; /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public boolean hasName() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } } /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // required uint64 key = 4; public static final int KEY_FIELD_NUMBER = 4; private long key_; /** * <code>required uint64 key = 4;</code> * * <pre> ** @exclude * </pre> */ public boolean hasKey() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>required uint64 key = 4;</code> * * <pre> ** @exclude * </pre> */ public long getKey() { return key_; } // required bool ast = 5; public static final int AST_FIELD_NUMBER = 5; private boolean ast_; /** * <code>required bool ast = 5;</code> * * <pre> ** @exclude Indicates if this file has a corresponding parsed AST or not * </pre> */ public boolean hasAst() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>required bool ast = 5;</code> * * <pre> ** @exclude Indicates if this file has a corresponding parsed AST or not * </pre> */ public boolean getAst() { return ast_; } // optional .boa.types.CommentsRoot comments = 6; public static final int COMMENTS_FIELD_NUMBER = 6; private boa.types.Ast.CommentsRoot comments_; /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public boolean hasComments() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public boa.types.Ast.CommentsRoot getComments() { return comments_; } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public boa.types.Ast.CommentsRootOrBuilder getCommentsOrBuilder() { return comments_; } // repeated .boa.types.ChangeKind changes = 7; public static final int CHANGES_FIELD_NUMBER = 7; private java.util.List<boa.types.Shared.ChangeKind> changes_; /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public java.util.List<boa.types.Shared.ChangeKind> getChangesList() { return changes_; } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public int getChangesCount() { return changes_.size(); } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public boa.types.Shared.ChangeKind getChanges(int index) { return changes_.get(index); } // repeated string previous_names = 8; public static final int PREVIOUS_NAMES_FIELD_NUMBER = 8; private com.google.protobuf.LazyStringList previousNames_; /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public java.util.List<java.lang.String> getPreviousNamesList() { return previousNames_; } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public int getPreviousNamesCount() { return previousNames_.size(); } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public java.lang.String getPreviousNames(int index) { return previousNames_.get(index); } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public com.google.protobuf.ByteString getPreviousNamesBytes(int index) { return previousNames_.getByteString(index); } // repeated int32 previous_versions = 9; public static final int PREVIOUS_VERSIONS_FIELD_NUMBER = 9; private java.util.List<java.lang.Integer> previousVersions_; /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public java.util.List<java.lang.Integer> getPreviousVersionsList() { return previousVersions_; } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public int getPreviousVersionsCount() { return previousVersions_.size(); } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public int getPreviousVersions(int index) { return previousVersions_.get(index); } // repeated int32 previous_indices = 10; public static final int PREVIOUS_INDICES_FIELD_NUMBER = 10; private java.util.List<java.lang.Integer> previousIndices_; /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public java.util.List<java.lang.Integer> getPreviousIndicesList() { return previousIndices_; } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public int getPreviousIndicesCount() { return previousIndices_.size(); } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public int getPreviousIndices(int index) { return previousIndices_.get(index); } private void initFields() { change_ = boa.types.Shared.ChangeKind.UNKNOWN; kind_ = boa.types.Diff.ChangedFile.FileKind.OTHER; name_ = ""; key_ = 0L; ast_ = false; comments_ = boa.types.Ast.CommentsRoot.getDefaultInstance(); changes_ = java.util.Collections.emptyList(); previousNames_ = com.google.protobuf.LazyStringArrayList.EMPTY; previousVersions_ = java.util.Collections.emptyList(); previousIndices_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasChange()) { memoizedIsInitialized = 0; return false; } if (!hasKind()) { memoizedIsInitialized = 0; return false; } if (!hasName()) { memoizedIsInitialized = 0; return false; } if (!hasKey()) { memoizedIsInitialized = 0; return false; } if (!hasAst()) { memoizedIsInitialized = 0; return false; } if (hasComments()) { if (!getComments().isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeEnum(1, change_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeEnum(2, kind_.getNumber()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getNameBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeUInt64(4, key_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeBool(5, ast_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeMessage(6, comments_); } for (int i = 0; i < changes_.size(); i++) { output.writeEnum(7, changes_.get(i).getNumber()); } for (int i = 0; i < previousNames_.size(); i++) { output.writeBytes(8, previousNames_.getByteString(i)); } for (int i = 0; i < previousVersions_.size(); i++) { output.writeInt32(9, previousVersions_.get(i)); } for (int i = 0; i < previousIndices_.size(); i++) { output.writeInt32(10, previousIndices_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, change_.getNumber()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, kind_.getNumber()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getNameBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, key_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(5, ast_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(6, comments_); } { int dataSize = 0; for (int i = 0; i < changes_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeEnumSizeNoTag(changes_.get(i).getNumber()); } size += dataSize; size += 1 * changes_.size(); } { int dataSize = 0; for (int i = 0; i < previousNames_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(previousNames_.getByteString(i)); } size += dataSize; size += 1 * getPreviousNamesList().size(); } { int dataSize = 0; for (int i = 0; i < previousVersions_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(previousVersions_.get(i)); } size += dataSize; size += 1 * getPreviousVersionsList().size(); } { int dataSize = 0; for (int i = 0; i < previousIndices_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeInt32SizeNoTag(previousIndices_.get(i)); } size += dataSize; size += 1 * getPreviousIndicesList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static boa.types.Diff.ChangedFile parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static boa.types.Diff.ChangedFile parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static boa.types.Diff.ChangedFile parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static boa.types.Diff.ChangedFile parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static boa.types.Diff.ChangedFile parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static boa.types.Diff.ChangedFile parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static boa.types.Diff.ChangedFile parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static boa.types.Diff.ChangedFile parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static boa.types.Diff.ChangedFile parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static boa.types.Diff.ChangedFile parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(boa.types.Diff.ChangedFile prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code boa.types.ChangedFile} * * <pre> ** A file committed in a Revision * </pre> */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements boa.types.Diff.ChangedFileOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return boa.types.Diff.internal_static_boa_types_ChangedFile_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return boa.types.Diff.internal_static_boa_types_ChangedFile_fieldAccessorTable .ensureFieldAccessorsInitialized( boa.types.Diff.ChangedFile.class, boa.types.Diff.ChangedFile.Builder.class); } // Construct using boa.types.Diff.ChangedFile.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getCommentsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); change_ = boa.types.Shared.ChangeKind.UNKNOWN; bitField0_ = (bitField0_ & ~0x00000001); kind_ = boa.types.Diff.ChangedFile.FileKind.OTHER; bitField0_ = (bitField0_ & ~0x00000002); name_ = ""; bitField0_ = (bitField0_ & ~0x00000004); key_ = 0L; bitField0_ = (bitField0_ & ~0x00000008); ast_ = false; bitField0_ = (bitField0_ & ~0x00000010); if (commentsBuilder_ == null) { comments_ = boa.types.Ast.CommentsRoot.getDefaultInstance(); } else { commentsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000020); changes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); previousNames_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000080); previousVersions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000100); previousIndices_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000200); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return boa.types.Diff.internal_static_boa_types_ChangedFile_descriptor; } public boa.types.Diff.ChangedFile getDefaultInstanceForType() { return boa.types.Diff.ChangedFile.getDefaultInstance(); } public boa.types.Diff.ChangedFile build() { boa.types.Diff.ChangedFile result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public boa.types.Diff.ChangedFile buildPartial() { boa.types.Diff.ChangedFile result = new boa.types.Diff.ChangedFile(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.change_ = change_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.kind_ = kind_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.name_ = name_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.key_ = key_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.ast_ = ast_; if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000020; } if (commentsBuilder_ == null) { result.comments_ = comments_; } else { result.comments_ = commentsBuilder_.build(); } if (((bitField0_ & 0x00000040) == 0x00000040)) { changes_ = java.util.Collections.unmodifiableList(changes_); bitField0_ = (bitField0_ & ~0x00000040); } result.changes_ = changes_; if (((bitField0_ & 0x00000080) == 0x00000080)) { previousNames_ = new com.google.protobuf.UnmodifiableLazyStringList( previousNames_); bitField0_ = (bitField0_ & ~0x00000080); } result.previousNames_ = previousNames_; if (((bitField0_ & 0x00000100) == 0x00000100)) { previousVersions_ = java.util.Collections.unmodifiableList(previousVersions_); bitField0_ = (bitField0_ & ~0x00000100); } result.previousVersions_ = previousVersions_; if (((bitField0_ & 0x00000200) == 0x00000200)) { previousIndices_ = java.util.Collections.unmodifiableList(previousIndices_); bitField0_ = (bitField0_ & ~0x00000200); } result.previousIndices_ = previousIndices_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof boa.types.Diff.ChangedFile) { return mergeFrom((boa.types.Diff.ChangedFile)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(boa.types.Diff.ChangedFile other) { if (other == boa.types.Diff.ChangedFile.getDefaultInstance()) return this; if (other.hasChange()) { setChange(other.getChange()); } if (other.hasKind()) { setKind(other.getKind()); } if (other.hasName()) { bitField0_ |= 0x00000004; name_ = other.name_; onChanged(); } if (other.hasKey()) { setKey(other.getKey()); } if (other.hasAst()) { setAst(other.getAst()); } if (other.hasComments()) { mergeComments(other.getComments()); } if (!other.changes_.isEmpty()) { if (changes_.isEmpty()) { changes_ = other.changes_; bitField0_ = (bitField0_ & ~0x00000040); } else { ensureChangesIsMutable(); changes_.addAll(other.changes_); } onChanged(); } if (!other.previousNames_.isEmpty()) { if (previousNames_.isEmpty()) { previousNames_ = other.previousNames_; bitField0_ = (bitField0_ & ~0x00000080); } else { ensurePreviousNamesIsMutable(); previousNames_.addAll(other.previousNames_); } onChanged(); } if (!other.previousVersions_.isEmpty()) { if (previousVersions_.isEmpty()) { previousVersions_ = other.previousVersions_; bitField0_ = (bitField0_ & ~0x00000100); } else { ensurePreviousVersionsIsMutable(); previousVersions_.addAll(other.previousVersions_); } onChanged(); } if (!other.previousIndices_.isEmpty()) { if (previousIndices_.isEmpty()) { previousIndices_ = other.previousIndices_; bitField0_ = (bitField0_ & ~0x00000200); } else { ensurePreviousIndicesIsMutable(); previousIndices_.addAll(other.previousIndices_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasChange()) { return false; } if (!hasKind()) { return false; } if (!hasName()) { return false; } if (!hasKey()) { return false; } if (!hasAst()) { return false; } if (hasComments()) { if (!getComments().isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { boa.types.Diff.ChangedFile parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (boa.types.Diff.ChangedFile) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required .boa.types.ChangeKind change = 1; private boa.types.Shared.ChangeKind change_ = boa.types.Shared.ChangeKind.UNKNOWN; /** * <code>required .boa.types.ChangeKind change = 1;</code> * * <pre> ** The kind of change for this file * </pre> */ public boolean hasChange() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required .boa.types.ChangeKind change = 1;</code> * * <pre> ** The kind of change for this file * </pre> */ public boa.types.Shared.ChangeKind getChange() { return change_; } /** * <code>required .boa.types.ChangeKind change = 1;</code> * * <pre> ** The kind of change for this file * </pre> */ public Builder setChange(boa.types.Shared.ChangeKind value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; change_ = value; onChanged(); return this; } /** * <code>required .boa.types.ChangeKind change = 1;</code> * * <pre> ** The kind of change for this file * </pre> */ public Builder clearChange() { bitField0_ = (bitField0_ & ~0x00000001); change_ = boa.types.Shared.ChangeKind.UNKNOWN; onChanged(); return this; } // required .boa.types.ChangedFile.FileKind kind = 2; private boa.types.Diff.ChangedFile.FileKind kind_ = boa.types.Diff.ChangedFile.FileKind.OTHER; /** * <code>required .boa.types.ChangedFile.FileKind kind = 2;</code> * * <pre> ** The kind of file * </pre> */ public boolean hasKind() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required .boa.types.ChangedFile.FileKind kind = 2;</code> * * <pre> ** The kind of file * </pre> */ public boa.types.Diff.ChangedFile.FileKind getKind() { return kind_; } /** * <code>required .boa.types.ChangedFile.FileKind kind = 2;</code> * * <pre> ** The kind of file * </pre> */ public Builder setKind(boa.types.Diff.ChangedFile.FileKind value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; kind_ = value; onChanged(); return this; } /** * <code>required .boa.types.ChangedFile.FileKind kind = 2;</code> * * <pre> ** The kind of file * </pre> */ public Builder clearKind() { bitField0_ = (bitField0_ & ~0x00000002); kind_ = boa.types.Diff.ChangedFile.FileKind.OTHER; onChanged(); return this; } // required string name = 3; private java.lang.Object name_ = ""; /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public boolean hasName() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; name_ = value; onChanged(); return this; } /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public Builder clearName() { bitField0_ = (bitField0_ & ~0x00000004); name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>required string name = 3;</code> * * <pre> ** The full name and path of the file * </pre> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; name_ = value; onChanged(); return this; } // required uint64 key = 4; private long key_ ; /** * <code>required uint64 key = 4;</code> * * <pre> ** @exclude * </pre> */ public boolean hasKey() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>required uint64 key = 4;</code> * * <pre> ** @exclude * </pre> */ public long getKey() { return key_; } /** * <code>required uint64 key = 4;</code> * * <pre> ** @exclude * </pre> */ public Builder setKey(long value) { bitField0_ |= 0x00000008; key_ = value; onChanged(); return this; } /** * <code>required uint64 key = 4;</code> * * <pre> ** @exclude * </pre> */ public Builder clearKey() { bitField0_ = (bitField0_ & ~0x00000008); key_ = 0L; onChanged(); return this; } // required bool ast = 5; private boolean ast_ ; /** * <code>required bool ast = 5;</code> * * <pre> ** @exclude Indicates if this file has a corresponding parsed AST or not * </pre> */ public boolean hasAst() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>required bool ast = 5;</code> * * <pre> ** @exclude Indicates if this file has a corresponding parsed AST or not * </pre> */ public boolean getAst() { return ast_; } /** * <code>required bool ast = 5;</code> * * <pre> ** @exclude Indicates if this file has a corresponding parsed AST or not * </pre> */ public Builder setAst(boolean value) { bitField0_ |= 0x00000010; ast_ = value; onChanged(); return this; } /** * <code>required bool ast = 5;</code> * * <pre> ** @exclude Indicates if this file has a corresponding parsed AST or not * </pre> */ public Builder clearAst() { bitField0_ = (bitField0_ & ~0x00000010); ast_ = false; onChanged(); return this; } // optional .boa.types.CommentsRoot comments = 6; private boa.types.Ast.CommentsRoot comments_ = boa.types.Ast.CommentsRoot.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< boa.types.Ast.CommentsRoot, boa.types.Ast.CommentsRoot.Builder, boa.types.Ast.CommentsRootOrBuilder> commentsBuilder_; /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public boolean hasComments() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public boa.types.Ast.CommentsRoot getComments() { if (commentsBuilder_ == null) { return comments_; } else { return commentsBuilder_.getMessage(); } } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public Builder setComments(boa.types.Ast.CommentsRoot value) { if (commentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } comments_ = value; onChanged(); } else { commentsBuilder_.setMessage(value); } bitField0_ |= 0x00000020; return this; } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public Builder setComments( boa.types.Ast.CommentsRoot.Builder builderForValue) { if (commentsBuilder_ == null) { comments_ = builderForValue.build(); onChanged(); } else { commentsBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000020; return this; } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public Builder mergeComments(boa.types.Ast.CommentsRoot value) { if (commentsBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020) && comments_ != boa.types.Ast.CommentsRoot.getDefaultInstance()) { comments_ = boa.types.Ast.CommentsRoot.newBuilder(comments_).mergeFrom(value).buildPartial(); } else { comments_ = value; } onChanged(); } else { commentsBuilder_.mergeFrom(value); } bitField0_ |= 0x00000020; return this; } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public Builder clearComments() { if (commentsBuilder_ == null) { comments_ = boa.types.Ast.CommentsRoot.getDefaultInstance(); onChanged(); } else { commentsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000020); return this; } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public boa.types.Ast.CommentsRoot.Builder getCommentsBuilder() { bitField0_ |= 0x00000020; onChanged(); return getCommentsFieldBuilder().getBuilder(); } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ public boa.types.Ast.CommentsRootOrBuilder getCommentsOrBuilder() { if (commentsBuilder_ != null) { return commentsBuilder_.getMessageOrBuilder(); } else { return comments_; } } /** * <code>optional .boa.types.CommentsRoot comments = 6;</code> * * <pre> ** @exclude * </pre> */ private com.google.protobuf.SingleFieldBuilder< boa.types.Ast.CommentsRoot, boa.types.Ast.CommentsRoot.Builder, boa.types.Ast.CommentsRootOrBuilder> getCommentsFieldBuilder() { if (commentsBuilder_ == null) { commentsBuilder_ = new com.google.protobuf.SingleFieldBuilder< boa.types.Ast.CommentsRoot, boa.types.Ast.CommentsRoot.Builder, boa.types.Ast.CommentsRootOrBuilder>( comments_, getParentForChildren(), isClean()); comments_ = null; } return commentsBuilder_; } // repeated .boa.types.ChangeKind changes = 7; private java.util.List<boa.types.Shared.ChangeKind> changes_ = java.util.Collections.emptyList(); private void ensureChangesIsMutable() { if (!((bitField0_ & 0x00000040) == 0x00000040)) { changes_ = new java.util.ArrayList<boa.types.Shared.ChangeKind>(changes_); bitField0_ |= 0x00000040; } } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public java.util.List<boa.types.Shared.ChangeKind> getChangesList() { return java.util.Collections.unmodifiableList(changes_); } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public int getChangesCount() { return changes_.size(); } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public boa.types.Shared.ChangeKind getChanges(int index) { return changes_.get(index); } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder setChanges( int index, boa.types.Shared.ChangeKind value) { if (value == null) { throw new NullPointerException(); } ensureChangesIsMutable(); changes_.set(index, value); onChanged(); return this; } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder addChanges(boa.types.Shared.ChangeKind value) { if (value == null) { throw new NullPointerException(); } ensureChangesIsMutable(); changes_.add(value); onChanged(); return this; } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder addAllChanges( java.lang.Iterable<? extends boa.types.Shared.ChangeKind> values) { ensureChangesIsMutable(); super.addAll(values, changes_); onChanged(); return this; } /** * <code>repeated .boa.types.ChangeKind changes = 7;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder clearChanges() { changes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000040); onChanged(); return this; } // repeated string previous_names = 8; private com.google.protobuf.LazyStringList previousNames_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensurePreviousNamesIsMutable() { if (!((bitField0_ & 0x00000080) == 0x00000080)) { previousNames_ = new com.google.protobuf.LazyStringArrayList(previousNames_); bitField0_ |= 0x00000080; } } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public java.util.List<java.lang.String> getPreviousNamesList() { return java.util.Collections.unmodifiableList(previousNames_); } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public int getPreviousNamesCount() { return previousNames_.size(); } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public java.lang.String getPreviousNames(int index) { return previousNames_.get(index); } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public com.google.protobuf.ByteString getPreviousNamesBytes(int index) { return previousNames_.getByteString(index); } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder setPreviousNames( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePreviousNamesIsMutable(); previousNames_.set(index, value); onChanged(); return this; } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder addPreviousNames( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePreviousNamesIsMutable(); previousNames_.add(value); onChanged(); return this; } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder addAllPreviousNames( java.lang.Iterable<java.lang.String> values) { ensurePreviousNamesIsMutable(); super.addAll(values, previousNames_); onChanged(); return this; } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder clearPreviousNames() { previousNames_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000080); onChanged(); return this; } /** * <code>repeated string previous_names = 8;</code> * * <pre> ** The kinds of changes of this this compared to the corresponding parent commits * </pre> */ public Builder addPreviousNamesBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensurePreviousNamesIsMutable(); previousNames_.add(value); onChanged(); return this; } // repeated int32 previous_versions = 9; private java.util.List<java.lang.Integer> previousVersions_ = java.util.Collections.emptyList(); private void ensurePreviousVersionsIsMutable() { if (!((bitField0_ & 0x00000100) == 0x00000100)) { previousVersions_ = new java.util.ArrayList<java.lang.Integer>(previousVersions_); bitField0_ |= 0x00000100; } } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public java.util.List<java.lang.Integer> getPreviousVersionsList() { return java.util.Collections.unmodifiableList(previousVersions_); } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public int getPreviousVersionsCount() { return previousVersions_.size(); } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public int getPreviousVersions(int index) { return previousVersions_.get(index); } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public Builder setPreviousVersions( int index, int value) { ensurePreviousVersionsIsMutable(); previousVersions_.set(index, value); onChanged(); return this; } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public Builder addPreviousVersions(int value) { ensurePreviousVersionsIsMutable(); previousVersions_.add(value); onChanged(); return this; } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public Builder addAllPreviousVersions( java.lang.Iterable<? extends java.lang.Integer> values) { ensurePreviousVersionsIsMutable(); super.addAll(values, previousVersions_); onChanged(); return this; } /** * <code>repeated int32 previous_versions = 9;</code> * * <pre> ** @exclude The indices of the corresponding parent commits in the list of all commits * </pre> */ public Builder clearPreviousVersions() { previousVersions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000100); onChanged(); return this; } // repeated int32 previous_indices = 10; private java.util.List<java.lang.Integer> previousIndices_ = java.util.Collections.emptyList(); private void ensurePreviousIndicesIsMutable() { if (!((bitField0_ & 0x00000200) == 0x00000200)) { previousIndices_ = new java.util.ArrayList<java.lang.Integer>(previousIndices_); bitField0_ |= 0x00000200; } } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public java.util.List<java.lang.Integer> getPreviousIndicesList() { return java.util.Collections.unmodifiableList(previousIndices_); } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public int getPreviousIndicesCount() { return previousIndices_.size(); } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public int getPreviousIndices(int index) { return previousIndices_.get(index); } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public Builder setPreviousIndices( int index, int value) { ensurePreviousIndicesIsMutable(); previousIndices_.set(index, value); onChanged(); return this; } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public Builder addPreviousIndices(int value) { ensurePreviousIndicesIsMutable(); previousIndices_.add(value); onChanged(); return this; } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public Builder addAllPreviousIndices( java.lang.Iterable<? extends java.lang.Integer> values) { ensurePreviousIndicesIsMutable(); super.addAll(values, previousIndices_); onChanged(); return this; } /** * <code>repeated int32 previous_indices = 10;</code> * * <pre> ** @exclude The indices of the previous files in the list of changed files of the corresponding parent commits * </pre> */ public Builder clearPreviousIndices() { previousIndices_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000200); onChanged(); return this; } // @@protoc_insertion_point(builder_scope:boa.types.ChangedFile) } static { defaultInstance = new ChangedFile(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:boa.types.ChangedFile) } private static com.google.protobuf.Descriptors.Descriptor internal_static_boa_types_ChangedFile_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_boa_types_ChangedFile_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\ndiff.proto\022\tboa.types\032\014shared.proto\032\ta" + "st.proto\"\325\t\n\013ChangedFile\022%\n\006change\030\001 \002(\016" + "2\025.boa.types.ChangeKind\022-\n\004kind\030\002 \002(\0162\037." + "boa.types.ChangedFile.FileKind\022\014\n\004name\030\003" + " \002(\t\022\013\n\003key\030\004 \002(\004\022\013\n\003ast\030\005 \002(\010\022)\n\010commen" + "ts\030\006 \001(\0132\027.boa.types.CommentsRoot\022&\n\007cha" + "nges\030\007 \003(\0162\025.boa.types.ChangeKind\022\026\n\016pre" + "vious_names\030\010 \003(\t\022\031\n\021previous_versions\030\t" + " \003(\005\022\030\n\020previous_indices\030\n \003(\005\"\247\007\n\010FileK" + "ind\022\t\n\005OTHER\020\000\022\n\n\006BINARY\020\001\022\010\n\004TEXT\020\002\022\007\n\003", "XML\020\003\022\025\n\021SOURCE_JAVA_ERROR\020d\022\024\n\020SOURCE_J" + "AVA_JLS2\020f\022\024\n\020SOURCE_JAVA_JLS3\020g\022\024\n\020SOUR" + "CE_JAVA_JLS4\020h\022\024\n\020SOURCE_JAVA_JLS8\020l\022\016\n\n" + "JAVA_ERROR\020d\022\010\n\004JLS2\020f\022\010\n\004JLS3\020g\022\010\n\004JLS4" + "\020h\022\010\n\004JLS8\020l\022\024\n\017SOURCE_CS_ERROR\020\310\001\022\022\n\rSO" + "URCE_CS_CS1\020\311\001\022\022\n\rSOURCE_CS_CS2\020\312\001\022\022\n\rSO" + "URCE_CS_CS3\020\313\001\022\022\n\rSOURCE_CS_CS4\020\314\001\022\022\n\rSO" + "URCE_CS_CS5\020\315\001\022\r\n\010CS_ERROR\020\310\001\022\010\n\003CS1\020\311\001\022" + "\010\n\003CS2\020\312\001\022\010\n\003CS3\020\313\001\022\010\n\003CS4\020\314\001\022\010\n\003CS5\020\315\001\022" + "\024\n\017SOURCE_JS_ERROR\020\254\002\022\022\n\rSOURCE_JS_ES1\020\255", "\002\022\022\n\rSOURCE_JS_ES2\020\256\002\022\022\n\rSOURCE_JS_ES3\020\257" + "\002\022\022\n\rSOURCE_JS_ES5\020\260\002\022\022\n\rSOURCE_JS_ES6\020\261" + "\002\022\022\n\rSOURCE_JS_ES7\020\262\002\022\022\n\rSOURCE_JS_ES8\020\263" + "\002\022\r\n\010JS_ERROR\020\254\002\022\025\n\020SOURCE_PHP_ERROR\020\220\003\022" + "\020\n\013SOURCE_PHP5\020\221\003\022\022\n\rSOURCE_PHP5_3\020\222\003\022\022\n" + "\rSOURCE_PHP5_4\020\223\003\022\022\n\rSOURCE_PHP5_5\020\224\003\022\022\n" + "\rSOURCE_PHP5_6\020\225\003\022\022\n\rSOURCE_PHP7_0\020\226\003\022\022\n" + "\rSOURCE_PHP7_1\020\227\003\022\016\n\tPHP_ERROR\020\220\003\022\026\n\021SOU" + "RCE_HTML_ERROR\020\364\003\022\020\n\013Source_HTML\020\365\003\022\017\n\nH" + "TML_ERROR\020\364\003\022\025\n\020SOURCE_XML_ERROR\020\330\004\022\017\n\nS", "ource_XML\020\331\004\022\016\n\tXML_ERROR\020\330\004\022\025\n\020SOURCE_C" + "SS_ERROR\020\274\005\022\017\n\nSource_CSS\020\275\005\022\016\n\tCSS_ERRO" + "R\020\274\005\032\002\020\001B\002H\001" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_boa_types_ChangedFile_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_boa_types_ChangedFile_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_boa_types_ChangedFile_descriptor, new java.lang.String[] { "Change", "Kind", "Name", "Key", "Ast", "Comments", "Changes", "PreviousNames", "PreviousVersions", "PreviousIndices", }); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { boa.types.Shared.getDescriptor(), boa.types.Ast.getDescriptor(), }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
apache-2.0
gawkermedia/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201602/ContentMetadataKeyHierarchyTargeting.java
6120
/** * ContentMetadataKeyHierarchyTargeting.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201602; /** * Represents one or more {@link CustomTargetingValue custom targeting * values} from different * {@link CustomTargetingKey custom targeting keys} ANDed * together. */ public class ContentMetadataKeyHierarchyTargeting implements java.io.Serializable { /* The list of IDs of the targeted {@link CustomTargetingValue} * objects that are ANDed together. * <p>Targeting values do not need to be in the order * of the hierarchy levels. For example, * if the hierarchy is "show > season > genre" the values * could be * "season=3, show=30rock, genre=comedy." */ private long[] customTargetingValueIds; public ContentMetadataKeyHierarchyTargeting() { } public ContentMetadataKeyHierarchyTargeting( long[] customTargetingValueIds) { this.customTargetingValueIds = customTargetingValueIds; } /** * Gets the customTargetingValueIds value for this ContentMetadataKeyHierarchyTargeting. * * @return customTargetingValueIds * The list of IDs of the targeted {@link CustomTargetingValue} * objects that are ANDed together. * <p>Targeting values do not need to be in the order * of the hierarchy levels. For example, * if the hierarchy is "show > season > genre" the values * could be * "season=3, show=30rock, genre=comedy." */ public long[] getCustomTargetingValueIds() { return customTargetingValueIds; } /** * Sets the customTargetingValueIds value for this ContentMetadataKeyHierarchyTargeting. * * @param customTargetingValueIds * The list of IDs of the targeted {@link CustomTargetingValue} * objects that are ANDed together. * <p>Targeting values do not need to be in the order * of the hierarchy levels. For example, * if the hierarchy is "show > season > genre" the values * could be * "season=3, show=30rock, genre=comedy." */ public void setCustomTargetingValueIds(long[] customTargetingValueIds) { this.customTargetingValueIds = customTargetingValueIds; } public long getCustomTargetingValueIds(int i) { return this.customTargetingValueIds[i]; } public void setCustomTargetingValueIds(int i, long _value) { this.customTargetingValueIds[i] = _value; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof ContentMetadataKeyHierarchyTargeting)) return false; ContentMetadataKeyHierarchyTargeting other = (ContentMetadataKeyHierarchyTargeting) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.customTargetingValueIds==null && other.getCustomTargetingValueIds()==null) || (this.customTargetingValueIds!=null && java.util.Arrays.equals(this.customTargetingValueIds, other.getCustomTargetingValueIds()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getCustomTargetingValueIds() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getCustomTargetingValueIds()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getCustomTargetingValueIds(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ContentMetadataKeyHierarchyTargeting.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "ContentMetadataKeyHierarchyTargeting")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("customTargetingValueIds"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "customTargetingValueIds")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setMaxOccursUnbounded(true); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
chirino/activemq
activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/QueuePurgeTest.java
11485
/** * 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.activemq.broker.region; import java.io.File; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.CombinationTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.jmx.QueueViewMBean; import org.apache.activemq.broker.region.policy.FilePendingQueueMessageStoragePolicy; import org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; import org.apache.activemq.util.DefaultTestAppender; import org.apache.log4j.Appender; import org.apache.log4j.Level; import org.apache.log4j.spi.LoggingEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class QueuePurgeTest extends CombinationTestSupport { private static final Logger LOG = LoggerFactory.getLogger(QueuePurgeTest.class); private static final int NUM_TO_SEND = 20000; private final String MESSAGE_TEXT = new String(new byte[1024]); BrokerService broker; ConnectionFactory factory; Connection connection; Session session; Queue queue; MessageConsumer consumer; @Override protected void setUp() throws Exception { setMaxTestTime(10*60*1000); // 10 mins setAutoFail(true); super.setUp(); broker = new BrokerService(); File testDataDir = new File("target/activemq-data/QueuePurgeTest"); broker.setDataDirectoryFile(testDataDir); broker.setUseJmx(true); broker.setDeleteAllMessagesOnStartup(true); broker.getSystemUsage().getMemoryUsage().setLimit(1024l*1024*64); KahaDBPersistenceAdapter persistenceAdapter = new KahaDBPersistenceAdapter(); persistenceAdapter.setDirectory(new File(testDataDir, "kahadb")); broker.setPersistenceAdapter(persistenceAdapter); broker.addConnector("tcp://localhost:0"); broker.start(); factory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getConnectUri().toString()); connection = factory.createConnection(); connection.start(); } @Override protected void tearDown() throws Exception { super.tearDown(); if (consumer != null) { consumer.close(); } session.close(); connection.stop(); connection.close(); broker.stop(); } public void testPurgeLargeQueue() throws Exception { testPurgeLargeQueue(false); } public void testPurgeLargeQueuePrioritizedMessages() throws Exception { testPurgeLargeQueue(true); } private void testPurgeLargeQueue(boolean prioritizedMessages) throws Exception { applyBrokerSpoolingPolicy(prioritizedMessages); createProducerAndSendMessages(NUM_TO_SEND); QueueViewMBean proxy = getProxyToQueueViewMBean(); LOG.info("purging.."); org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getLogger(org.apache.activemq.broker.jmx.QueueView.class); final AtomicBoolean gotPurgeLogMessage = new AtomicBoolean(false); Appender appender = new DefaultTestAppender() { @Override public void doAppend(LoggingEvent event) { if (event.getMessage() instanceof String) { String message = (String) event.getMessage(); if (message.contains("purge of " + NUM_TO_SEND +" messages")) { LOG.info("Received a log message: {} ", event.getMessage()); gotPurgeLogMessage.set(true); } } } }; Level level = log4jLogger.getLevel(); log4jLogger.setLevel(Level.INFO); log4jLogger.addAppender(appender); try { proxy.purge(); } finally { log4jLogger.setLevel(level); log4jLogger.removeAppender(appender); } assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, proxy.getQueueSize()); assertTrue("cache is disabled, temp store being used", !proxy.isCacheEnabled()); assertTrue("got expected info purge log message", gotPurgeLogMessage.get()); assertEquals("Found messages when browsing", 0, proxy.browseMessages().size()); } public void testRepeatedExpiryProcessingOfLargeQueue() throws Exception { applyBrokerSpoolingPolicy(false); final int expiryPeriod = 500; applyExpiryDuration(expiryPeriod); createProducerAndSendMessages(NUM_TO_SEND); QueueViewMBean proxy = getProxyToQueueViewMBean(); LOG.info("waiting for expiry to kick in a bunch of times to verify it does not blow mem"); Thread.sleep(5000); assertEquals("Queue size is has not changed " + proxy.getQueueSize(), NUM_TO_SEND, proxy.getQueueSize()); } private void applyExpiryDuration(int i) { broker.getDestinationPolicy().getDefaultEntry().setExpireMessagesPeriod(i); } private void applyBrokerSpoolingPolicy(boolean prioritizedMessages) { PolicyMap policyMap = new PolicyMap(); PolicyEntry defaultEntry = new PolicyEntry(); defaultEntry.setPrioritizedMessages(prioritizedMessages); defaultEntry.setProducerFlowControl(false); PendingQueueMessageStoragePolicy pendingQueuePolicy = new FilePendingQueueMessageStoragePolicy(); defaultEntry.setPendingQueuePolicy(pendingQueuePolicy); policyMap.setDefaultEntry(defaultEntry); broker.setDestinationPolicy(policyMap); } public void testPurgeLargeQueueWithConsumer() throws Exception { testPurgeLargeQueueWithConsumer(false); } public void testPurgeLargeQueueWithConsumerPrioritizedMessages() throws Exception { testPurgeLargeQueueWithConsumer(true); } public void testConcurrentPurgeAndSend() throws Exception { testConcurrentPurgeAndSend(false); } public void testConcurrentPurgeAndSendPrioritizedMessages() throws Exception { testConcurrentPurgeAndSend(true); } private void testConcurrentPurgeAndSend(boolean prioritizedMessages) throws Exception { applyBrokerSpoolingPolicy(false); createProducerAndSendMessages(NUM_TO_SEND / 2); final QueueViewMBean proxy = getProxyToQueueViewMBean(); createConsumer(); final long start = System.currentTimeMillis(); ExecutorService service = Executors.newFixedThreadPool(1); try { LOG.info("purging.."); service.submit(new Runnable() { @Override public void run() { try { proxy.purge(); } catch (Exception e) { fail(e.getMessage()); } LOG.info("purge done: " + (System.currentTimeMillis() - start) + "ms"); } }); //send should get blocked while purge is running //which should ensure the metrics are correct createProducerAndSendMessages(NUM_TO_SEND / 2); Message msg; do { msg = consumer.receive(1000); if (msg != null) { msg.acknowledge(); } } while (msg != null); assertEquals("Queue size not valid", 0, proxy.getQueueSize()); assertEquals("Found messages when browsing", 0, proxy.browseMessages().size()); } finally { service.shutdownNow(); } } private void testPurgeLargeQueueWithConsumer(boolean prioritizedMessages) throws Exception { applyBrokerSpoolingPolicy(prioritizedMessages); createProducerAndSendMessages(NUM_TO_SEND); QueueViewMBean proxy = getProxyToQueueViewMBean(); createConsumer(); long start = System.currentTimeMillis(); LOG.info("purging.."); proxy.purge(); LOG.info("purge done: " + (System.currentTimeMillis() - start) + "ms"); assertEquals("Queue size is not zero, it's " + proxy.getQueueSize(), 0, proxy.getQueueSize()); assertEquals("usage goes to duck", 0, proxy.getMemoryPercentUsage()); Message msg; do { msg = consumer.receive(1000); if (msg != null) { msg.acknowledge(); } } while (msg != null); assertEquals("Queue size not valid", 0, proxy.getQueueSize()); assertEquals("Found messages when browsing", 0, proxy.browseMessages().size()); } private QueueViewMBean getProxyToQueueViewMBean() throws MalformedObjectNameException, JMSException { ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=" + queue.getQueueName()); QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext() .newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true); return proxy; } private void createProducerAndSendMessages(int numToSend) throws Exception { session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); queue = session.createQueue("test1"); MessageProducer producer = session.createProducer(queue); for (int i = 0; i < numToSend; i++) { TextMessage message = session.createTextMessage(MESSAGE_TEXT + i); if (i != 0 && i % 10000 == 0) { LOG.info("sent: " + i); } producer.send(message); } producer.close(); } private void createConsumer() throws Exception { consumer = session.createConsumer(queue); // wait for buffer fill out Thread.sleep(5 * 1000); for (int i = 0; i < 500; ++i) { Message message = consumer.receive(); message.acknowledge(); } } }
apache-2.0
davidzchen/bazel
src/test/java/com/google/devtools/build/lib/skyframe/PackageFunctionTest.java
68630
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skyframe; import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.build.skyframe.EvaluationResultSubjectFactory.assertThatEvaluationResult; import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.devtools.build.lib.actions.FileStateValue; import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider; import com.google.devtools.build.lib.analysis.util.BuildViewTestCase; import com.google.devtools.build.lib.clock.BlazeClock; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.PackageIdentifier; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.ExtendedEventHandler; import com.google.devtools.build.lib.packages.BazelModuleContext; import com.google.devtools.build.lib.packages.BuildFileNotFoundException; import com.google.devtools.build.lib.packages.ConstantRuleVisibility; import com.google.devtools.build.lib.packages.NoSuchPackageException; import com.google.devtools.build.lib.packages.NoSuchTargetException; import com.google.devtools.build.lib.packages.Package; import com.google.devtools.build.lib.packages.PackageValidator; import com.google.devtools.build.lib.packages.PackageValidator.InvalidPackageException; import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions; import com.google.devtools.build.lib.pkgcache.PackageOptions; import com.google.devtools.build.lib.pkgcache.PathPackageLocator; import com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction; import com.google.devtools.build.lib.server.FailureDetails.PackageLoading; import com.google.devtools.build.lib.skyframe.util.SkyframeExecutorTestUtils; import com.google.devtools.build.lib.testutil.ManualClock; import com.google.devtools.build.lib.testutil.TestRuleClassProvider; import com.google.devtools.build.lib.util.DetailedExitCode; import com.google.devtools.build.lib.util.ExitCode; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.util.io.TimestampGranularityMonitor; import com.google.devtools.build.lib.vfs.DigestHashFunction; import com.google.devtools.build.lib.vfs.Dirent; import com.google.devtools.build.lib.vfs.FileStatus; import com.google.devtools.build.lib.vfs.FileSystem; import com.google.devtools.build.lib.vfs.FileSystemUtils; import com.google.devtools.build.lib.vfs.ModifiedFileSet; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.lib.vfs.Root; import com.google.devtools.build.lib.vfs.RootedPath; import com.google.devtools.build.lib.vfs.Symlinks; import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem; import com.google.devtools.build.skyframe.ErrorInfo; import com.google.devtools.build.skyframe.EvaluationResult; import com.google.devtools.build.skyframe.RecordingDifferencer; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.SkyValue; import com.google.devtools.common.options.Options; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import net.starlark.java.eval.Module; import net.starlark.java.eval.StarlarkInt; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; /** * Unit tests of specific functionality of PackageFunction. Note that it's already tested indirectly * in several other places. */ @RunWith(JUnit4.class) public class PackageFunctionTest extends BuildViewTestCase { @Rule public final MockitoRule mockito = MockitoJUnit.rule(); @Mock private PackageValidator mockPackageValidator; private CustomInMemoryFs fs = new CustomInMemoryFs(new ManualClock()); private void preparePackageLoading(Path... roots) { preparePackageLoadingWithCustomStarklarkSemanticsOptions( Options.getDefaults(BuildLanguageOptions.class), roots); } private void preparePackageLoadingWithCustomStarklarkSemanticsOptions( BuildLanguageOptions starlarkSemanticsOptions, Path... roots) { PackageOptions packageOptions = Options.getDefaults(PackageOptions.class); packageOptions.defaultVisibility = ConstantRuleVisibility.PUBLIC; packageOptions.showLoadingProgress = true; packageOptions.globbingThreads = 7; getSkyframeExecutor() .preparePackageLoading( new PathPackageLocator( outputBase, Arrays.stream(roots).map(Root::fromPath).collect(ImmutableList.toImmutableList()), BazelSkyframeExecutorConstants.BUILD_FILES_BY_PRIORITY), packageOptions, starlarkSemanticsOptions, UUID.randomUUID(), ImmutableMap.<String, String>of(), new TimestampGranularityMonitor(BlazeClock.instance())); skyframeExecutor.setActionEnv(ImmutableMap.<String, String>of()); } @Override protected FileSystem createFileSystem() { return fs; } @Override protected PackageValidator getPackageValidator() { return mockPackageValidator; } private Package validPackageWithoutErrors(SkyKey skyKey) throws InterruptedException { return validPackageInternal(skyKey, /*checkPackageError=*/ true); } private Package validPackage(SkyKey skyKey) throws InterruptedException { return validPackageInternal(skyKey, /*checkPackageError=*/ false); } private Package validPackageInternal(SkyKey skyKey, boolean checkPackageError) throws InterruptedException { SkyframeExecutor skyframeExecutor = getSkyframeExecutor(); skyframeExecutor.injectExtraPrecomputedValues( ImmutableList.of( PrecomputedValue.injected( RepositoryDelegatorFunction.RESOLVED_FILE_INSTEAD_OF_WORKSPACE, Optional.empty()))); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( skyframeExecutor, skyKey, /*keepGoing=*/ false, reporter); if (result.hasError()) { fail(result.getError(skyKey).getException().getMessage()); } PackageValue value = result.get(skyKey); if (checkPackageError) { assertThat(value.getPackage().containsErrors()).isFalse(); } return value.getPackage(); } @Test public void testValidPackage() throws Exception { scratch.file("pkg/BUILD"); validPackageWithoutErrors(PackageValue.key(PackageIdentifier.parse("@//pkg"))); } @Test public void testInvalidPackage() throws Exception { scratch.file("pkg/BUILD", "sh_library(name='foo', srcs=['foo.sh'])"); scratch.file("pkg/foo.sh"); doAnswer( inv -> { Package pkg = inv.getArgument(0, Package.class); if (pkg.getName().equals("pkg")) { inv.getArgument(1, ExtendedEventHandler.class).handle(Event.warn("warning event")); throw new InvalidPackageException(pkg.getPackageIdentifier(), "no good"); } return null; }) .when(mockPackageValidator) .validate(any(Package.class), any(ExtendedEventHandler.class)); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThatEvaluationResult(result).hasError(); assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(skyKey) .hasExceptionThat() .isInstanceOf(InvalidPackageException.class); assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(skyKey) .hasExceptionThat() .hasMessageThat() .contains("no such package 'pkg': no good"); assertContainsEvent("warning event"); } @Test public void testSkyframeExecutorClearedPackagesResultsInReload() throws Exception { scratch.file("pkg/BUILD", "sh_library(name='foo', srcs=['foo.sh'])"); scratch.file("pkg/foo.sh"); invalidatePackages(); // Use number of times the package was validated as a proxy for number of times it was loaded. AtomicInteger validationCount = new AtomicInteger(); doAnswer( inv -> { if (inv.getArgument(0, Package.class).getName().equals("pkg")) { validationCount.incrementAndGet(); } return null; }) .when(mockPackageValidator) .validate(any(Package.class), any(ExtendedEventHandler.class)); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); EvaluationResult<PackageValue> result1 = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThatEvaluationResult(result1).hasNoError(); skyframeExecutor.clearLoadedPackages(); EvaluationResult<PackageValue> result2 = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThatEvaluationResult(result2).hasNoError(); assertThat(validationCount.get()).isEqualTo(2); } @Test public void testPropagatesFilesystemInconsistencies() throws Exception { reporter.removeHandler(failFastHandler); RecordingDifferencer differencer = getSkyframeExecutor().getDifferencerForTesting(); Root pkgRoot = getSkyframeExecutor().getPathEntries().get(0); Path fooBuildFile = scratch.file("foo/BUILD"); Path fooDir = fooBuildFile.getParentDirectory(); // Our custom filesystem says that fooDir is neither a file nor directory nor symlink FileStatus inconsistentFileStatus = new FileStatus() { @Override public boolean isFile() { return false; } @Override public boolean isDirectory() { return false; } @Override public boolean isSymbolicLink() { return false; } @Override public boolean isSpecialFile() { return false; } @Override public long getSize() throws IOException { return 0; } @Override public long getLastModifiedTime() throws IOException { return 0; } @Override public long getLastChangeTime() throws IOException { return 0; } @Override public long getNodeId() throws IOException { return 0; } }; fs.stubStat(fooBuildFile, inconsistentFileStatus); RootedPath pkgRootedPath = RootedPath.toRootedPath(pkgRoot, fooDir); SkyValue fooDirValue = FileStateValue.create(pkgRootedPath, tsgm); differencer.inject(ImmutableMap.of(FileStateValue.key(pkgRootedPath), fooDirValue)); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); String expectedMessage = "according to stat, existing path /workspace/foo/BUILD is neither" + " a file nor directory nor symlink."; EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); ErrorInfo errorInfo = result.getError(skyKey); String errorMessage = errorInfo.getException().getMessage(); assertThat(errorMessage).contains("Inconsistent filesystem operations"); assertThat(errorMessage).contains(expectedMessage); assertDetailedExitCode( errorInfo.getException(), PackageLoading.Code.PERSISTENT_INCONSISTENT_FILESYSTEM_ERROR); } @Test public void testPropagatesFilesystemInconsistencies_globbing() throws Exception { getSkyframeExecutor().turnOffSyscallCacheForTesting(); reporter.removeHandler(failFastHandler); RecordingDifferencer differencer = getSkyframeExecutor().getDifferencerForTesting(); Root pkgRoot = getSkyframeExecutor().getPathEntries().get(0); scratch.file( "foo/BUILD", "sh_library(name = 'foo', srcs = glob(['bar/**/baz.sh']))", "x = 1//0" // causes 'foo' to be marked in error ); Path bazFile = scratch.file("foo/bar/baz/baz.sh"); Path bazDir = bazFile.getParentDirectory(); Path barDir = bazDir.getParentDirectory(); // Our custom filesystem says "foo/bar/baz" does not exist but it also says that "foo/bar" // has a child directory "baz". fs.stubStat(bazDir, null); RootedPath barDirRootedPath = RootedPath.toRootedPath(pkgRoot, barDir); differencer.inject( ImmutableMap.of( DirectoryListingStateValue.key(barDirRootedPath), DirectoryListingStateValue.create( ImmutableList.of(new Dirent("baz", Dirent.Type.DIRECTORY))))); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); String expectedMessage = "/workspace/foo/bar/baz is no longer an existing directory"; EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); ErrorInfo errorInfo = result.getError(skyKey); String errorMessage = errorInfo.getException().getMessage(); assertThat(errorMessage).contains("Inconsistent filesystem operations"); assertThat(errorMessage).contains(expectedMessage); assertDetailedExitCode( errorInfo.getException(), PackageLoading.Code.PERSISTENT_INCONSISTENT_FILESYSTEM_ERROR); } /** Regression test for unexpected exception type from PackageValue. */ @Test public void testDiscrepancyBetweenLegacyAndSkyframePackageLoadingErrors() throws Exception { // Normally, legacy globbing and skyframe globbing share a cache for `readdir` filesystem calls. // In order to exercise a situation where they observe different results for filesystem calls, // we disable the cache. This might happen in a real scenario, e.g. if the cache hits a limit // and evicts entries. getSkyframeExecutor().turnOffSyscallCacheForTesting(); reporter.removeHandler(failFastHandler); Path fooBuildFile = scratch.file("foo/BUILD", "sh_library(name = 'foo', srcs = glob(['bar/*.sh']))"); Path fooDir = fooBuildFile.getParentDirectory(); Path barDir = fooDir.getRelative("bar"); scratch.file("foo/bar/baz.sh"); fs.scheduleMakeUnreadableAfterReaddir(barDir); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); String expectedMessage = "Encountered error 'Directory is not readable'"; EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); ErrorInfo errorInfo = result.getError(skyKey); String errorMessage = errorInfo.getException().getMessage(); assertThat(errorMessage).contains("Inconsistent filesystem operations"); assertThat(errorMessage).contains(expectedMessage); assertDetailedExitCode( errorInfo.getException(), PackageLoading.Code.TRANSIENT_INCONSISTENT_FILESYSTEM_ERROR); } @SuppressWarnings("unchecked") // Cast of srcs attribute to Iterable<Label>. @Test public void testGlobOrderStable() throws Exception { scratch.file("foo/BUILD", "sh_library(name = 'foo', srcs = glob(['**/*.txt']))"); scratch.file("foo/b.txt"); scratch.file("foo/c/c.txt"); preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); Package pkg = validPackageWithoutErrors(skyKey); assertThat((Iterable<Label>) pkg.getTarget("foo").getAssociatedRule().getAttr("srcs")) .containsExactly( Label.parseAbsoluteUnchecked("//foo:b.txt"), Label.parseAbsoluteUnchecked("//foo:c/c.txt")) .inOrder(); scratch.file("foo/d.txt"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/d.txt")).build(), Root.fromPath(rootDirectory)); pkg = validPackageWithoutErrors(skyKey); assertThat((Iterable<Label>) pkg.getTarget("foo").getAssociatedRule().getAttr("srcs")) .containsExactly( Label.parseAbsoluteUnchecked("//foo:b.txt"), Label.parseAbsoluteUnchecked("//foo:c/c.txt"), Label.parseAbsoluteUnchecked("//foo:d.txt")) .inOrder(); } @Test public void testGlobOrderStableWithLegacyAndSkyframeComponents() throws Exception { scratch.file("foo/BUILD", "sh_library(name = 'foo', srcs = glob(['*.txt']))"); scratch.file("foo/b.txt"); scratch.file("foo/a.config"); preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); assertSrcs(validPackageWithoutErrors(skyKey), "foo", "//foo:b.txt"); scratch.overwriteFile( "foo/BUILD", "sh_library(name = 'foo', srcs = glob(['*.txt', '*.config']))"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), Root.fromPath(rootDirectory)); assertSrcs(validPackageWithoutErrors(skyKey), "foo", "//foo:a.config", "//foo:b.txt"); scratch.overwriteFile( "foo/BUILD", "sh_library(name = 'foo', srcs = glob(['*.txt', '*.config'])) # comment"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), Root.fromPath(rootDirectory)); assertSrcs(validPackageWithoutErrors(skyKey), "foo", "//foo:a.config", "//foo:b.txt"); getSkyframeExecutor().resetEvaluator(); PackageOptions packageOptions = Options.getDefaults(PackageOptions.class); packageOptions.defaultVisibility = ConstantRuleVisibility.PUBLIC; packageOptions.showLoadingProgress = true; packageOptions.globbingThreads = 7; getSkyframeExecutor() .preparePackageLoading( new PathPackageLocator( outputBase, ImmutableList.of(Root.fromPath(rootDirectory)), BazelSkyframeExecutorConstants.BUILD_FILES_BY_PRIORITY), packageOptions, Options.getDefaults(BuildLanguageOptions.class), UUID.randomUUID(), ImmutableMap.<String, String>of(), tsgm); getSkyframeExecutor().setActionEnv(ImmutableMap.<String, String>of()); assertSrcs(validPackageWithoutErrors(skyKey), "foo", "//foo:a.config", "//foo:b.txt"); } @Test public void globEscapesAt() throws Exception { scratch.file("foo/BUILD", "filegroup(name = 'foo', srcs = glob(['*.txt']))"); scratch.file("foo/@f.txt"); preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); assertSrcs(validPackageWithoutErrors(skyKey), "foo", "//foo:@f.txt"); scratch.overwriteFile("foo/BUILD", "filegroup(name = 'foo', srcs = glob(['*.txt'])) # comment"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), Root.fromPath(rootDirectory)); assertSrcs(validPackageWithoutErrors(skyKey), "foo", "//foo:@f.txt"); } /** * Tests that a symlink to a file outside of the package root is handled consistently. If the * default behavior of Bazel was changed from {@code * ExternalFileAction#DEPEND_ON_EXTERNAL_PKG_FOR_EXTERNAL_REPO_PATHS} to {@code * ExternalFileAction#ASSUME_NON_EXISTENT_AND_IMMUTABLE_FOR_EXTERNAL_PATHS} then foo/link.sh * should no longer appear in the srcs of //foo:foo. However, either way the srcs should be the * same independent of the evaluation being incremental or clean. */ @Test public void testGlobWithExternalSymlink() throws Exception { scratch.file( "foo/BUILD", "sh_library(name = 'foo', srcs = glob(['*.sh']))", "sh_library(name = 'bar', srcs = glob(['link.sh']))", "sh_library(name = 'baz', srcs = glob(['subdir_link/*.txt']))"); scratch.file("foo/ordinary.sh"); Path externalTarget = scratch.file("../ops/target.txt"); FileSystemUtils.ensureSymbolicLink(scratch.resolve("foo/link.sh"), externalTarget); FileSystemUtils.ensureSymbolicLink( scratch.resolve("foo/subdir_link"), externalTarget.getParentDirectory()); preparePackageLoading(rootDirectory); SkyKey fooKey = PackageValue.key(PackageIdentifier.parse("@//foo")); Package fooPkg = validPackageWithoutErrors(fooKey); assertSrcs(fooPkg, "foo", "//foo:link.sh", "//foo:ordinary.sh"); assertSrcs(fooPkg, "bar", "//foo:link.sh"); assertSrcs(fooPkg, "baz", "//foo:subdir_link/target.txt"); scratch.overwriteFile( "foo/BUILD", "sh_library(name = 'foo', srcs = glob(['*.sh'])) #comment", "sh_library(name = 'bar', srcs = glob(['link.sh']))", "sh_library(name = 'baz', srcs = glob(['subdir_link/*.txt']))"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), Root.fromPath(rootDirectory)); Package fooPkg2 = validPackageWithoutErrors(fooKey); assertThat(fooPkg2).isNotEqualTo(fooPkg); assertSrcs(fooPkg2, "foo", "//foo:link.sh", "//foo:ordinary.sh"); assertSrcs(fooPkg2, "bar", "//foo:link.sh"); assertSrcs(fooPkg2, "baz", "//foo:subdir_link/target.txt"); } private static void assertSrcs(Package pkg, String targetName, String... expected) throws NoSuchTargetException { List<Label> expectedLabels = new ArrayList<>(); for (String item : expected) { expectedLabels.add(Label.parseAbsoluteUnchecked(item)); } assertThat(getSrcs(pkg, targetName)).containsExactlyElementsIn(expectedLabels).inOrder(); } @SuppressWarnings("unchecked") private static Iterable<Label> getSrcs(Package pkg, String targetName) throws NoSuchTargetException { return (Iterable<Label>) pkg.getTarget(targetName).getAssociatedRule().getAttr("srcs"); } @Test public void testOneNewElementInMultipleGlob() throws Exception { scratch.file( "foo/BUILD", "sh_library(name = 'foo', srcs = glob(['*.sh']))", "sh_library(name = 'bar', srcs = glob(['*.sh', '*.txt']))"); preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); Package pkg = validPackageWithoutErrors(skyKey); scratch.file("foo/irrelevant"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/irrelevant")).build(), Root.fromPath(rootDirectory)); assertThat(validPackageWithoutErrors(skyKey)).isSameInstanceAs(pkg); } @Test public void testNoNewElementInMultipleGlob() throws Exception { scratch.file( "foo/BUILD", "sh_library(name = 'foo', srcs = glob(['*.sh', '*.txt']))", "sh_library(name = 'bar', srcs = glob(['*.sh', '*.txt']))"); preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); Package pkg = validPackageWithoutErrors(skyKey); scratch.file("foo/irrelevant"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/irrelevant")).build(), Root.fromPath(rootDirectory)); assertThat(validPackageWithoutErrors(skyKey)).isSameInstanceAs(pkg); } @Test public void testTransitiveStarlarkDepsStoredInPackage() throws Exception { scratch.file("foo/BUILD", "load('//bar:ext.bzl', 'a')"); scratch.file("bar/BUILD"); scratch.file("bar/ext.bzl", "load('//baz:ext.bzl', 'b')", "a = b"); scratch.file("baz/BUILD"); scratch.file("baz/ext.bzl", "b = 1"); scratch.file("qux/BUILD"); scratch.file("qux/ext.bzl", "c = 1"); preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); Package pkg = validPackageWithoutErrors(skyKey); assertThat(pkg.getStarlarkFileDependencies()) .containsExactly( Label.parseAbsolute("//bar:ext.bzl", ImmutableMap.of()), Label.parseAbsolute("//baz:ext.bzl", ImmutableMap.of())); scratch.overwriteFile("bar/ext.bzl", "load('//qux:ext.bzl', 'c')", "a = c"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("bar/ext.bzl")).build(), Root.fromPath(rootDirectory)); pkg = validPackageWithoutErrors(skyKey); assertThat(pkg.getStarlarkFileDependencies()) .containsExactly( Label.parseAbsolute("//bar:ext.bzl", ImmutableMap.of()), Label.parseAbsolute("//qux:ext.bzl", ImmutableMap.of())); } @Test public void testNonExistingStarlarkExtension() throws Exception { reporter.removeHandler(failFastHandler); scratch.file( "test/starlark/BUILD", "load('//test/starlark:bad_extension.bzl', 'some_symbol')", "genrule(name = gr,", " outs = ['out.txt'],", " cmd = 'echo hello >@')"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//test/starlark")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); ErrorInfo errorInfo = result.getError(skyKey); String expectedMsg = "error loading package 'test/starlark': " + "cannot load '//test/starlark:bad_extension.bzl': no such file"; assertThat(errorInfo.getException()).hasMessageThat().isEqualTo(expectedMsg); assertDetailedExitCode( errorInfo.getException(), PackageLoading.Code.IMPORT_STARLARK_FILE_ERROR); } @Test public void testNonExistingStarlarkExtensionFromExtension() throws Exception { reporter.removeHandler(failFastHandler); scratch.file( "test/starlark/extension.bzl", "load('//test/starlark:bad_extension.bzl', 'some_symbol')", "a = 'a'"); scratch.file( "test/starlark/BUILD", "load('//test/starlark:extension.bzl', 'a')", "genrule(name = gr,", " outs = ['out.txt'],", " cmd = 'echo hello >@')"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//test/starlark")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); ErrorInfo errorInfo = result.getError(skyKey); assertThat(errorInfo.getException()) .hasMessageThat() .isEqualTo( "error loading package 'test/starlark': " + "in /workspace/test/starlark/extension.bzl: " + "cannot load '//test/starlark:bad_extension.bzl': no such file"); assertDetailedExitCode( errorInfo.getException(), PackageLoading.Code.IMPORT_STARLARK_FILE_ERROR); } @Test public void testSymlinkCycleWithStarlarkExtension() throws Exception { reporter.removeHandler(failFastHandler); Path extensionFilePath = scratch.resolve("/workspace/test/starlark/extension.bzl"); FileSystemUtils.ensureSymbolicLink(extensionFilePath, PathFragment.create("extension.bzl")); scratch.file( "test/starlark/BUILD", "load('//test/starlark:extension.bzl', 'a')", "genrule(name = gr,", " outs = ['out.txt'],", " cmd = 'echo hello >@')"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//test/starlark")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); ErrorInfo errorInfo = result.getError(skyKey); assertThat(errorInfo.getRootCauseOfException()).isEqualTo(skyKey); assertThat(errorInfo.getException()) .hasMessageThat() .isEqualTo( "error loading package 'test/starlark': Encountered error while reading extension " + "file 'test/starlark/extension.bzl': Symlink cycle"); assertDetailedExitCode( errorInfo.getException(), PackageLoading.Code.IMPORT_STARLARK_FILE_ERROR); } @Test public void testIOErrorLookingForSubpackageForLabelIsHandled() throws Exception { reporter.removeHandler(failFastHandler); scratch.file("foo/BUILD", "sh_library(name = 'foo', srcs = ['bar/baz.sh'])"); Path barBuildFile = scratch.file("foo/bar/BUILD"); fs.stubStatError(barBuildFile, new IOException("nope")); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); assertContainsEvent("nope"); } @Test public void testLoadOK() throws Exception { scratch.file("p/a.bzl", "a = 1; b = 1; d = 1"); scratch.file("p/subdir/a.bzl", "c = 1; e = 1"); scratch.file( "p/BUILD", // "load(':a.bzl', 'a')", "load('a.bzl', 'b')", "load('subdir/a.bzl', 'c')", "load('//p:a.bzl', 'd')", "load('//p:subdir/a.bzl', 'e')"); validPackageWithoutErrors(PackageValue.key(PackageIdentifier.parse("@//p"))); } // See WorkspaceFileFunctionTest for tests that exercise load('@repo...'). @Test public void testLoadBadLabel() throws Exception { scratch.file("p/BUILD", "load('this\tis not a label', 'a')"); reporter.removeHandler(failFastHandler); SkyKey key = PackageValue.key(PackageIdentifier.parse("@//p")); SkyframeExecutorTestUtils.evaluate(skyframeExecutor, key, /*keepGoing=*/ false, reporter); assertContainsEvent( "in load statement: invalid target name 'this<?>is not a label': target names may not" + " contain non-printable characters"); } @Test public void testLoadFromExternalPackage() throws Exception { scratch.file("p/BUILD", "load('//external:file.bzl', 'a')"); reporter.removeHandler(failFastHandler); SkyKey key = PackageValue.key(PackageIdentifier.parse("@//p")); SkyframeExecutorTestUtils.evaluate(skyframeExecutor, key, /*keepGoing=*/ false, reporter); assertContainsEvent("Starlark files may not be loaded from the //external package"); } @Test public void testLoadWithoutBzlSuffix() throws Exception { scratch.file("p/BUILD", "load('//p:file.starlark', 'a')"); reporter.removeHandler(failFastHandler); SkyKey key = PackageValue.key(PackageIdentifier.parse("@//p")); SkyframeExecutorTestUtils.evaluate(skyframeExecutor, key, /*keepGoing=*/ false, reporter); assertContainsEvent("The label must reference a file with extension '.bzl'"); } @Test public void testBadWorkspaceFile() throws Exception { Path workspacePath = scratch.overwriteFile("WORKSPACE", "junk"); SkyKey skyKey = PackageValue.key(PackageIdentifier.createInMainRepo("external")); getSkyframeExecutor() .invalidate( Predicates.equalTo( FileStateValue.key( RootedPath.toRootedPath( Root.fromPath(workspacePath.getParentDirectory()), PathFragment.create(workspacePath.getBaseName()))))); reporter.removeHandler(failFastHandler); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isFalse(); assertThat(result.get(skyKey).getPackage().containsErrors()).isTrue(); } // Regression test for the two ugly consequences of a bug where GlobFunction incorrectly matched // dangling symlinks. @Test public void testIncrementalSkyframeHybridGlobbingOnDanglingSymlink() throws Exception { Path packageDirPath = scratch.file("foo/BUILD", "exports_files(glob(['*.txt']))").getParentDirectory(); scratch.file("foo/existing.txt"); FileSystemUtils.ensureSymbolicLink(packageDirPath.getChild("dangling.txt"), "nope"); preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); Package pkg = validPackageWithoutErrors(skyKey); assertThat(pkg.containsErrors()).isFalse(); assertThat(pkg.getTarget("existing.txt").getName()).isEqualTo("existing.txt"); assertThrows(NoSuchTargetException.class, () -> pkg.getTarget("dangling.txt")); scratch.overwriteFile( "foo/BUILD", "exports_files(glob(['*.txt']))", "#some-irrelevant-comment"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), Root.fromPath(rootDirectory)); Package pkg2 = validPackageWithoutErrors(skyKey); assertThat(pkg2.containsErrors()).isFalse(); assertThat(pkg2.getTarget("existing.txt").getName()).isEqualTo("existing.txt"); assertThrows(NoSuchTargetException.class, () -> pkg2.getTarget("dangling.txt")); // One consequence of the bug was that dangling symlinks were matched by globs evaluated by // Skyframe globbing, meaning there would incorrectly be corresponding targets in packages // that had skyframe cache hits during skyframe hybrid globbing. scratch.file("foo/nope"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/nope")).build(), Root.fromPath(rootDirectory)); Package newPkg = validPackageWithoutErrors(skyKey); assertThat(newPkg.containsErrors()).isFalse(); assertThat(newPkg.getTarget("existing.txt").getName()).isEqualTo("existing.txt"); // Another consequence of the bug is that change pruning would incorrectly cut off changes that // caused a dangling symlink potentially matched by a glob to come into existence. assertThat(newPkg.getTarget("dangling.txt").getName()).isEqualTo("dangling.txt"); assertThat(newPkg).isNotSameInstanceAs(pkg); } // Regression test for Skyframe globbing incorrectly matching the package's directory path on // 'glob(['**'], exclude_directories = 0)'. We test for this directly by triggering // hybrid globbing (gives coverage for both legacy globbing and skyframe globbing). @Test public void testRecursiveGlobNeverMatchesPackageDirectory() throws Exception { scratch.file( "foo/BUILD", "[sh_library(name = x + '-matched') for x in glob(['**'], exclude_directories = 0)]"); scratch.file("foo/bar"); preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); Package pkg = validPackageWithoutErrors(skyKey); assertThat(pkg.containsErrors()).isFalse(); assertThat(pkg.getTarget("bar-matched").getName()).isEqualTo("bar-matched"); assertThrows(NoSuchTargetException.class, () -> pkg.getTarget("-matched")); scratch.overwriteFile( "foo/BUILD", "[sh_library(name = x + '-matched') for x in glob(['**'], exclude_directories = 0)]", "#some-irrelevant-comment"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), Root.fromPath(rootDirectory)); Package pkg2 = validPackageWithoutErrors(skyKey); assertThat(pkg2.containsErrors()).isFalse(); assertThat(pkg2.getTarget("bar-matched").getName()).isEqualTo("bar-matched"); assertThrows(NoSuchTargetException.class, () -> pkg2.getTarget("-matched")); } @Test public void testPackageLoadingErrorOnIOExceptionReadingBuildFile() throws Exception { Path fooBuildFilePath = scratch.file("foo/BUILD"); IOException exn = new IOException("nope"); fs.throwExceptionOnGetInputStream(fooBuildFilePath, exn); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); ErrorInfo errorInfo = result.getError(skyKey); String errorMessage = errorInfo.getException().getMessage(); assertThat(errorMessage).contains("nope"); assertThat(errorInfo.getException()).isInstanceOf(NoSuchPackageException.class); assertThat(errorInfo.getException()).hasCauseThat().isInstanceOf(IOException.class); assertDetailedExitCode(errorInfo.getException(), PackageLoading.Code.BUILD_FILE_MISSING); } @Test public void testPackageLoadingErrorOnIOExceptionReadingBzlFile() throws Exception { scratch.file("foo/BUILD", "load('//foo:bzl.bzl', 'x')"); Path fooBzlFilePath = scratch.file("foo/bzl.bzl"); IOException exn = new IOException("nope"); fs.throwExceptionOnGetInputStream(fooBzlFilePath, exn); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//foo")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThat(result.hasError()).isTrue(); ErrorInfo errorInfo = result.getError(skyKey); String errorMessage = errorInfo.getException().getMessage(); assertThat(errorMessage).contains("nope"); assertThat(errorInfo.getException()).isInstanceOf(NoSuchPackageException.class); assertThat(errorInfo.getException()).hasCauseThat().isInstanceOf(IOException.class); assertDetailedExitCode( errorInfo.getException(), PackageLoading.Code.IMPORT_STARLARK_FILE_ERROR); } @Test public void testLabelsCrossesSubpackageBoundaries() throws Exception { reporter.removeHandler(failFastHandler); scratch.file("pkg/BUILD", "exports_files(['sub/blah'])"); scratch.file("pkg/sub/BUILD"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThatEvaluationResult(result).hasNoError(); assertThat(result.get(skyKey).getPackage().containsErrors()).isTrue(); assertContainsEvent("Label '//pkg:sub/blah' is invalid because 'pkg/sub' is a subpackage"); } @Test public void testSymlinkCycleEncounteredWhileHandlingLabelCrossingSubpackageBoundaries() throws Exception { reporter.removeHandler(failFastHandler); scratch.file("pkg/BUILD", "exports_files(['sub/blah'])"); Path subBuildFilePath = scratch.dir("pkg/sub").getChild("BUILD"); FileSystemUtils.ensureSymbolicLink(subBuildFilePath, subBuildFilePath); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), skyKey, /*keepGoing=*/ false, reporter); assertThatEvaluationResult(result).hasError(); assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(skyKey) .hasExceptionThat() .isInstanceOf(BuildFileNotFoundException.class); assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(skyKey) .hasExceptionThat() .hasMessageThat() .contains( "no such package 'pkg/sub': Symlink cycle detected while trying to find BUILD file"); assertContainsEvent("circular symlinks detected"); } @Test public void testGlobAllowEmpty_paramValueMustBeBoolean() throws Exception { reporter.removeHandler(failFastHandler); scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty = 5)"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); validPackage(skyKey); assertContainsEvent("expected boolean for argument `allow_empty`, got `5`"); } @Test public void testGlobAllowEmpty_functionParam() throws Exception { scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty=True)"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isFalse(); assertNoEvents(); } @Test public void testGlobAllowEmpty_starlarkOption() throws Exception { preparePackageLoadingWithCustomStarklarkSemanticsOptions( Options.parse(BuildLanguageOptions.class, "--incompatible_disallow_empty_glob=false") .getOptions(), rootDirectory); scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'])"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isFalse(); assertNoEvents(); } @Test public void testGlobDisallowEmpty_functionParam_wasNonEmptyAndBecomesEmpty() throws Exception { scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty=False)"); scratch.file("pkg/blah.foo"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isFalse(); assertNoEvents(); scratch.deleteFile("pkg/blah.foo"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("pkg/blah.foo")).build(), Root.fromPath(rootDirectory)); reporter.removeHandler(failFastHandler); pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent( "glob pattern '*.foo' didn't match anything, but allow_empty is set to False (the " + "default value of allow_empty can be set with --incompatible_disallow_empty_glob)."); } @Test public void testGlobDisallowEmpty_starlarkOption_wasNonEmptyAndBecomesEmpty() throws Exception { preparePackageLoadingWithCustomStarklarkSemanticsOptions( Options.parse(BuildLanguageOptions.class, "--incompatible_disallow_empty_glob=true") .getOptions(), rootDirectory); scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'])"); scratch.file("pkg/blah.foo"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isFalse(); assertNoEvents(); scratch.deleteFile("pkg/blah.foo"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("pkg/blah.foo")).build(), Root.fromPath(rootDirectory)); reporter.removeHandler(failFastHandler); pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent( "glob pattern '*.foo' didn't match anything, but allow_empty is set to False (the " + "default value of allow_empty can be set with --incompatible_disallow_empty_glob)."); } @Test public void testGlobDisallowEmpty_functionParam_wasEmptyAndStaysEmpty() throws Exception { scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty=False)"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); reporter.removeHandler(failFastHandler); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); String expectedEventString = "glob pattern '*.foo' didn't match anything, but allow_empty is set to False (the " + "default value of allow_empty can be set with --incompatible_disallow_empty_glob)."; assertContainsEvent(expectedEventString); scratch.overwriteFile("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty=False) #comment"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("pkg/BUILD")).build(), Root.fromPath(rootDirectory)); pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent(expectedEventString); } @Test public void testGlobDisallowEmpty_starlarkOption_wasEmptyAndStaysEmpty() throws Exception { preparePackageLoadingWithCustomStarklarkSemanticsOptions( Options.parse(BuildLanguageOptions.class, "--incompatible_disallow_empty_glob=true") .getOptions(), rootDirectory); scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'])"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); reporter.removeHandler(failFastHandler); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); String expectedEventString = "glob pattern '*.foo' didn't match anything, but allow_empty is set to False (the " + "default value of allow_empty can be set with --incompatible_disallow_empty_glob)."; assertContainsEvent(expectedEventString); scratch.overwriteFile("pkg/BUILD", "x = " + "glob(['*.foo']) #comment"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("pkg/BUILD")).build(), Root.fromPath(rootDirectory)); pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent(expectedEventString); } @Test public void testGlobDisallowEmpty_functionParam_wasEmptyDueToExcludeAndStaysEmpty() throws Exception { scratch.file("pkg/BUILD", "x = glob(include=['*.foo'], exclude=['blah.*'], allow_empty=False)"); scratch.file("pkg/blah.foo"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); reporter.removeHandler(failFastHandler); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); String expectedEventString = "all files in the glob have been excluded, but allow_empty is set to False (the " + "default value of allow_empty can be set with --incompatible_disallow_empty_glob)."; assertContainsEvent(expectedEventString); scratch.overwriteFile( "pkg/BUILD", "x = glob(include=['*.foo'], exclude=['blah.*'], allow_empty=False) # comment"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("pkg/BUILD")).build(), Root.fromPath(rootDirectory)); pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent(expectedEventString); } @Test public void testGlobDisallowEmpty_starlarkOption_wasEmptyDueToExcludeAndStaysEmpty() throws Exception { preparePackageLoadingWithCustomStarklarkSemanticsOptions( Options.parse(BuildLanguageOptions.class, "--incompatible_disallow_empty_glob=true") .getOptions(), rootDirectory); scratch.file("pkg/BUILD", "x = glob(include=['*.foo'], exclude=['blah.*'])"); scratch.file("pkg/blah.foo"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); reporter.removeHandler(failFastHandler); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); String expectedEventString = "all files in the glob have been excluded, but allow_empty is set to False (the " + "default value of allow_empty can be set with --incompatible_disallow_empty_glob)."; assertContainsEvent(expectedEventString); scratch.overwriteFile("pkg/BUILD", "x = glob(include=['*.foo'], exclude=['blah.*']) # comment"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("pkg/BUILD")).build(), Root.fromPath(rootDirectory)); pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent(expectedEventString); } @Test public void testGlobDisallowEmpty_functionParam_wasEmptyAndBecomesNonEmpty() throws Exception { scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'], allow_empty=False)"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); reporter.removeHandler(failFastHandler); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent( "glob pattern '*.foo' didn't match anything, but allow_empty is set to False (the " + "default value of allow_empty can be set with --incompatible_disallow_empty_glob)."); scratch.file("pkg/blah.foo"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("pkg/blah.foo")).build(), Root.fromPath(rootDirectory)); reporter.addHandler(failFastHandler); eventCollector.clear(); pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isFalse(); assertNoEvents(); } @Test public void testGlobDisallowEmpty_starlarkOption_wasEmptyAndBecomesNonEmpty() throws Exception { preparePackageLoadingWithCustomStarklarkSemanticsOptions( Options.parse(BuildLanguageOptions.class, "--incompatible_disallow_empty_glob=true") .getOptions(), rootDirectory); scratch.file("pkg/BUILD", "x = " + "glob(['*.foo'])"); invalidatePackages(); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//pkg")); reporter.removeHandler(failFastHandler); Package pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent( "glob pattern '*.foo' didn't match anything, but allow_empty is set to False (the " + "default value of allow_empty can be set with --incompatible_disallow_empty_glob)."); scratch.file("pkg/blah.foo"); getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("pkg/blah.foo")).build(), Root.fromPath(rootDirectory)); reporter.addHandler(failFastHandler); eventCollector.clear(); pkg = validPackage(skyKey); assertThat(pkg.containsErrors()).isFalse(); assertNoEvents(); } @Test public void testPackageRecordsLoadedModules() throws Exception { scratch.file("p/BUILD", "load('a.bzl', 'a'); load(':b.bzl', 'b')"); scratch.file("p/a.bzl", "load('c.bzl', 'c'); a = c"); scratch.file("p/b.bzl", "load(':c.bzl', 'c'); b = c"); scratch.file("p/c.bzl", "c = 0"); // load p preparePackageLoading(rootDirectory); SkyKey skyKey = PackageValue.key(PackageIdentifier.parse("@//p")); Package p = validPackageWithoutErrors(skyKey); // Keys are load strings as they appear in the source (notice ":" in one of them). Map<String, Module> pLoads = p.getLoads(); assertThat(pLoads.keySet().toString()).isEqualTo("[a.bzl, :b.bzl]"); // subgraph a Module a = pLoads.get("a.bzl"); assertThat(a.toString()).isEqualTo("<module //p:a.bzl>"); Map<String, Module> aLoads = BazelModuleContext.of(a).loads(); assertThat(aLoads.keySet().toString()).isEqualTo("[c.bzl]"); Module cViaA = aLoads.get("c.bzl"); assertThat(cViaA.toString()).isEqualTo("<module //p:c.bzl>"); // subgraph b Module b = pLoads.get(":b.bzl"); assertThat(b.toString()).isEqualTo("<module //p:b.bzl>"); Map<String, Module> bLoads = BazelModuleContext.of(b).loads(); assertThat(bLoads.keySet().toString()).isEqualTo("[:c.bzl]"); Module cViaB = bLoads.get(":c.bzl"); assertThat(cViaB).isSameInstanceAs(cViaA); assertThat(cViaA.getGlobal("c")).isEqualTo(StarlarkInt.of(0)); } @Test public void veryBrokenPackagePostsDoneToProgressReceiver() throws Exception { reporter.removeHandler(failFastHandler); scratch.file("pkg/BUILD", "load('//does_not:exist.bzl', 'broken'"); SkyKey key = PackageValue.key(PackageIdentifier.parse("@//pkg")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate(getSkyframeExecutor(), key, false, reporter); assertThatEvaluationResult(result).hasError(); assertThat(getSkyframeExecutor().getPackageProgressReceiver().progressState()) .isEqualTo(new Pair<String, String>("1 packages loaded", "")); } @Test public void testLegacyGlobbingEncountersSymlinkCycleAndThrowsIOException() throws Exception { reporter.removeHandler(failFastHandler); getSkyframeExecutor().turnOffSyscallCacheForTesting(); // When a package's BUILD file and the relevant filesystem state is such that legacy globbing // will encounter an IOException due to a directory symlink cycle, Path fooBUILDPath = scratch.file("foo/BUILD", "glob(['cycle/**/foo.txt'])"); Path fooCyclePath = fooBUILDPath.getParentDirectory().getChild("cycle"); FileSystemUtils.ensureSymbolicLink(fooCyclePath, fooCyclePath); IOException ioExnFromFS = assertThrows(IOException.class, () -> fooCyclePath.statIfFound(Symlinks.FOLLOW)); // And it is indeed the case that the FileSystem throws an IOException when the cycle's Path is // stat'd (following symlinks, as legacy globbing does). assertThat(ioExnFromFS).hasMessageThat().contains("Too many levels of symbolic links"); // Then, when we evaluate the PackageValue node for the Package in keepGoing mode, SkyKey pkgKey = PackageValue.key(PackageIdentifier.parse("@//foo")); EvaluationResult<PackageValue> result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), pkgKey, /*keepGoing=*/ true, reporter); // The result is a *non-transient* Skyframe error. assertThatEvaluationResult(result).hasErrorEntryForKeyThat(pkgKey).isNotTransient(); // And that error is a NoSuchPackageException assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(pkgKey) .hasExceptionThat() .isInstanceOf(NoSuchPackageException.class); // With a useful error message, assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(pkgKey) .hasExceptionThat() .hasMessageThat() .contains("Symlink cycle: /workspace/foo/cycle"); // And appropriate Skyframe root cause (N.B. since we want PackageFunction to rethrow in // situations like this, we want the PackageValue node to be its own root cause). assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(pkgKey) .rootCauseOfExceptionIs(pkgKey); // Then, when we modify the BUILD file so as to force package loading, scratch.overwriteFile( "foo/BUILD", "glob(['cycle/**/foo.txt']) # dummy comment to force package loading"); // But we don't make any filesystem changes that would invalidate the GlobValues, meaning that // PackageFunction will observe cache hits from Skyframe globbing, // // And we also have our filesystem blow up if the directory symlink cycle is encountered (thus, // the absence of a crash indicates the lack of legacy globbing), fs.stubStatError( fooCyclePath, new IOException() { @Override public String getMessage() { throw new IllegalStateException("should't get here!"); } }); // And we evaluate the PackageValue node for the Package in keepGoing mode, getSkyframeExecutor() .invalidateFilesUnderPathForTesting( reporter, ModifiedFileSet.builder().modify(PathFragment.create("foo/BUILD")).build(), Root.fromPath(rootDirectory)); // The results are exactly the same as before, result = SkyframeExecutorTestUtils.evaluate( getSkyframeExecutor(), pkgKey, /*keepGoing=*/ true, reporter); assertThatEvaluationResult(result).hasErrorEntryForKeyThat(pkgKey).isNotTransient(); assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(pkgKey) .hasExceptionThat() .isInstanceOf(NoSuchPackageException.class); assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(pkgKey) .hasExceptionThat() .hasMessageThat() .contains("Symlink cycle: /workspace/foo/cycle"); assertThatEvaluationResult(result) .hasErrorEntryForKeyThat(pkgKey) .rootCauseOfExceptionIs(pkgKey); // Thus showing that clean and incremental package loading have the same semantics in the // presence of a symlink cycle encountered during glob evaluation. } private static void assertDetailedExitCode( Exception exception, PackageLoading.Code expectedPackageLoadingCode) { assertThat(exception).isInstanceOf(DetailedException.class); DetailedExitCode detailedExitCode = ((DetailedException) exception).getDetailedExitCode(); assertThat(detailedExitCode.getExitCode()).isEqualTo(ExitCode.BUILD_FAILURE); assertThat(detailedExitCode.getFailureDetail().getPackageLoading().getCode()) .isEqualTo(expectedPackageLoadingCode); } /** * Tests of the prelude file functionality. * * <p>This is in a separate BuildViewTestCase because we override the prelude label for the test. * (The prelude label is configured differently between Bazel and Blaze.) */ @RunWith(JUnit4.class) public static class PreludeTest extends BuildViewTestCase { private final CustomInMemoryFs fs = new CustomInMemoryFs(new ManualClock()); @Override protected FileSystem createFileSystem() { return fs; } @Override protected ConfiguredRuleClassProvider createRuleClassProvider() { ConfiguredRuleClassProvider.Builder builder = new ConfiguredRuleClassProvider.Builder(); // addStandardRules() may call setPrelude(), so do it first. TestRuleClassProvider.addStandardRules(builder); builder.setPrelude("//tools/build_rules:test_prelude"); return builder.build(); } @Test public void testPreludeDefinedSymbolIsUsable() throws Exception { scratch.file("tools/build_rules/BUILD"); scratch.file( "tools/build_rules/test_prelude", // "foo = 'FOO'"); scratch.file( "pkg/BUILD", // "print(foo)"); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("FOO"); } @Test public void testPreludeAutomaticallyReexportsLoadedSymbols() throws Exception { scratch.file("tools/build_rules/BUILD"); scratch.file( "tools/build_rules/test_prelude", // "load('//util:common.bzl', 'foo')"); scratch.file("util/BUILD"); scratch.file( "util/common.bzl", // "foo = 'FOO'"); scratch.file( "pkg/BUILD", // "print(foo)"); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("FOO"); } // TODO(brandjon): Invert this test once the prelude is a module instead of a syntactic // mutation on BUILD files. @Test public void testPreludeCanExportUnderscoreSymbols() throws Exception { scratch.file("tools/build_rules/BUILD"); scratch.file( "tools/build_rules/test_prelude", // "_foo = 'FOO'"); scratch.file( "pkg/BUILD", // "print(_foo)"); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("FOO"); } @Test public void testPreludeCanShadowPredeclareds() throws Exception { scratch.file("tools/build_rules/BUILD"); scratch.file( "tools/build_rules/test_prelude", // "cc_library = 'FOO'"); scratch.file( "pkg/BUILD", // "print(cc_library)"); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("FOO"); } @Test public void testPreludeSymbolCannotBeMutated() throws Exception { scratch.file("tools/build_rules/BUILD"); scratch.file( "tools/build_rules/test_prelude", // "foo = ['FOO']"); scratch.file( "pkg/BUILD", // "foo.append('BAR')"); reporter.removeHandler(failFastHandler); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("trying to mutate a frozen list value"); } @Test public void testPreludeCanAccessBzlDialectFeatures() throws Exception { scratch.file("tools/build_rules/BUILD"); // Test both bzl symbols and syntax (e.g. function defs). scratch.file( "tools/build_rules/test_prelude", // "def foo():", " return native.glob"); scratch.file( "pkg/BUILD", // "print(foo())"); getConfiguredTarget("//pkg:BUILD"); // Prelude can access native.glob (though only a BUILD thread can call it). assertContainsEvent("<built-in method glob of native value>"); } @Test public void testPreludeNeedNotBePresent() throws Exception { scratch.file( "pkg/BUILD", // "print('FOO')"); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("FOO"); } @Test public void testPreludeNeedNotBePresent_evenWhenPackageIs() throws Exception { scratch.file("tools/build_rules/BUILD"); scratch.file( "pkg/BUILD", // "print('FOO')"); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("FOO"); } @Test public void testPreludeFileNotRecognizedWithoutPackage() throws Exception { scratch.file( "tools/build_rules/test_prelude", // "foo = 'FOO'"); scratch.file( "pkg/BUILD", // "print(foo)"); // The prelude file is not found without a corresponding package to contain it. BUILD files // get processed as if no prelude file is present. reporter.removeHandler(failFastHandler); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("name 'foo' is not defined"); } @Test public void testPreludeFailsWhenErrorInPreludeFile() throws Exception { scratch.file("tools/build_rules/BUILD"); scratch.file( "tools/build_rules/test_prelude", // "1//0", // <-- dynamic error "foo = 'FOO'"); scratch.file( "pkg/BUILD", // "print(foo)"); reporter.removeHandler(failFastHandler); getConfiguredTarget("//pkg:BUILD"); assertContainsEvent( "File \"/workspace/tools/build_rules/test_prelude\", line 1, column 2, in <toplevel>"); assertContainsEvent("Error: integer division by zero"); } @Test public void testPreludeWorksEvenWhenPreludePackageInError() throws Exception { scratch.file( "tools/build_rules/BUILD", // "1//0"); // <-- dynamic error scratch.file( "tools/build_rules/test_prelude", // "foo = 'FOO'"); scratch.file( "pkg/BUILD", // "print(foo)"); // Succeeds because prelude loading is only dependent on the prelude package's existence, not // its evaluation. getConfiguredTarget("//pkg:BUILD"); assertContainsEvent("FOO"); } // Another hypothetical test case we could try: Confirm that it's possible to explicitly load // the prelude file as a regular .bzl. We don't bother testing this use case because, aside from // being arguably pathological, it is currently impossible in practice: The prelude label // doesn't end with ".bzl" and isn't configurable by the user. We also want to eliminate the // prelude, so there's no intention of adding such a feature. // Another possible test case: Verify how prelude applies to WORKSPACE files. } private static class CustomInMemoryFs extends InMemoryFileSystem { private abstract static class FileStatusOrException { abstract FileStatus get() throws IOException; private static class ExceptionImpl extends FileStatusOrException { private final IOException exn; private ExceptionImpl(IOException exn) { this.exn = exn; } @Override FileStatus get() throws IOException { throw exn; } } private static class FileStatusImpl extends FileStatusOrException { @Nullable private final FileStatus fileStatus; private FileStatusImpl(@Nullable FileStatus fileStatus) { this.fileStatus = fileStatus; } @Override @Nullable FileStatus get() { return fileStatus; } } } private final Map<Path, FileStatusOrException> stubbedStats = Maps.newHashMap(); private final Set<Path> makeUnreadableAfterReaddir = Sets.newHashSet(); private final Map<Path, IOException> pathsToErrorOnGetInputStream = Maps.newHashMap(); public CustomInMemoryFs(ManualClock manualClock) { super(manualClock, DigestHashFunction.SHA256); } public void stubStat(Path path, @Nullable FileStatus stubbedResult) { stubbedStats.put(path, new FileStatusOrException.FileStatusImpl(stubbedResult)); } public void stubStatError(Path path, IOException stubbedResult) { stubbedStats.put(path, new FileStatusOrException.ExceptionImpl(stubbedResult)); } @Override public FileStatus statIfFound(Path path, boolean followSymlinks) throws IOException { if (stubbedStats.containsKey(path)) { return stubbedStats.get(path).get(); } return super.statIfFound(path, followSymlinks); } public void scheduleMakeUnreadableAfterReaddir(Path path) { makeUnreadableAfterReaddir.add(path); } @Override public Collection<Dirent> readdir(Path path, boolean followSymlinks) throws IOException { Collection<Dirent> result = super.readdir(path, followSymlinks); if (makeUnreadableAfterReaddir.contains(path)) { path.setReadable(false); } return result; } public void throwExceptionOnGetInputStream(Path path, IOException exn) { pathsToErrorOnGetInputStream.put(path, exn); } @Override protected InputStream getInputStream(Path path) throws IOException { IOException exnToThrow = pathsToErrorOnGetInputStream.get(path); if (exnToThrow != null) { throw exnToThrow; } return super.getInputStream(path); } } }
apache-2.0
woniukeji/jianguo
qiaqia/src/main/java/com/haibin/qiaqia/entity/Market.java
549
package com.haibin.qiaqia.entity; import java.util.List; /** * Created by cai on 2016/6/25. */ public class Market { private List<ListMarket> list_chao_class; public List<ListMarket> getList_chao_class() { return list_chao_class; } public void setList_chao_class(List<ListMarket> list_chao_class) { this.list_chao_class = list_chao_class; } @Override public String toString() { return "Market{" + "listMarkets=" + list_chao_class.toString() + '}'; } }
apache-2.0
rouies/cosmos
cosmos-parent/cosmos-workflow/src/main/java/com/cosmos/workflow/runtime/xml/initializer/SSHShellActivityInitializer.java
2585
package com.cosmos.workflow.runtime.xml.initializer; import java.util.HashMap; import java.util.List; import org.dom4j.Element; import com.cosmos.utils.text.StringUtils; import com.cosmos.workflow.activities.sequence.action.network.ssh.SSHShellActivity; import com.cosmos.workflow.runtime.WorkflowRuntimeException; import com.cosmos.workflow.runtime.xml.IXmlInitializer; public class SSHShellActivityInitializer implements IXmlInitializer<SSHShellActivity>{ @Override public void init(SSHShellActivity activity, Element item) throws WorkflowRuntimeException { String client = item.attributeValue("client"); String charset = item.attributeValue("charset"); String processor = item.attributeValue("processor"); String timeout = item.attributeValue("timeout"); String endChars = item.attributeValue("endChars"); if(StringUtils.isEmptyOrNull(endChars)){ throw new WorkflowRuntimeException("必须指明至少一个结束符"); } activity.setEndChars(endChars.split(",")); if(StringUtils.isEmptyOrNull(client)){ throw new WorkflowRuntimeException("必须指明至少一个client"); } activity.setClient(client); if(StringUtils.isEmptyOrNull(charset)){ charset = "UTF-8"; } activity.setCharset(charset); activity.setProcessor(processor); if(timeout != null){ try { activity.setTimeout(new Integer(timeout)); } catch (NumberFormatException e) { activity.setTimeout(0); } } Element config = item.element("ssh-environment"); if(config != null){ @SuppressWarnings("unchecked") List<Element> properties = config.elements("property"); if(properties.size() !=0){ HashMap<String, String> pr = new HashMap<String, String>(); for (Element property : properties) { pr.put(property.attributeValue("key"), property.attributeValue("value")); } activity.setEnv(pr); } } @SuppressWarnings("unchecked") List<Element> commands = item.elements("ssh-command"); for (int i = 0,len = commands.size(); i < len; i++) { Element commandItem = commands.get(i); String args = commandItem.attributeValue("arguments"); String out = commandItem.attributeValue("out"); String command = commandItem.getTextTrim(); String[] arguments = StringUtils.isEmptyOrNull(args) ? new String[0] : args.split(","); if(StringUtils.isEmptyOrNull(command)){ throw new WorkflowRuntimeException("ssh-command:命令不能为空!"); } if(StringUtils.isEmptyOrNull(out)){ throw new WorkflowRuntimeException("ssh-command:必须!"); } activity.appendCommnad(command, out, arguments); } } }
apache-2.0
vega113/WaveInCloud
src/org/waveprotocol/wave/client/StageTwo.java
27885
/** * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.waveprotocol.wave.client; import com.google.common.base.Preconditions; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.Command; import org.waveprotocol.wave.client.account.ProfileManager; import org.waveprotocol.wave.client.account.impl.ProfileManagerImpl; import org.waveprotocol.wave.client.common.util.AsyncHolder; import org.waveprotocol.wave.client.common.util.ClientPercentEncoderDecoder; import org.waveprotocol.wave.client.common.util.CountdownLatch; import org.waveprotocol.wave.client.concurrencycontrol.LiveChannelBinder; import org.waveprotocol.wave.client.concurrencycontrol.MuxConnector; import org.waveprotocol.wave.client.concurrencycontrol.WaveletOperationalizer; import org.waveprotocol.wave.client.doodad.DoodadInstallers; import org.waveprotocol.wave.client.doodad.diff.DiffAnnotationHandler; import org.waveprotocol.wave.client.doodad.diff.DiffDeleteRenderer; import org.waveprotocol.wave.client.doodad.link.LinkAnnotationHandler; import org.waveprotocol.wave.client.doodad.link.LinkAnnotationHandler.LinkAttributeAugmenter; import org.waveprotocol.wave.client.doodad.selection.SelectionAnnotationHandler; import org.waveprotocol.wave.client.doodad.title.TitleAnnotationHandler; import org.waveprotocol.wave.client.editor.content.Registries; import org.waveprotocol.wave.client.editor.content.misc.StyleAnnotationHandler; import org.waveprotocol.wave.client.gadget.Gadget; import org.waveprotocol.wave.client.scheduler.Scheduler.Task; import org.waveprotocol.wave.client.scheduler.SchedulerInstance; import org.waveprotocol.wave.client.state.BlipReadStateMonitor; import org.waveprotocol.wave.client.state.BlipReadStateMonitorImpl; import org.waveprotocol.wave.client.state.ThreadReadStateMonitor; import org.waveprotocol.wave.client.state.ThreadReadStateMonitorImpl; import org.waveprotocol.wave.client.util.ClientFlags; import org.waveprotocol.wave.client.wave.InteractiveDocument; import org.waveprotocol.wave.client.wave.LazyContentDocument; import org.waveprotocol.wave.client.wave.LocalSupplementedWave; import org.waveprotocol.wave.client.wave.LocalSupplementedWaveImpl; import org.waveprotocol.wave.client.wave.RegistriesHolder; import org.waveprotocol.wave.client.wave.SimpleDiffDoc; import org.waveprotocol.wave.client.wave.WaveDocuments; import org.waveprotocol.wave.client.wavepanel.impl.diff.DiffController; import org.waveprotocol.wave.client.wavepanel.impl.reader.Reader; import org.waveprotocol.wave.client.wavepanel.render.BlipPager; import org.waveprotocol.wave.client.wavepanel.render.DocumentRegistries; import org.waveprotocol.wave.client.wavepanel.render.FullDomWaveRendererImpl; import org.waveprotocol.wave.client.wavepanel.render.InlineAnchorLiveRenderer; import org.waveprotocol.wave.client.wavepanel.render.LiveConversationViewRenderer; import org.waveprotocol.wave.client.wavepanel.render.PagingHandlerProxy; import org.waveprotocol.wave.client.wavepanel.render.ReplyManager; import org.waveprotocol.wave.client.wavepanel.render.ShallowBlipRenderer; import org.waveprotocol.wave.client.wavepanel.render.UndercurrentShallowBlipRenderer; import org.waveprotocol.wave.client.wavepanel.view.ModelIdMapper; import org.waveprotocol.wave.client.wavepanel.view.ModelIdMapperImpl; import org.waveprotocol.wave.client.wavepanel.view.ViewIdMapper; import org.waveprotocol.wave.client.wavepanel.view.dom.DomAsViewProvider; import org.waveprotocol.wave.client.wavepanel.view.dom.ModelAsViewProvider; import org.waveprotocol.wave.client.wavepanel.view.dom.ModelAsViewProviderImpl; import org.waveprotocol.wave.client.wavepanel.view.dom.full.BlipQueueRenderer; import org.waveprotocol.wave.client.wavepanel.view.dom.full.DomRenderer; import org.waveprotocol.wave.client.wavepanel.view.dom.full.ViewFactories; import org.waveprotocol.wave.client.wavepanel.view.dom.full.ViewFactory; import org.waveprotocol.wave.client.wavepanel.view.dom.full.WavePanelResourceLoader; import org.waveprotocol.wave.common.logging.LoggerBundle; import org.waveprotocol.wave.concurrencycontrol.channel.OperationChannelMultiplexer; import org.waveprotocol.wave.concurrencycontrol.channel.OperationChannelMultiplexerImpl; import org.waveprotocol.wave.concurrencycontrol.channel.OperationChannelMultiplexerImpl.LoggerContext; import org.waveprotocol.wave.concurrencycontrol.channel.ViewChannelFactory; import org.waveprotocol.wave.concurrencycontrol.channel.ViewChannelImpl; import org.waveprotocol.wave.concurrencycontrol.channel.WaveViewService; import org.waveprotocol.wave.concurrencycontrol.common.UnsavedDataListenerFactory; import org.waveprotocol.wave.model.conversation.ObservableConversationView; import org.waveprotocol.wave.model.conversation.WaveBasedConversationView; import org.waveprotocol.wave.model.document.indexed.IndexedDocumentImpl; import org.waveprotocol.wave.model.document.operation.DocInitialization; import org.waveprotocol.wave.model.id.IdConstants; import org.waveprotocol.wave.model.id.IdFilter; import org.waveprotocol.wave.model.id.IdGenerator; import org.waveprotocol.wave.model.id.IdGeneratorImpl; import org.waveprotocol.wave.model.id.IdGeneratorImpl.Seed; import org.waveprotocol.wave.model.id.IdURIEncoderDecoder; import org.waveprotocol.wave.model.id.WaveId; import org.waveprotocol.wave.model.id.WaveletId; import org.waveprotocol.wave.model.schema.SchemaProvider; import org.waveprotocol.wave.model.supplement.LiveSupplementedWaveImpl; import org.waveprotocol.wave.model.supplement.ObservablePrimitiveSupplement; import org.waveprotocol.wave.model.supplement.ObservableSupplementedWave; import org.waveprotocol.wave.model.supplement.SupplementedWaveImpl.DefaultFollow; import org.waveprotocol.wave.model.supplement.WaveletBasedSupplement; import org.waveprotocol.wave.model.util.FuzzingBackOffScheduler; import org.waveprotocol.wave.model.util.FuzzingBackOffScheduler.CollectiveScheduler; import org.waveprotocol.wave.model.util.Scheduler; import org.waveprotocol.wave.model.version.HashedVersion; import org.waveprotocol.wave.model.version.HashedVersionFactory; import org.waveprotocol.wave.model.version.HashedVersionZeroFactoryImpl; import org.waveprotocol.wave.model.wave.ParticipantId; import org.waveprotocol.wave.model.wave.Wavelet; import org.waveprotocol.wave.model.wave.data.DocumentFactory; import org.waveprotocol.wave.model.wave.data.ObservableWaveletData; import org.waveprotocol.wave.model.wave.data.WaveViewData; import org.waveprotocol.wave.model.wave.data.impl.ObservablePluggableMutableDocument; import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl; import org.waveprotocol.wave.model.wave.opbased.ObservableWaveView; import org.waveprotocol.wave.model.wave.opbased.OpBasedWavelet; import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl; import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl.WaveletConfigurator; import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl.WaveletFactory; import java.util.Collections; import java.util.Map; /** * The second stage of client code. * <p> * This stage builds the wave model in memory, and also opens the channel to * make it live. Rendering code that operates on the model is also established * in this stage. * */ public interface StageTwo { /** @return the (live) conversations in the wave. */ ObservableConversationView getConversations(); /** @return the core wave. */ ObservableWaveView getWave(); /** @return the signed-in user's (live) supplementary data in the wave. */ LocalSupplementedWave getSupplement(); /** @return live blip read/unread information. */ BlipReadStateMonitor getReadMonitor(); /** @return the registry of document objects used for conversational blips. */ WaveDocuments<? extends InteractiveDocument> getDocumentRegistry(); /** @return the provider of view objects given model objects. */ ModelAsViewProvider getModelAsViewProvider(); /** @return the profile manager. */ ProfileManager getProfileManager(); /** return the id generator. */ IdGenerator getIdGenerator(); /** @return the communication channel connector. */ MuxConnector getConnector(); /** * @return the blip content renderer, which needs to be flushed by anything * requiring synchronous rendering. */ BlipQueueRenderer getBlipQueue(); /** @return controller of diff state. */ DiffController getDiffController(); /** @return the signed in user. */ ParticipantId getSignedInUser(); /** @return a unique string identifying this session. */ String getSessionId(); /** @return stage one. */ StageOne getStageOne(); /** * Default implementation of the stage two configuration. Each component is * defined by a factory method, any of which may be overridden in order to * stub out some dependencies. Circular dependencies are not detected. * */ public static abstract class DefaultProvider extends AsyncHolder.Impl<StageTwo> implements StageTwo { // Asynchronously constructed and external dependencies protected final StageOne stageOne; private WaveViewData waveData; // // Synchronously constructed dependencies. // // Client stuff. private String sessionId; private ParticipantId signedInuser; private CollectiveScheduler rpcScheduler; // Wave stack. private IdGenerator idGenerator; private WaveDocuments<LazyContentDocument> documentRegistry; private WaveletOperationalizer wavelets; private WaveViewImpl<OpBasedWavelet> wave; private MuxConnector connector; // Model objects private ProfileManager profileManager; private ObservableConversationView conversations; private LocalSupplementedWave supplement; private BlipReadStateMonitor readMonitor; // State Monitors private ThreadReadStateMonitor threadReadStateMonitor; // Rendering objects. private ViewIdMapper viewIdMapper; private ShallowBlipRenderer blipDetailer; private DomRenderer renderer; private BlipQueueRenderer queueRenderer; private ModelAsViewProvider modelAsView; private DiffController diffController; public DefaultProvider(StageOne stageOne) { this.stageOne = stageOne; } /** * Creates the second stage. */ @Override protected void create(final Accessor<StageTwo> whenReady) { onStageInit(); final CountdownLatch synchronizer = CountdownLatch.create(2, new Command() { @Override public void execute() { install(); onStageLoaded(); whenReady.use(DefaultProvider.this); } }); fetchWave(new Accessor<WaveViewData>() { @Override public void use(WaveViewData x) { waveData = x; synchronizer.tick(); } }); // Defer everything else, to let the RPC go out. SchedulerInstance.getMediumPriorityTimer().scheduleDelayed(new Task() { @Override public void execute() { installStatics(); synchronizer.tick(); } }, 20); } /** Notifies this provider that the stage is about to be loaded. */ protected void onStageInit() { } /** Notifies this provider that the stage has been loaded. */ protected void onStageLoaded() { } @Override public final StageOne getStageOne() { return stageOne; } @Override public final String getSessionId() { return sessionId == null ? sessionId = createSessionId() : sessionId; } protected final ViewIdMapper getViewIdMapper() { return viewIdMapper == null ? viewIdMapper = createViewIdMapper() : viewIdMapper; } protected final ShallowBlipRenderer getBlipDetailer() { return blipDetailer == null ? blipDetailer = createBlipDetailer() : blipDetailer; } protected final DomRenderer getRenderer() { return renderer == null ? renderer = createRenderer() : renderer; } protected final ThreadReadStateMonitor getThreadReadStateMonitor() { return threadReadStateMonitor == null ? threadReadStateMonitor = createThreadReadStateMonitor() : threadReadStateMonitor; } @Override public final BlipQueueRenderer getBlipQueue() { return queueRenderer == null ? queueRenderer = createBlipQueueRenderer() : queueRenderer; } @Override public final ModelAsViewProvider getModelAsViewProvider() { return modelAsView == null ? modelAsView = createModelAsViewProvider() : modelAsView; } @Override public final ParticipantId getSignedInUser() { return signedInuser == null ? signedInuser = createSignedInUser() : signedInuser; } @Override public final IdGenerator getIdGenerator() { return idGenerator == null ? idGenerator = createIdGenerator() : idGenerator; } /** @return the scheduler to use for RPCs. */ protected final CollectiveScheduler getRpcScheduler() { return rpcScheduler == null ? rpcScheduler = createRpcScheduler() : rpcScheduler; } @Override public final ProfileManager getProfileManager() { return profileManager == null ? profileManager = createProfileManager() : profileManager; } @Override public final MuxConnector getConnector() { return connector == null ? connector = createConnector() : connector; } @Override public final WaveViewImpl<OpBasedWavelet> getWave() { return wave == null ? wave = createWave() : wave; } protected final WaveletOperationalizer getWavelets() { return wavelets == null ? wavelets = createWavelets() : wavelets; } @Override public final ObservableConversationView getConversations() { return conversations == null ? conversations = createConversations() : conversations; } @Override public final LocalSupplementedWave getSupplement() { return supplement == null ? supplement = createSupplement() : supplement; } @Override public final BlipReadStateMonitor getReadMonitor() { return readMonitor == null ? readMonitor = createReadMonitor() : readMonitor; } @Override public final WaveDocuments<LazyContentDocument> getDocumentRegistry() { return documentRegistry == null ? documentRegistry = createDocumentRegistry() : documentRegistry; } protected final WaveViewData getWaveData() { Preconditions.checkState(waveData != null, "wave not ready"); return waveData; } @Override public final DiffController getDiffController() { return diffController == null ? diffController = createDiffController() : diffController; } /** @return the id mangler for model objects. Subclasses may override. */ protected ModelIdMapper createModelIdMapper() { return ModelIdMapperImpl.create(getConversations(), "UC"); } /** @return the id mangler for view objects. Subclasses may override. */ protected ViewIdMapper createViewIdMapper() { return new ViewIdMapper(createModelIdMapper()); } /** @return the id of the signed-in user. Subclassses may override. */ protected abstract ParticipantId createSignedInUser(); /** @return the unique id for this client session. */ protected abstract String createSessionId(); /** @return the id generator for model object. Subclasses may override. */ protected IdGenerator createIdGenerator() { final String seed = getSessionId(); // Replace with session. return new IdGeneratorImpl(getSignedInUser().getDomain(), new Seed() { @Override public String get() { return seed; } }); } /** @return the scheduler to use for RPCs. Subclasses may override. */ protected CollectiveScheduler createRpcScheduler() { // Use a scheduler that runs closely-timed tasks at the same time. return new OptimalGroupingScheduler(SchedulerInstance.getLowPriorityTimer()); } protected WaveletOperationalizer createWavelets() { return WaveletOperationalizer.create(getWaveData().getWaveId(), getSignedInUser()); } protected WaveViewImpl<OpBasedWavelet> createWave() { WaveViewData snapshot = getWaveData(); // The operationalizer makes the wavelets function via operation control. // The hookup with concurrency-control and remote operation streams occurs // later in createUpgrader(). final WaveletOperationalizer operationalizer = getWavelets(); WaveletFactory<OpBasedWavelet> waveletFactory = new WaveletFactory<OpBasedWavelet>() { @Override public OpBasedWavelet create(WaveId waveId, WaveletId id, ParticipantId creator) { long now = System.currentTimeMillis(); ObservableWaveletData data = new WaveletDataImpl(id, creator, now, 0L, HashedVersion.unsigned(0), now, waveId, getDocumentRegistry()); return operationalizer.operationalize(data); } }; WaveViewImpl<OpBasedWavelet> wave = WaveViewImpl.create(waveletFactory, getWaveData().getWaveId(), getIdGenerator(), getSignedInUser(), WaveletConfigurator.ADD_CREATOR); // Populate the initial state. for (ObservableWaveletData waveletData : snapshot.getWavelets()) { wave.addWavelet(operationalizer.operationalize(waveletData)); } return wave; } /** @return the conversations in the wave. Subclasses may override. */ protected ObservableConversationView createConversations() { return WaveBasedConversationView.create(getWave(), getIdGenerator()); } /** @return the user supplement of the wave. Subclasses may override. */ protected LocalSupplementedWave createSupplement() { Wavelet udw = getWave().getUserData(); if (udw == null) { udw = getWave().createUserData(); } ObservablePrimitiveSupplement state = WaveletBasedSupplement.create(udw); ObservableSupplementedWave live = new LiveSupplementedWaveImpl( state, getWave(), getSignedInUser(), DefaultFollow.ALWAYS, getConversations()); return LocalSupplementedWaveImpl.create(getWave(), live); } /** @return a supplement to the supplement, to get exact read/unread counts. */ protected BlipReadStateMonitor createReadMonitor() { return BlipReadStateMonitorImpl.create( getWave().getWaveId(), getSupplement(), getConversations()); } /** @return the registry of documents in the wave. Subclasses may override. */ protected WaveDocuments<LazyContentDocument> createDocumentRegistry() { IndexedDocumentImpl.performValidation = false; DocumentFactory<?> dataDocFactory = ObservablePluggableMutableDocument.createFactory(createSchemas()); DocumentFactory<LazyContentDocument> blipDocFactory = new DocumentFactory<LazyContentDocument>() { private final Registries registries = RegistriesHolder.get(); @Override public LazyContentDocument create( WaveletId waveletId, String docId, DocInitialization content) { // TODO(piotrkaleta,hearnden): hook up real diff state. SimpleDiffDoc noDiff = SimpleDiffDoc.create(content, null); return LazyContentDocument.create(registries, noDiff); } }; return WaveDocuments.create(blipDocFactory, dataDocFactory); } protected abstract SchemaProvider createSchemas(); /** @return the RPC interface for wave communication. */ protected abstract WaveViewService createWaveViewService(); /** @return upgrader for activating stacklets. Subclasses may override. */ protected MuxConnector createConnector() { LoggerBundle logger = LoggerBundle.NOP_IMPL; LoggerContext loggers = new LoggerContext(logger, logger, logger, logger); IdURIEncoderDecoder uriCodec = new IdURIEncoderDecoder(new ClientPercentEncoderDecoder()); HashedVersionFactory hashFactory = new HashedVersionZeroFactoryImpl(uriCodec); Scheduler scheduler = new FuzzingBackOffScheduler.Builder(getRpcScheduler()) .setInitialBackOffMs(ClientFlags.get().initialRpcBackoffMs()) .setMaxBackOffMs(ClientFlags.get().maxRpcBackoffMs()) .setRandomisationFactor(0.5) .build(); ViewChannelFactory viewFactory = ViewChannelImpl.factory(createWaveViewService(), logger); UnsavedDataListenerFactory unsyncedListeners = UnsavedDataListenerFactory.NONE; WaveletId udwId = getIdGenerator().newUserDataWaveletId(getSignedInUser().getAddress()); final IdFilter filter = IdFilter.of(Collections.singleton(udwId), Collections.singleton(IdConstants.CONVERSATION_WAVELET_PREFIX)); WaveletDataImpl.Factory snapshotFactory = WaveletDataImpl.Factory.create(getDocumentRegistry()); final OperationChannelMultiplexer mux = new OperationChannelMultiplexerImpl(getWave().getWaveId(), viewFactory, snapshotFactory, loggers, unsyncedListeners, scheduler, hashFactory); final WaveViewImpl<OpBasedWavelet> wave = getWave(); return new MuxConnector() { @Override public void connect(Command onOpened) { LiveChannelBinder.openAndBind(getWavelets(), wave, getDocumentRegistry(), mux, filter, onOpened); } @Override public void close() { mux.close(); } }; } /** @return the manager of user identities. Subclasses may override. */ protected ProfileManager createProfileManager() { return new ProfileManagerImpl(); } /** @return the renderer of intrinsic blip state. Subclasses may override. */ protected ShallowBlipRenderer createBlipDetailer() { return new UndercurrentShallowBlipRenderer(getProfileManager(), getSupplement()); } /** @return the thread state monitor. Subclasses may override. */ protected ThreadReadStateMonitor createThreadReadStateMonitor() { return ThreadReadStateMonitorImpl.create(getSupplement(), getConversations()); } /** @return the renderer of intrinsic blip state. Subclasses may override. */ protected BlipQueueRenderer createBlipQueueRenderer() { DomAsViewProvider domAsView = stageOne.getDomAsViewProvider(); ReplyManager replyManager = new ReplyManager(getModelAsViewProvider()); // Add all doodads here. DocumentRegistries doodads = installDoodads(DocumentRegistries.builder()) // \u2620 .use(InlineAnchorLiveRenderer.installer(getViewIdMapper(), replyManager, domAsView)) .use(Gadget.install(getProfileManager(), getSupplement(), getSignedInUser())) .build(); LiveConversationViewRenderer live = LiveConversationViewRenderer.create(SchedulerInstance.getLowPriorityTimer(), getConversations(), getModelAsViewProvider(), getBlipDetailer(), replyManager, getThreadReadStateMonitor(), getProfileManager(), getSupplement()); live.init(); BlipPager pager = BlipPager.create( getDocumentRegistry(), doodads, domAsView, getModelAsViewProvider(), getBlipDetailer(), stageOne.getWavePanel().getGwtPanel()); // Collect various components required for paging blips in/out. PagingHandlerProxy pagingHandler = PagingHandlerProxy.create( // \u2620 // Enables and disables the document rendering, as well blip metadata. pager, // Registers and deregisters profile listeners for name changes. live); return BlipQueueRenderer.create(pagingHandler); } protected ViewFactory createViewFactories() { return ViewFactories.FIXED; } protected DomRenderer createRenderer() { return FullDomWaveRendererImpl.create(getConversations(), getProfileManager(), getBlipDetailer(), getViewIdMapper(), getBlipQueue(), getThreadReadStateMonitor(), createViewFactories()); } protected DiffController createDiffController() { return DiffController.create( getConversations(), getSupplement(), getDocumentRegistry(), getModelAsViewProvider()); } /** * Fetches and builds the core wave state. * * @param whenReady command to execute when the wave is built */ protected abstract void fetchWave(final Accessor<WaveViewData> whenReady); /** * Installs parts of stage two that have no dependencies. * <p> * Subclasses may override this to change the set of installed features. */ protected void installStatics() { WavePanelResourceLoader.loadCss(); } protected DocumentRegistries.Builder installDoodads(DocumentRegistries.Builder doodads) { return doodads.use(new DoodadInstallers.GlobalInstaller() { @Override public void install(Registries r) { DiffAnnotationHandler.register(r.getAnnotationHandlerRegistry(), r.getPaintRegistry()); DiffDeleteRenderer.register(r.getElementHandlerRegistry()); StyleAnnotationHandler.register(r); TitleAnnotationHandler.register(r); LinkAnnotationHandler.register(r, new LinkAttributeAugmenter() { @Override public Map<String, String> augment(Map<String, Object> annotations, boolean isEditing, Map<String, String> current) { return current; } }); SelectionAnnotationHandler.register(r, getSessionId(), getProfileManager()); } }); } protected ModelAsViewProvider createModelAsViewProvider() { return new ModelAsViewProviderImpl(getViewIdMapper(), stageOne.getDomAsViewProvider()); } /** * Installs parts of stage two that have dependencies. * <p> * This method is only called once all asynchronously loaded components of * stage two are ready. * <p> * Subclasses may override this to change the set of installed features. */ protected void install() { // Install diff control before rendering, because logical diff state may // need to be adjusted due to arbitrary UI policies. getDiffController().install(); // Install rendering capabilities, then render if necessary. stageOne.getDomAsViewProvider().setRenderer(getRenderer()); ensureRendered(); // Install eager UI features installFeatures(); // Activate liveness. getConnector().connect(null); } /** * Ensures that the wave is rendered. * <p> * Subclasses may override (e.g., to use server-side rendering). */ protected void ensureRendered() { // Default behaviour is to render the whole wave. Element e = getRenderer().render(getConversations()); stageOne.getWavePanel().init(e); } /** * Installs the eager features of this stage. */ protected void installFeatures() { // Eagerly install some features. Reader.install(getSupplement(), stageOne.getFocusFrame(), getModelAsViewProvider(), getDocumentRegistry()); } } }
apache-2.0
raky168/train
javacore/javacore018/src/raky/train/javacore003/TestDataByteStream.java
743
package raky.train.javacore003; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class TestDataByteStream { public static void main(String[] args) { try{ FileOutputStream fos = new FileOutputStream("myfile.data"); DataOutputStream dos = new DataOutputStream(fos); dos.writeUTF("ÂÞ˹¸£"); dos.writeInt(40); dos.close(); FileInputStream fis = new FileInputStream("myfile.data"); DataInputStream dis = new DataInputStream(fis); System.out.println("name:" + dis.readUTF()); System.out.println("age:" + dis.readInt()); fis.close(); }catch(IOException e){ System.out.println(e); } } }
apache-2.0
kieker-monitoring/kieker
kieker-monitoring/test/kieker/test/monitoring/junit/probe/spring/executions/jetty/TestSpringMethodInterceptor.java
6712
/*************************************************************************** * Copyright 2021 Kieker Project (http://kieker-monitoring.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package kieker.test.monitoring.junit.probe.spring.executions.jetty; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.context.support.FileSystemXmlApplicationContext; import kieker.common.record.IMonitoringRecord; import kieker.common.record.controlflow.OperationExecutionRecord; import kieker.monitoring.core.configuration.ConfigurationConstants; import kieker.monitoring.core.controller.IMonitoringController; import kieker.monitoring.core.controller.MonitoringController; import kieker.monitoring.probe.spring.executions.jetty.UrlUtil; import kieker.test.common.junit.AbstractKiekerTest; import kieker.test.monitoring.junit.probe.spring.executions.jetty.bookstore.Bookstore; import kieker.test.monitoring.junit.probe.spring.executions.jetty.bookstore.Catalog; import kieker.test.monitoring.util.NamedListWriter; /** * @author Andre van Hoorn * * @since 1.5 */ @Ignore // https://kieker-monitoring.atlassian.net/browse/KIEKER-1515 public class TestSpringMethodInterceptor extends AbstractKiekerTest { // private static final Log LOG = LogFactory.getLog(TestSpringMethodInterceptor.class); private static final String HOSTNAME = "SRV-W4W7E9pN"; private static final String CTRLNAME = "MonitoringController-TestSpringMethodInterceptor"; private static final URL BOOKSTORE_SEARCH_ANY_URL; private FileSystemXmlApplicationContext ctx; private List<IMonitoringRecord> recordListFilledByListWriter; static { try { BOOKSTORE_SEARCH_ANY_URL = new URL("http://localhost:9293/bookstore/search/any/"); } catch (final MalformedURLException e) { throw new IllegalStateException("Should not happen because the URL is valid.", e); } } public TestSpringMethodInterceptor() { // empty default constructor } @Before public void startServer() throws IOException { final String listName = NamedListWriter.FALLBACK_LIST_NAME; this.recordListFilledByListWriter = NamedListWriter.createNamedList(listName); // We must use System.setProperty (and not a new custom Configuration instance) // because the probe for the spring intercepter uses the singleton instance of the monitoring controller // which reads its properties by configuration file and system properties System.setProperty(ConfigurationConstants.META_DATA, "false"); System.setProperty(ConfigurationConstants.HOST_NAME, HOSTNAME); System.setProperty(ConfigurationConstants.CONTROLLER_NAME, CTRLNAME); System.setProperty(ConfigurationConstants.WRITER_CLASSNAME, NamedListWriter.class.getName()); // Doesn't work because the property does not start with kieker.monitoring: // System.setProperty(NamedListWriter.CONFIG_PROPERTY_NAME_LIST_NAME, listName); // this.monitoringController = MonitoringController.getInstance(); // start the server final URL configURL = TestSpringMethodInterceptor.class .getResource("/kieker/test/monitoring/junit/probe/spring/executions/jetty/jetty.xml"); this.ctx = new FileSystemXmlApplicationContext(configURL.toExternalForm()); // Note that the Spring interceptor is configured in // test/monitoring/kieker/test/monitoring/junit/probe/spring/executions/jetty/webapp/WEB-INF/spring/servlet-context.xml // to only instrument // Bookstore.searchBook and Catalog.getBook } @Test public void testDummy() { // to avoid PMD issues Assert.assertNotNull(BOOKSTORE_SEARCH_ANY_URL); } // @Test // server returns a 503 on access public void ignoretestIt() throws IOException { // Assert.assertNotNull(this.ctx); Assert.assertThat(this.ctx.isRunning(), CoreMatchers.is(true)); final IMonitoringController monitoringController = MonitoringController.getInstance(); Assume.assumeThat(monitoringController.getName(), CoreMatchers.is(CTRLNAME)); for (int i = 0; i < 5; i++) { UrlUtil.ping(BOOKSTORE_SEARCH_ANY_URL); } this.checkRecordList(this.recordListFilledByListWriter); } /** * Performs some basic tests on the received records. * * @param records */ private void checkRecordList(final List<IMonitoringRecord> records) { Assert.assertFalse("No records in List", records.isEmpty()); // Note that the Spring interceptor is configured in // test/monitoring/kieker/test/monitoring/junit/probe/spring/executions/jetty/webapp/WEB-INF/spring/servlet-context.xml // to only instrument // Bookstore.searchBook and Catalog.getBook for (final IMonitoringRecord record : records) { final OperationExecutionRecord opRec = (OperationExecutionRecord) record; Assert.assertEquals("Unexpected hostname", HOSTNAME, opRec.getHostname()); switch (opRec.getEoi()) { case 0: this.assertSignatureIncludesString(opRec.getOperationSignature(), Bookstore.class.getName()); Assert.assertEquals("Unexpected ess", 0, opRec.getEss()); break; case 1: // fall through to case 2 case 2: this.assertSignatureIncludesString(opRec.getOperationSignature(), Catalog.class.getName()); Assert.assertEquals("Unexpected ess", 1, opRec.getEss()); break; default: Assert.fail("Record with unexpected eoi" + opRec); break; } } } private void assertSignatureIncludesString(final String signatureString, final String stringIncluded) { final boolean included = signatureString.contains(stringIncluded); Assert.assertTrue( "Expected string '" + stringIncluded + "' not included in signature '" + signatureString + "'", included); } @After public void cleanup() { this.ctx.destroy(); System.clearProperty(ConfigurationConstants.META_DATA); System.clearProperty(ConfigurationConstants.CONTROLLER_NAME); System.clearProperty(ConfigurationConstants.WRITER_CLASSNAME); System.clearProperty(ConfigurationConstants.HOST_NAME); } }
apache-2.0
Axway/ats-framework
corelibrary/src/main/java/com/axway/ats/core/uiengine/swt/ISwtComboBox.java
2047
/* * Copyright 2017 Axway Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.axway.ats.core.uiengine.swt; import java.rmi.Remote; import java.rmi.RemoteException; public interface ISwtComboBox extends Remote { public void setSelection( String text, String label, String inGroup, int index, int selectionIndex ) throws RemoteException; public void setSelection( String text, String label, String inGroup, int index, String selectionText ) throws RemoteException; public void setText( String text, String label, String inGroup, int index, String textToSet ) throws RemoteException; public String getSelection( String text, String label, String inGroup, int index ) throws RemoteException; public int getSelectionIndex( String text, String label, String inGroup, int index ) throws RemoteException; }
apache-2.0
YoungOG/CarbyneCore
src/com/medievallords/carbyne/crates/commands/CrateKeyCommand.java
3232
package com.medievallords.carbyne.crates.commands; import com.medievallords.carbyne.crates.keys.Key; import com.medievallords.carbyne.utils.Lang; import com.medievallords.carbyne.utils.MessageManager; import com.medievallords.carbyne.utils.PlayerUtility; import com.medievallords.carbyne.utils.StaticClasses; import com.medievallords.carbyne.utils.command.BaseCommand; import com.medievallords.carbyne.utils.command.Command; import com.medievallords.carbyne.utils.command.CommandArgs; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class CrateKeyCommand extends BaseCommand { @Command(name = "crate.key", permission = "utils.commands.crate.key") public void onCommand(CommandArgs command) { CommandSender sender = command.getSender(); String[] args = command.getArgs(); if (args.length < 4) { MessageManager.sendMessage(sender, Lang.TOO_FEW_ARGS_CRATE_KEY.toString()); return; } if (args.length > 4) { MessageManager.sendMessage(sender, Lang.TOO_MANY_ARGS_CRATE_KEY.toString()); return; } if (args[0].equalsIgnoreCase("give")) { String who = args[1]; String name = args[2]; if (!isInteger(args[3])) { MessageManager.sendMessage(sender, Lang.CRATE_KEY_VALID_AMOUNT.toString()); return; } int amount = Integer.valueOf(args[3]); if (StaticClasses.crateManager.getKeys().size() <= 0) { MessageManager.sendMessage(sender, Lang.CRATE_KEYS_NO_KEYS.toString()); return; } Key key = StaticClasses.crateManager.getKey(name); if (key == null) { MessageManager.sendMessage(sender, Lang.CRATE_KEYS_NOT_FOUND.toString().replace("{NAME}", name)); return; } if (who.equalsIgnoreCase("-a")) { for (Player all : PlayerUtility.getOnlinePlayers()) { all.getInventory().addItem(key.getItem(amount)); } MessageManager.sendMessage(sender, Lang.SUCCESS_CRATE_KEY.toString().replace("{NAME}", "everyone").replace("{KEY_NAME}", key.getName()).replace("{AMOUNT}", "" + amount)); } else { Player player = Bukkit.getPlayer(who); if (player == null) { MessageManager.sendMessage(sender, Lang.ERROR_PLAYER_NOT_FOUND.toString().replace("{NAME}", who)); return; } player.getInventory().addItem(key.getItem(amount)); MessageManager.sendMessage(sender, Lang.SUCCESS_CRATE_KEY.toString().replace("{NAME}", player.getName()).replace("{KEY_NAME}", key.getName()).replace("{AMOUNT}", "" + amount)); } } else { MessageManager.sendMessage(sender, Lang.USAGE_CRATE_KEY.toString()); } } public static boolean isInteger(String s) { try { Integer.parseInt(s); } catch(NumberFormatException | NullPointerException e) { return false; } return true; } }
apache-2.0
electrum/presto
plugin/trino-hive/src/main/java/io/trino/plugin/hive/HiveModule.java
8692
/* * 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.trino.plugin.hive; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.multibindings.Multibinder; import io.airlift.event.client.EventClient; import io.trino.plugin.base.CatalogName; import io.trino.plugin.hive.metastore.MetastoreConfig; import io.trino.plugin.hive.metastore.SemiTransactionalHiveMetastore; import io.trino.plugin.hive.orc.OrcFileWriterFactory; import io.trino.plugin.hive.orc.OrcPageSourceFactory; import io.trino.plugin.hive.orc.OrcReaderConfig; import io.trino.plugin.hive.orc.OrcWriterConfig; import io.trino.plugin.hive.parquet.ParquetFileWriterFactory; import io.trino.plugin.hive.parquet.ParquetPageSourceFactory; import io.trino.plugin.hive.parquet.ParquetReaderConfig; import io.trino.plugin.hive.parquet.ParquetWriterConfig; import io.trino.plugin.hive.rcfile.RcFilePageSourceFactory; import io.trino.plugin.hive.s3select.S3SelectRecordCursorProvider; import io.trino.plugin.hive.s3select.TrinoS3ClientFactory; import io.trino.spi.connector.ConnectorNodePartitioningProvider; import io.trino.spi.connector.ConnectorPageSinkProvider; import io.trino.spi.connector.ConnectorPageSourceProvider; import io.trino.spi.connector.ConnectorSplitManager; import io.trino.spi.connector.SystemTable; import io.trino.spi.type.Type; import io.trino.spi.type.TypeId; import io.trino.spi.type.TypeManager; import javax.inject.Inject; import javax.inject.Singleton; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Function; import static com.google.inject.multibindings.Multibinder.newSetBinder; import static com.google.inject.multibindings.OptionalBinder.newOptionalBinder; import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static io.airlift.configuration.ConfigBinder.configBinder; import static io.airlift.json.JsonBinder.jsonBinder; import static io.airlift.json.JsonCodecBinder.jsonCodecBinder; import static java.util.Objects.requireNonNull; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newScheduledThreadPool; import static org.weakref.jmx.guice.ExportBinder.newExporter; public class HiveModule implements Module { @Override public void configure(Binder binder) { binder.bind(DirectoryLister.class).to(CachingDirectoryLister.class).in(Scopes.SINGLETON); configBinder(binder).bindConfig(HiveConfig.class); configBinder(binder).bindConfig(MetastoreConfig.class); binder.bind(HiveSessionProperties.class).in(Scopes.SINGLETON); binder.bind(HiveTableProperties.class).in(Scopes.SINGLETON); binder.bind(HiveAnalyzeProperties.class).in(Scopes.SINGLETON); binder.bind(TrinoS3ClientFactory.class).in(Scopes.SINGLETON); binder.bind(CachingDirectoryLister.class).in(Scopes.SINGLETON); newExporter(binder).export(CachingDirectoryLister.class).withGeneratedName(); binder.bind(HiveWriterStats.class).in(Scopes.SINGLETON); newExporter(binder).export(HiveWriterStats.class).withGeneratedName(); newSetBinder(binder, EventClient.class).addBinding().to(HiveEventClient.class).in(Scopes.SINGLETON); binder.bind(HivePartitionManager.class).in(Scopes.SINGLETON); binder.bind(LocationService.class).to(HiveLocationService.class).in(Scopes.SINGLETON); newOptionalBinder(binder, HiveRedirectionsProvider.class) .setDefault().to(NoneHiveRedirectionsProvider.class).in(Scopes.SINGLETON); newOptionalBinder(binder, HiveMaterializedViewMetadataFactory.class) .setDefault().to(DefaultHiveMaterializedViewMetadataFactory.class).in(Scopes.SINGLETON); newOptionalBinder(binder, TransactionalMetadataFactory.class) .setDefault().to(HiveMetadataFactory.class).in(Scopes.SINGLETON); binder.bind(HiveTransactionManager.class).in(Scopes.SINGLETON); binder.bind(ConnectorSplitManager.class).to(HiveSplitManager.class).in(Scopes.SINGLETON); newExporter(binder).export(ConnectorSplitManager.class).as(generator -> generator.generatedNameOf(HiveSplitManager.class)); binder.bind(ConnectorPageSourceProvider.class).to(HivePageSourceProvider.class).in(Scopes.SINGLETON); binder.bind(ConnectorPageSinkProvider.class).to(HivePageSinkProvider.class).in(Scopes.SINGLETON); binder.bind(ConnectorNodePartitioningProvider.class).to(HiveNodePartitioningProvider.class).in(Scopes.SINGLETON); jsonCodecBinder(binder).bindJsonCodec(PartitionUpdate.class); binder.bind(FileFormatDataSourceStats.class).in(Scopes.SINGLETON); newExporter(binder).export(FileFormatDataSourceStats.class).withGeneratedName(); Multibinder<HivePageSourceFactory> pageSourceFactoryBinder = newSetBinder(binder, HivePageSourceFactory.class); pageSourceFactoryBinder.addBinding().to(OrcPageSourceFactory.class).in(Scopes.SINGLETON); pageSourceFactoryBinder.addBinding().to(ParquetPageSourceFactory.class).in(Scopes.SINGLETON); pageSourceFactoryBinder.addBinding().to(RcFilePageSourceFactory.class).in(Scopes.SINGLETON); Multibinder<HiveRecordCursorProvider> recordCursorProviderBinder = newSetBinder(binder, HiveRecordCursorProvider.class); recordCursorProviderBinder.addBinding().to(S3SelectRecordCursorProvider.class).in(Scopes.SINGLETON); binder.bind(GenericHiveRecordCursorProvider.class).in(Scopes.SINGLETON); Multibinder<HiveFileWriterFactory> fileWriterFactoryBinder = newSetBinder(binder, HiveFileWriterFactory.class); binder.bind(OrcFileWriterFactory.class).in(Scopes.SINGLETON); newExporter(binder).export(OrcFileWriterFactory.class).withGeneratedName(); configBinder(binder).bindConfig(OrcReaderConfig.class); configBinder(binder).bindConfig(OrcWriterConfig.class); fileWriterFactoryBinder.addBinding().to(OrcFileWriterFactory.class).in(Scopes.SINGLETON); fileWriterFactoryBinder.addBinding().to(RcFileFileWriterFactory.class).in(Scopes.SINGLETON); configBinder(binder).bindConfig(ParquetReaderConfig.class); configBinder(binder).bindConfig(ParquetWriterConfig.class); fileWriterFactoryBinder.addBinding().to(ParquetFileWriterFactory.class).in(Scopes.SINGLETON); jsonBinder(binder).addDeserializerBinding(Type.class).to(TypeDeserializer.class); newSetBinder(binder, SystemTable.class); } @Singleton @Provides public ExecutorService createHiveClientExecutor(CatalogName catalogName) { return newCachedThreadPool(daemonThreadsNamed("hive-" + catalogName + "-%s")); } @ForHiveTransactionHeartbeats @Singleton @Provides public ScheduledExecutorService createHiveTransactionHeartbeatExecutor(CatalogName catalogName, HiveConfig hiveConfig) { return newScheduledThreadPool( hiveConfig.getHiveTransactionHeartbeatThreads(), daemonThreadsNamed("hive-heartbeat-" + catalogName + "-%s")); } @Singleton @Provides public Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> createMetastoreGetter(HiveTransactionManager transactionManager) { return transactionHandle -> ((HiveMetadata) transactionManager.get(transactionHandle)).getMetastore(); } public static final class TypeDeserializer extends FromStringDeserializer<Type> { private final TypeManager typeManager; @Inject public TypeDeserializer(TypeManager typeManager) { super(Type.class); this.typeManager = requireNonNull(typeManager, "typeManager is null"); } @Override protected Type _deserialize(String value, DeserializationContext context) { return typeManager.getType(TypeId.of(value)); } } }
apache-2.0
teartao/jarvis
jarvis-web/src/main/java/net/hehe/exceptions/AuthenticationException.java
382
package net.hehe.exceptions; /** * author: taolei * date: 15/11/22. * description:认证失败异常 */ public class AuthenticationException extends RuntimeException { private final String HTTP_STATUS = "401"; public AuthenticationException() { super("Authentication failed"); } public String getErrorCode() { return this.HTTP_STATUS; } }
apache-2.0
kifile/common-utils
download/src/main/java/com/kifile/android/download/DownloadState.java
2783
package com.kifile.android.download; import android.os.Parcel; import android.os.Parcelable; /** * 下载任务状态. * * @author kifile */ public class DownloadState implements Parcelable { /** * 下载状态 */ public static final int STATUS_NOT_EXIST = -1; // 任务不存在 public static final int STATUS_PENDING = 0; // 等待下载 public static final int STATUS_DOWNLOADING = 1; // 下载中 public static final int STATUS_SUCCESS = 2; // 下载成功 public static final int STATUS_FAILED = 3; // 下载失败 public static final int STATUS_CANCELED = 4; // 取消下载 /** * 错误码 */ public static final int ERROR_NORMAL = 0; // 正常. public static final int ERROR_NO_LINK = 1; // 没有下载地址. public static final int ERROR_NO_PATH = 2; // 没有保存路径. public static final int ERROR_CANCEL = 3; // 用户取消. public static final int ERROR_ALREADY_EXIST = 4; // 已经存在任务队列中. public static final int ERROR_OTHER = 4; // 其他错误. /** * 当前状态. * * @see #STATUS_PENDING * @see #STATUS_DOWNLOADING * @see #STATUS_SUCCESS * @see #STATUS_FAILED */ public int status; /** * 任务错误. */ public int error; /** * 下载进度. */ public double percent; /** * Link地址 */ public String link; /** * 下载路径 */ public String path; /** * 开启任务的ServiceId */ public int startId; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(status); dest.writeInt(error); dest.writeDouble(percent); dest.writeString(link); dest.writeString(path); dest.writeInt(startId); } @Override public boolean equals(Object o) { if (o instanceof DownloadState) { DownloadState state = (DownloadState) o; return link != null && link.equals(state.link) && path != null && path.equals(state.path); } return false; } public static final Parcelable.Creator<DownloadState> CREATOR = new Parcelable.Creator<DownloadState>() { public DownloadState createFromParcel(Parcel in) { DownloadState task = new DownloadState(); task.status = in.readInt(); task.error = in.readInt(); task.percent = in.readDouble(); task.link = in.readString(); task.path = in.readString(); return task; } public DownloadState[] newArray(int size) { return new DownloadState[size]; } }; }
apache-2.0
ticofab/The-Things-Network-Android-SDK
ttn-android-sdk/src/main/java/org/ttn/android/sdk/v0/api/converter/MqttPacketConverter.java
4376
package org.ttn.android.sdk.v0.api.converter; import org.joda.time.DateTime; import org.joda.time.format.ISODateTimeFormat; import org.json.JSONException; import org.json.JSONObject; import org.ttn.android.sdk.v0.api.converter.base.JsonConverter; import org.ttn.android.sdk.v0.api.converter.base.JsonErrorMessage; import org.ttn.android.sdk.v0.domain.packet.Packet; /* * Copyright 2016 Fabio Tiriticco / Fabway * * 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. * * Created by fabiotiriticco on 25/09/15. */ @Deprecated public class MqttPacketConverter extends JsonConverter { // example of a packet coming from MQTT /* { "gatewayEui":"1DEE0DF33702B031", "nodeEui":"02011B01", "time":"2016-02-01T08:27:03.13697068Z", "frequency":868.5, "dataRate":"SF7BW125", "rssi":-53, "snr":7, "rawData":"QAEbAQKACgABieNcoUcBwskLvCk80jPLrnxCSM4cDeQUqQJYELy0atRxChPhq9xhu2IV2zwpEp9U1cpZEC6VvelJ54Oh\/nENAuw=", "data":"e3RlbXAwOjIxLjAwLHRlbXAxOjIzLjA2LHRlbXAyOjIzLjAwLHRlbXAzOjIzLjA2LGh1bWkwOjE3LjAwfQ==" } */ public static final String JSON_KEY_SNR = "snr"; public static final String JSON_KEY_TIME = "time"; public static final String JSON_KEY_DATA = "data"; public static final String JSON_KEY_RSSI = "rssi"; public static final String JSON_KEY_NODE_EUI = "nodeEui"; public static final String JSON_KEY_DATA_RAW = "rawData"; public static final String JSON_KEY_DATA_RATE = "dataRate"; public static final String JSON_KEY_FREQUENCY = "frequency"; public static final String JSON_KEY_GATEWAY_EUI = "gatewayEui"; @Override public Object fromJson(JSONObject jsonObj) throws JSONException { Packet.Builder builder = new Packet.Builder(); if (jsonObj.has(JSON_KEY_DATA)) { builder.setData(jsonObj.getString(JSON_KEY_DATA)); } if (jsonObj.has(JSON_KEY_DATA_RAW)) { builder.setDataRaw(JSON_KEY_DATA_RAW); } if (jsonObj.has(JSON_KEY_DATA_RATE)) { builder.setDataRate(jsonObj.getString(JSON_KEY_DATA_RATE)); } if (jsonObj.has(JSON_KEY_FREQUENCY)) { builder.setFrequency(jsonObj.getDouble(JSON_KEY_FREQUENCY)); } if (jsonObj.has(JSON_KEY_RSSI)) { builder.setRSSI(jsonObj.getInt(JSON_KEY_RSSI)); } if (jsonObj.has(JSON_KEY_SNR)) { builder.setSNR(jsonObj.getDouble(JSON_KEY_SNR)); } if (jsonObj.has(JSON_KEY_GATEWAY_EUI)) { builder.setGatewayEui(jsonObj.getString(JSON_KEY_GATEWAY_EUI)); } if (jsonObj.has(JSON_KEY_NODE_EUI)) { builder.setNodeEui(jsonObj.getString(JSON_KEY_NODE_EUI)); } if (jsonObj.has(JSON_KEY_TIME)) { String dateStr = jsonObj.getString(JSON_KEY_TIME); DateTime time = null; try { time = ISODateTimeFormat.dateTime().parseDateTime(dateStr); } catch (IllegalArgumentException e1) { // maybe we need to add a Z at the end? Someone might be sending wrong dates try { time = ISODateTimeFormat.dateTime().parseDateTime(dateStr + "Z"); } catch (IllegalArgumentException e2) { // pity, nothing to do } } if (time != null) { builder.setTime(time); } } return builder.build(); } @Override public JSONObject toJson(Object object) throws JSONException { if (!(object instanceof Packet)) { throw new JSONException(JsonErrorMessage.unexpectedObject(Packet.class, object)); } Packet packet = (Packet) object; final JSONObject jsonObj = new JSONObject(); // TODO return jsonObj; } }
apache-2.0
evenjn/knit
src/main/java/org/github/evenjn/knit/package-info.java
574
/** * <p> * Knit is a collection of tools to fold and unfold data sequences with limited * resources. * </p> * * <p> * The public interface of Knit consists of the following classes and * interfaces: * </p> * * <ul> * <li>{@link org.github.evenjn.knit.KnittingCursable KnittingCursable}</li> * <li>{@link org.github.evenjn.knit.KnittingCursor KnittingCursor}</li> * <li>{@link org.github.evenjn.knit.KnittingTuple KnittingTuple}</li> * <li>{@link org.github.evenjn.knit.Numbered Numbered}</li> * </ul> * * @since 1.0 */ package org.github.evenjn.knit;
apache-2.0
ctblanch/loljwrapper
src/lolwrapper/Rune.java
365
/** * */ package lolwrapper; /** * @author Cameron * */ public class Rune { private String description; private int id; private String name; private int tier; public String getDescription() { return description; } public int getId() { return id; } public String getName() { return name; } public int getTier() { return tier; } }
apache-2.0
yeastrc/msdapl
MSDaPl_Web_App/src/org/yeastrc/www/jobqueue/ResetJobAction.java
3365
/** * */ package org.yeastrc.www.jobqueue; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.yeastrc.jobqueue.Job; import org.yeastrc.jobqueue.JobResetter; import org.yeastrc.jobqueue.MSJob; import org.yeastrc.jobqueue.MSJobFactory; import org.yeastrc.jobqueue.MsAnalysisUploadJob; import org.yeastrc.project.Project; import org.yeastrc.www.user.Groups; import org.yeastrc.www.user.User; import org.yeastrc.www.user.UserUtils; /** * @author Mike * */ public class ResetJobAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception { // User making this request User user = UserUtils.getUser(request); if (user == null) { ActionErrors errors = new ActionErrors(); errors.add("username", new ActionMessage("error.login.notloggedin")); saveErrors( request, errors ); return mapping.findForward("authenticate"); } // Restrict access to yrc members Groups groupMan = Groups.getInstance(); if (!groupMan.isInAGroup(user.getResearcher().getID())) { ActionErrors errors = new ActionErrors(); errors.add("access", new ActionMessage("error.access.invalidgroup")); saveErrors( request, errors ); return mapping.findForward( "Failure" ); } try { Job job = MSJobFactory.getInstance().getJob( Integer.parseInt( request.getParameter( "id" ) ) ); if (job == null) { ActionErrors errors = new ActionErrors(); errors.add("general", new ActionMessage("error.general.errorMessage","No job found with ID "+request.getParameter( "id" ))); saveErrors( request, errors ); return mapping.findForward( "Failure" ); } Project project = null; if(job instanceof MSJob) project = ((MSJob)job).getProject(); else if(job instanceof MsAnalysisUploadJob) project = ((MsAnalysisUploadJob)job).getProject(); if(project == null) { ActionErrors errors = new ActionErrors(); errors.add("general", new ActionMessage("error.general.errorMessage","No project found for job ID "+request.getParameter( "id" ))); saveErrors( request, errors ); return mapping.findForward("Failure"); } if(!project.checkAccess(user.getResearcher())) { ActionErrors errors = new ActionErrors(); errors.add("username", new ActionMessage("error.general.errorMessage", "You may reset upload jobs only for projects to which you are affiliated")); saveErrors( request, errors ); return mapping.findForward( "Failure" ); } JobResetter.getInstance().resetJob( job ); //request.setAttribute( "job", job ); } catch (Exception e) { return mapping.findForward( "Failure" ); } return mapping.findForward( "Success" ); } }
apache-2.0
compomics/compomics-utilities
src/main/java/com/compomics/util/gui/parameters/tools/ProcessingParametersDialog.java
13400
package com.compomics.util.gui.parameters.tools; import com.compomics.util.gui.renderers.AlignedListCellRenderer; import com.compomics.util.parameters.tools.ProcessingParameters; import com.compomics.util.parameters.tools.ProcessingParameters.ProcessingType; import java.awt.Dialog; import javax.swing.DefaultComboBoxModel; import javax.swing.SwingConstants; /** * Dialog to edit the processing parameters. * * @author Marc Vaudel * @author Harald Barsnes */ public class ProcessingParametersDialog extends javax.swing.JDialog { /** * Empty default constructor */ public ProcessingParametersDialog() { } /** * Boolean indicating whether the user canceled the editing. */ private boolean canceled = false; /** * Boolean indicating whether the processing and identification parameters * should be edited upon clicking on OK. */ private boolean editable; /** * Creates a new ProcessingPreferencesDialog with a frame as owner. * * @param parentFrame a parent frame * @param processingPreferences the processing parameters to display * @param editable boolean indicating whether the settings can be edited */ public ProcessingParametersDialog(java.awt.Frame parentFrame, ProcessingParameters processingPreferences, boolean editable) { super(parentFrame, true); initComponents(); this.editable = editable; setUpGui(); populateGUI(processingPreferences); setLocationRelativeTo(parentFrame); setVisible(true); } /** * Creates a new ProcessingPreferencesDialog with a dialog as owner. * * @param owner the dialog owner * @param parentFrame a parent frame * @param processingPreferences the processing parameters to display * @param editable boolean indicating whether the settings can be edited */ public ProcessingParametersDialog(Dialog owner, java.awt.Frame parentFrame, ProcessingParameters processingPreferences, boolean editable) { super(owner, true); initComponents(); this.editable = editable; setUpGui(); populateGUI(processingPreferences); setLocationRelativeTo(owner); setVisible(true); } /** * Set up the GUI. */ private void setUpGui() { processingTypeCmb.setRenderer(new AlignedListCellRenderer(SwingConstants.CENTER)); //processingTypeCmb.setEnabled(editable); nThreadsSpinner.setEnabled(editable); } /** * Fills the GUI with the given settings. * * @param processingPreferences the processing parameters to display */ private void populateGUI(ProcessingParameters processingPreferences) { processingTypeCmb.setSelectedItem(processingPreferences.getProcessingType()); nThreadsSpinner.setModel(new javax.swing.SpinnerNumberModel(processingPreferences.getnThreads(), 1, null, 1)); } /** * Indicates whether the user canceled the editing. * * @return a boolean indicating whether the user canceled the editing */ public boolean isCanceled() { return canceled; } /** * Validates the user input. * * @return a boolean indicating whether the user input is valid */ public boolean validateInput() { return true; } /** * Returns the processing parameters as set by the user. * * @return the processing parameters as set by the user */ public ProcessingParameters getProcessingParameters() { ProcessingParameters processingParameters = new ProcessingParameters(); processingParameters.setProcessingType((ProcessingParameters.ProcessingType) processingTypeCmb.getSelectedItem()); processingParameters.setnThreads((Integer) nThreadsSpinner.getValue()); return processingParameters; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { backgroundPanel = new javax.swing.JPanel(); performancePanel = new javax.swing.JPanel(); performanceLbl = new javax.swing.JLabel(); nThreadsSpinner = new javax.swing.JSpinner(); processingTypePanel = new javax.swing.JPanel(); processingTypeLbl = new javax.swing.JLabel(); processingTypeCmb = new javax.swing.JComboBox(); cancelButton = new javax.swing.JButton(); okButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Processing Preferences"); backgroundPanel.setBackground(new java.awt.Color(230, 230, 230)); performancePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Performance Settings")); performancePanel.setOpaque(false); performanceLbl.setText("Number of Cores"); nThreadsSpinner.setModel(new javax.swing.SpinnerNumberModel(1, 1, null, 1)); nThreadsSpinner.setRequestFocusEnabled(false); javax.swing.GroupLayout performancePanelLayout = new javax.swing.GroupLayout(performancePanel); performancePanel.setLayout(performancePanelLayout); performancePanelLayout.setHorizontalGroup( performancePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(performancePanelLayout.createSequentialGroup() .addContainerGap() .addComponent(performanceLbl) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 67, Short.MAX_VALUE) .addComponent(nThreadsSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); performancePanelLayout.setVerticalGroup( performancePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(performancePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(performancePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(performanceLbl) .addComponent(nThreadsSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); processingTypePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Processing Type")); processingTypePanel.setOpaque(false); processingTypeLbl.setText("Execution"); processingTypeCmb.setModel(new DefaultComboBoxModel(ProcessingType.values())); processingTypeCmb.setEnabled(false); javax.swing.GroupLayout processingTypePanelLayout = new javax.swing.GroupLayout(processingTypePanel); processingTypePanel.setLayout(processingTypePanelLayout); processingTypePanelLayout.setHorizontalGroup( processingTypePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processingTypePanelLayout.createSequentialGroup() .addContainerGap() .addComponent(processingTypeLbl) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(processingTypeCmb, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); processingTypePanelLayout.setVerticalGroup( processingTypePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(processingTypePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(processingTypePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(processingTypeLbl) .addComponent(processingTypeCmb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); okButton.setText("OK"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); javax.swing.GroupLayout backgroundPanelLayout = new javax.swing.GroupLayout(backgroundPanel); backgroundPanel.setLayout(backgroundPanelLayout); backgroundPanelLayout.setHorizontalGroup( backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(backgroundPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(processingTypePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(performancePanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, backgroundPanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cancelButton))) .addContainerGap()) ); backgroundPanelLayout.setVerticalGroup( backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, backgroundPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(processingTypePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(performancePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancelButton) .addComponent(okButton)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(backgroundPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Cancel the dialog. * * @param evt */ private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed canceled = true; dispose(); }//GEN-LAST:event_cancelButtonActionPerformed /** * Cancel the dialog. * * @param evt */ private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed dispose(); }//GEN-LAST:event_okButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel backgroundPanel; private javax.swing.JButton cancelButton; private javax.swing.JSpinner nThreadsSpinner; private javax.swing.JButton okButton; private javax.swing.JLabel performanceLbl; private javax.swing.JPanel performancePanel; private javax.swing.JComboBox processingTypeCmb; private javax.swing.JLabel processingTypeLbl; private javax.swing.JPanel processingTypePanel; // End of variables declaration//GEN-END:variables }
apache-2.0
ramkrish86/incubator-phoenix
phoenix-core/src/main/java/org/apache/phoenix/parse/CeilParseNode.java
3484
/* * Copyright 2014 The Apache Software Foundation * * 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.phoenix.parse; import java.sql.SQLException; import java.util.List; import org.apache.phoenix.compile.StatementContext; import org.apache.phoenix.expression.Expression; import org.apache.phoenix.expression.function.CeilDateExpression; import org.apache.phoenix.expression.function.CeilDecimalExpression; import org.apache.phoenix.expression.function.CeilFunction; import org.apache.phoenix.expression.function.CeilTimestampExpression; import org.apache.phoenix.schema.PDataType; import org.apache.phoenix.schema.TypeMismatchException; /** * Parse node corresponding to {@link CeilFunction}. * It also acts as a factory for creating the right kind of * ceil expression according to the data type of the * first child. * * * @since 3.0.0 */ public class CeilParseNode extends FunctionParseNode { CeilParseNode(String name, List<ParseNode> children, BuiltInFunctionInfo info) { super(name, children, info); } @Override public Expression create(List<Expression> children, StatementContext context) throws SQLException { return getCeilExpression(children); } public static Expression getCeilExpression(List<Expression> children) throws SQLException { final Expression firstChild = children.get(0); final PDataType firstChildDataType = firstChild.getDataType(); if(firstChildDataType.isCoercibleTo(PDataType.DATE)) { return CeilDateExpression.create(children); } else if (firstChildDataType == PDataType.TIMESTAMP || firstChildDataType == PDataType.UNSIGNED_TIMESTAMP) { return CeilTimestampExpression.create(children); } else if(firstChildDataType.isCoercibleTo(PDataType.DECIMAL)) { return new CeilDecimalExpression(children); } else { throw TypeMismatchException.newException(firstChildDataType, "1"); } } /** * When ceiling off decimals, user need not specify the scale. In such cases, * we need to prevent the function from getting evaluated as null. This is really * a hack. A better way would have been if {@link org.apache.phoenix.parse.FunctionParseNode.BuiltInFunctionInfo} provided a * way of associating default values for each permissible data type. * Something like: @ Argument(allowedTypes={PDataType.VARCHAR, PDataType.INTEGER}, defaultValues = {"null", "1"} isConstant=true) * Till then, this will have to do. */ @Override public boolean evalToNullIfParamIsNull(StatementContext context, int index) throws SQLException { return index == 0; } }
apache-2.0
a1vanov/ignite
modules/web-console/web-agent/src/main/java/org/apache/ignite/console/agent/handlers/ClusterListener.java
9551
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.console.agent.handlers; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.socket.client.Socket; import io.socket.emitter.Emitter; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.apache.ignite.console.agent.rest.RestExecutor; import org.apache.ignite.console.agent.rest.RestResult; import org.apache.ignite.internal.processors.rest.client.message.GridClientNodeBean; import org.apache.ignite.internal.processors.rest.protocols.http.jetty.GridJettyObjectMapper; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteClosure; import org.apache.ignite.lang.IgniteProductVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.ignite.console.agent.AgentUtils.toJSON; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_BUILD_VER; import static org.apache.ignite.internal.processors.rest.GridRestResponse.STATUS_SUCCESS; /** * API to retranslate topology from Ignite cluster available by node-uri. */ public class ClusterListener { /** */ private static final Logger log = LoggerFactory.getLogger(ClusterListener.class); /** */ private static final String EVENT_CLUSTER_CONNECTED = "cluster:connected"; /** */ private static final String EVENT_CLUSTER_TOPOLOGY = "cluster:topology"; /** */ private static final String EVENT_CLUSTER_DISCONNECTED = "cluster:disconnected"; /** Default timeout. */ private static final long DFLT_TIMEOUT = 3000L; /** JSON object mapper. */ private static final ObjectMapper mapper = new GridJettyObjectMapper(); /** Latest topology snapshot. */ private TopologySnapshot top; /** */ private final WatchTask watchTask = new WatchTask(); /** */ private final BroadcastTask broadcastTask = new BroadcastTask(); /** */ private static final IgniteClosure<GridClientNodeBean, UUID> NODE2ID = new IgniteClosure<GridClientNodeBean, UUID>() { @Override public UUID apply(GridClientNodeBean n) { return n.getNodeId(); } @Override public String toString() { return "Node bean to node ID transformer closure."; } }; /** */ private static final IgniteClosure<UUID, String> ID2ID8 = new IgniteClosure<UUID, String>() { @Override public String apply(UUID nid) { return U.id8(nid).toUpperCase(); } @Override public String toString() { return "Node ID to ID8 transformer closure."; } }; /** */ private static final ScheduledExecutorService pool = Executors.newScheduledThreadPool(1); /** */ private ScheduledFuture<?> refreshTask; /** */ private Socket client; /** */ private RestExecutor restExecutor; /** * @param client Client. * @param restExecutor Client. */ public ClusterListener(Socket client, RestExecutor restExecutor) { this.client = client; this.restExecutor = restExecutor; } /** * Callback on cluster connect. * * @param nids Cluster nodes IDs. */ private void clusterConnect(Collection<UUID> nids) { log.info("Connection successfully established to cluster with nodes: {}", F.viewReadOnly(nids, ID2ID8)); client.emit(EVENT_CLUSTER_CONNECTED, toJSON(nids)); } /** * Callback on disconnect from cluster. */ private void clusterDisconnect() { if (top == null) return; top = null; log.info("Connection to cluster was lost"); client.emit(EVENT_CLUSTER_DISCONNECTED); } /** * Stop refresh task. */ private void safeStopRefresh() { if (refreshTask != null) refreshTask.cancel(true); } /** * Start watch cluster. */ public void watch() { safeStopRefresh(); refreshTask = pool.scheduleWithFixedDelay(watchTask, 0L, DFLT_TIMEOUT, TimeUnit.MILLISECONDS); } /** * Start broadcast topology to server-side. */ public Emitter.Listener start() { return new Emitter.Listener() { @Override public void call(Object... args) { safeStopRefresh(); final long timeout = args.length > 1 && args[1] instanceof Long ? (long)args[1] : DFLT_TIMEOUT; refreshTask = pool.scheduleWithFixedDelay(broadcastTask, 0L, timeout, TimeUnit.MILLISECONDS); } }; } /** * Stop broadcast topology to server-side. */ public Emitter.Listener stop() { return new Emitter.Listener() { @Override public void call(Object... args) { refreshTask.cancel(true); watch(); } }; } /** */ private class TopologySnapshot { /** */ private Collection<UUID> nids; /** */ private String clusterVersion; /** * @param nodes Nodes. */ TopologySnapshot(Collection<GridClientNodeBean> nodes) { nids = F.viewReadOnly(nodes, NODE2ID); Collection<IgniteProductVersion> vers = F.transform(nodes, new IgniteClosure<GridClientNodeBean, IgniteProductVersion>() { @Override public IgniteProductVersion apply(GridClientNodeBean bean) { return IgniteProductVersion.fromString((String)bean.getAttributes().get(ATTR_BUILD_VER)); } }); clusterVersion = Collections.min(vers).toString(); } /** */ Collection<String> nid8() { return F.viewReadOnly(nids, ID2ID8); } /** */ boolean differentCluster(TopologySnapshot old) { if (old == null || F.isEmpty(old.nids)) return true; return Collections.disjoint(nids, old.nids); } } /** */ private class WatchTask implements Runnable { /** {@inheritDoc} */ @Override public void run() { try { RestResult res = restExecutor.topology(false, false); switch (res.getStatus()) { case STATUS_SUCCESS: List<GridClientNodeBean> nodes = mapper.readValue(res.getData(), new TypeReference<List<GridClientNodeBean>>() {}); TopologySnapshot newTop = new TopologySnapshot(nodes); if (newTop.differentCluster(top)) log.info("Connection successfully established to cluster with nodes: {}", newTop.nid8()); top = newTop; client.emit(EVENT_CLUSTER_TOPOLOGY, toJSON(top)); break; default: log.warn(res.getError()); clusterDisconnect(); } } catch (IOException ignore) { clusterDisconnect(); } } } /** */ private class BroadcastTask implements Runnable { /** {@inheritDoc} */ @Override public void run() { try { RestResult res = restExecutor.topology(false, true); switch (res.getStatus()) { case STATUS_SUCCESS: List<GridClientNodeBean> nodes = mapper.readValue(res.getData(), new TypeReference<List<GridClientNodeBean>>() {}); TopologySnapshot newTop = new TopologySnapshot(nodes); if (top.differentCluster(newTop)) { clusterDisconnect(); log.info("Connection successfully established to cluster with nodes: {}", newTop.nid8()); watch(); } top = newTop; client.emit(EVENT_CLUSTER_TOPOLOGY, res.getData()); break; default: log.warn(res.getError()); clusterDisconnect(); } } catch (IOException ignore) { clusterDisconnect(); watch(); } } } }
apache-2.0
NickAndroid/sinaBlog
2014/src/com/bpok/sina/adapters/PopViewAdapter.java
1413
package com.bpok.sina.adapters; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.bpok.sina.R; import com.bpok.sina.adapters.modle.PopItem; import com.bpok.sina.view.ViewHolderPop; public class PopViewAdapter extends BaseAdapter { // data public ArrayList<PopItem> popItemList; private Context mContext; public PopViewAdapter(ArrayList<PopItem> itemList, Context context) { super(); this.mContext = context; this.popItemList = itemList; } @Override public View getView(int position, View convertView, ViewGroup viewGroup) { ViewHolderPop viewHolder = null; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate( R.layout.pop_view_item, null); viewHolder = new ViewHolderPop(convertView, mContext); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolderPop) convertView.getTag(); } PopItem item = this.popItemList.get(position); viewHolder.tv_title.setText(item.getTitleString()); viewHolder.iv_icon.setImageResource(item.getIconSrc()); return convertView; } @Override public int getCount() { return this.popItemList.size(); } @Override public Object getItem(int index) { return null; } @Override public long getItemId(int position) { return position; } }
apache-2.0
joel-costigliola/assertj-core
src/test/java/org/assertj/core/api/Assertions_assertThat_asList_Test.java
2175
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2020 the original author or authors. */ package org.assertj.core.api; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.catchThrowable; import java.util.List; import org.junit.jupiter.api.Test; /** * Tests for Assert.asList() methods */ class Assertions_assertThat_asList_Test { @Test void should_pass_list_asserts_on_list_objects_with_asList() { Object listAsObject = asList(1, 2, 3); assertThat(listAsObject).asList().isSorted(); } @Test void should_pass_list_asserts_on_list_strings_with_asList() { List<String> listAsObject = asList("a", "b", "c"); assertThat(listAsObject).asList().isSorted() .last().isEqualTo("c"); } @Test void should_fail_list_asserts_on_non_list_objects_even_with_asList() { Object nonList = new Object(); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertThat(nonList).asList().isSorted()) .withMessageContaining(format("an instance of:%n <java.util.List>%nbut was instance of:%n <java.lang.Object>")); } @Test void should_keep_existing_description_set_before_calling_asList() { // GIVEN Object listAsObject = asList(1, 2, 3); // WHEN Throwable error = catchThrowable(() -> assertThat(listAsObject).as("oops").asList().isEmpty()); // THEN assertThat(error).hasMessageContaining("oops"); } }
apache-2.0
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/modifier/CompareFieldCreateModifier.java
19063
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.krad.uif.modifier; import com.google.common.collect.Lists; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.kuali.rice.krad.datadictionary.parse.BeanTag; import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute; import org.kuali.rice.krad.datadictionary.parse.BeanTags; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.UifPropertyPaths; import org.kuali.rice.krad.uif.component.Component; import org.kuali.rice.krad.uif.container.Group; import org.kuali.rice.krad.uif.element.Header; import org.kuali.rice.krad.uif.field.DataField; import org.kuali.rice.krad.uif.field.Field; import org.kuali.rice.krad.uif.field.SpaceField; import org.kuali.rice.krad.uif.layout.GridLayoutManager; import org.kuali.rice.krad.uif.view.ExpressionEvaluator; import org.kuali.rice.krad.uif.util.ComponentFactory; import org.kuali.rice.krad.uif.util.ComponentUtils; import org.kuali.rice.krad.uif.util.ObjectPropertyUtils; import org.kuali.rice.krad.uif.view.View; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Generates <code>Field</code> instances to produce a comparison view among * objects of the same type * * <p> * Modifier is initialized with a List of <code>ComparableInfo</code> instances. * For each comparable info, a copy of the configured group field is made and * adjusted to the binding object path for the comparable. The comparison fields * are ordered based on the configured order property of the comparable. In * addition, a <code>HeaderField<code> can be generated to label each group * of comparison fields. * </p> * * @author Kuali Rice Team (rice.collab@kuali.org) */ @BeanTags({@BeanTag(name = "compareFieldCreate-modifier-bean", parent = "Uif-CompareFieldCreate-Modifier"), @BeanTag(name = "maintenanceCompare-modifier-bean", parent = "Uif-MaintenanceCompare-Modifier")}) public class CompareFieldCreateModifier extends ComponentModifierBase { private static final Logger LOG = Logger.getLogger(CompareFieldCreateModifier.class); private static final long serialVersionUID = -6285531580512330188L; private int defaultOrderSequence; private boolean generateCompareHeaders; private Header headerFieldPrototype; private List<ComparableInfo> comparables; public CompareFieldCreateModifier() { defaultOrderSequence = 1; generateCompareHeaders = true; comparables = new ArrayList<ComparableInfo>(); } /** * Calls <code>ViewHelperService</code> to initialize the header field prototype * * @see org.kuali.rice.krad.uif.modifier.ComponentModifier#performInitialization(org.kuali.rice.krad.uif.view.View, * java.lang.Object, org.kuali.rice.krad.uif.component.Component) */ @Override public void performInitialization(View view, Object model, Component component) { super.performInitialization(view, model, component); if (headerFieldPrototype != null) { view.getViewHelperService().performComponentInitialization(view, model, headerFieldPrototype); } } /** * Generates the comparison fields * * <p> * First the configured List of <code>ComparableInfo</code> instances are * sorted based on their order property. Then if generateCompareHeaders is * set to true, a <code>HeaderField</code> is created for each comparable * using the headerFieldPrototype and the headerText given by the * comparable. Finally for each field configured on the <code>Group</code>, * a corresponding comparison field is generated for each comparable and * adjusted to the binding object path given by the comparable in addition * to suffixing the id and setting the readOnly property * </p> * * @see org.kuali.rice.krad.uif.modifier.ComponentModifier#performModification(org.kuali.rice.krad.uif.view.View, * java.lang.Object, org.kuali.rice.krad.uif.component.Component) */ @SuppressWarnings("unchecked") @Override public void performModification(View view, Object model, Component component) { if ((component != null) && !(component instanceof Group)) { throw new IllegalArgumentException( "Compare field initializer only support Group components, found type: " + component.getClass()); } if (component == null) { return; } Group group = (Group) component; // list to hold the generated compare items List<Component> comparisonItems = new ArrayList<Component>(); // sort comparables by their order property List<ComparableInfo> groupComparables = (List<ComparableInfo>) ComponentUtils.sort(comparables, defaultOrderSequence); // evaluate expressions on comparables Map<String, Object> context = new HashMap<String, Object>(); Map<String, Object> viewContext = view.getContext(); if (viewContext != null) { context.putAll(view.getContext()); } context.put(UifConstants.ContextVariableNames.COMPONENT, component); ExpressionEvaluator expressionEvaluator = view.getViewHelperService().getExpressionEvaluator(); for (ComparableInfo comparable : groupComparables) { expressionEvaluator.evaluateExpressionsOnConfigurable(view, comparable, context); } // generate compare header if (isGenerateCompareHeaders()) { // add space field for label column SpaceField spaceField = ComponentFactory.getSpaceField(); view.assignComponentIds(spaceField); comparisonItems.add(spaceField); for (ComparableInfo comparable : groupComparables) { Header compareHeaderField = ComponentUtils.copy(headerFieldPrototype, comparable.getIdSuffix()); compareHeaderField.setHeaderText(comparable.getHeaderText()); comparisonItems.add(compareHeaderField); } // if group is using grid layout, make first row a header if (group.getLayoutManager() instanceof GridLayoutManager) { ((GridLayoutManager) group.getLayoutManager()).setRenderFirstRowHeader(true); } } // find the comparable to use for comparing value changes (if // configured) boolean performValueChangeComparison = false; String compareValueObjectBindingPath = null; for (ComparableInfo comparable : groupComparables) { if (comparable.isCompareToForValueChange()) { performValueChangeComparison = true; compareValueObjectBindingPath = comparable.getBindingObjectPath(); } } // generate the compare items from the configured group boolean changeIconShowedOnHeader = false; for (Component item : group.getItems()) { int defaultSuffix = 0; boolean suppressLabel = false; for (ComparableInfo comparable : groupComparables) { String idSuffix = comparable.getIdSuffix(); if (StringUtils.isBlank(idSuffix)) { idSuffix = UifConstants.IdSuffixes.COMPARE + defaultSuffix; } Component compareItem = ComponentUtils.copy(item, idSuffix); ComponentUtils.setComponentPropertyDeep(compareItem, UifPropertyPaths.BIND_OBJECT_PATH, comparable.getBindingObjectPath()); if (comparable.isReadOnly()) { compareItem.setReadOnly(true); if (compareItem.getPropertyExpressions().containsKey("readOnly")) { compareItem.getPropertyExpressions().remove("readOnly"); } } // label will be enabled for first comparable only if (suppressLabel && (compareItem instanceof Field)) { ((Field) compareItem).getFieldLabel().setRender(false); } // do value comparison if (performValueChangeComparison && comparable.isHighlightValueChange() && !comparable .isCompareToForValueChange()) { boolean valueChanged = performValueComparison(group, compareItem, model, compareValueObjectBindingPath); // add icon to group header if not done so yet if (valueChanged && !changeIconShowedOnHeader && isGenerateCompareHeaders()) { Group groupToSetHeader = null; if (group.getDisclosure() != null && group.getDisclosure().isRender()) { groupToSetHeader = group; } else if (group.getContext().get(UifConstants.ContextVariableNames.PARENT) != null) { // use the parent group to set the notification if available groupToSetHeader = (Group) group.getContext().get(UifConstants.ContextVariableNames.PARENT); } if (groupToSetHeader.getDisclosure().isRender()) { groupToSetHeader.getDisclosure().setOnDocumentReadyScript( "showChangeIconOnDisclosure('" + groupToSetHeader.getId() + "');"); } else if (groupToSetHeader.getHeader() != null) { groupToSetHeader.getHeader().setOnDocumentReadyScript( "showChangeIconOnHeader('" + groupToSetHeader.getHeader().getId() + "');"); } changeIconShowedOnHeader = true; } } comparisonItems.add(compareItem); defaultSuffix++; suppressLabel = true; } } // update the group's list of components group.setItems(comparisonItems); } /** * For each attribute field in the compare item, retrieves the field value and compares against the value for the * main comparable. If the value is different, adds script to the field on ready event to add the change icon to * the field and the containing group header * * @param group group that contains the item and whose header will be highlighted for changes * @param compareItem the compare item being generated and to pull attribute fields from * @param model object containing the data * @param compareValueObjectBindingPath object path for the comparison item * @return true if the value in the field represented by compareItem is equal to the comparison items value, false * otherwise */ protected boolean performValueComparison(Group group, Component compareItem, Object model, String compareValueObjectBindingPath) { // get any attribute fields for the item so we can compare the values List<DataField> itemFields = ComponentUtils.getComponentsOfTypeDeep(compareItem, DataField.class); boolean valueChanged = false; for (DataField field : itemFields) { String fieldBindingPath = field.getBindingInfo().getBindingPath(); Object fieldValue = ObjectPropertyUtils.getPropertyValue(model, fieldBindingPath); String compareBindingPath = StringUtils.replaceOnce(fieldBindingPath, field.getBindingInfo().getBindingObjectPath(), compareValueObjectBindingPath); Object compareValue = ObjectPropertyUtils.getPropertyValue(model, compareBindingPath); if (!((fieldValue == null) && (compareValue == null))) { // if one is null then value changed if ((fieldValue == null) || (compareValue == null)) { valueChanged = true; } else { // both not null, compare values valueChanged = !fieldValue.equals(compareValue); } } if (valueChanged) { // add script to show change icon String onReadyScript = "showChangeIcon('" + field.getId() + "');"; field.setOnDocumentReadyScript(onReadyScript); } // TODO: add script for value changed? } return valueChanged; } /** * Generates an id suffix for the comparable item * * <p> * If the idSuffix to use if configured on the <code>ComparableInfo</code> * it will be used, else the given integer index will be used with an * underscore * </p> * * @param comparable comparable info to check for id suffix * @param index sequence integer * @return id suffix * @see org.kuali.rice.krad.uif.modifier.ComparableInfo#getIdSuffix() */ protected String getIdSuffix(ComparableInfo comparable, int index) { String idSuffix = comparable.getIdSuffix(); if (StringUtils.isBlank(idSuffix)) { idSuffix = "_" + index; } return idSuffix; } /** * @see org.kuali.rice.krad.uif.modifier.ComponentModifier#getSupportedComponents() */ @Override public Set<Class<? extends Component>> getSupportedComponents() { Set<Class<? extends Component>> components = new HashSet<Class<? extends Component>>(); components.add(Group.class); return components; } /** * @see org.kuali.rice.krad.uif.modifier.ComponentModifierBase#getComponentPrototypes() */ public List<Component> getComponentPrototypes() { List<Component> components = new ArrayList<Component>(); components.add(headerFieldPrototype); return components; } /** * Indicates the starting integer sequence value to use for * <code>ComparableInfo</code> instances that do not have the order property * set * * @return default sequence starting value */ @BeanTagAttribute(name = "defaultOrderSequence") public int getDefaultOrderSequence() { return this.defaultOrderSequence; } /** * Setter for the default sequence starting value * * @param defaultOrderSequence */ public void setDefaultOrderSequence(int defaultOrderSequence) { this.defaultOrderSequence = defaultOrderSequence; } /** * Indicates whether a <code>HeaderField</code> should be created for each * group of comparison fields * * <p> * If set to true, for each group of comparison fields a header field will * be created using the headerFieldPrototype configured on the modifier with * the headerText property of the comparable * </p> * * @return true if the headers should be created, false if no * headers should be created */ @BeanTagAttribute(name = "generateCompareHeaders") public boolean isGenerateCompareHeaders() { return this.generateCompareHeaders; } /** * Setter for the generate comparison headers indicator * * @param generateCompareHeaders */ public void setGenerateCompareHeaders(boolean generateCompareHeaders) { this.generateCompareHeaders = generateCompareHeaders; } /** * Prototype instance to use for creating the <code>HeaderField</code> for * each group of comparison fields (if generateCompareHeaders is true) * * @return header field prototype */ @BeanTagAttribute(name = "headerFieldPrototype", type = BeanTagAttribute.AttributeType.SINGLEBEAN) public Header getHeaderFieldPrototype() { return this.headerFieldPrototype; } /** * Setter for the header field prototype * * @param headerFieldPrototype */ public void setHeaderFieldPrototype(Header headerFieldPrototype) { this.headerFieldPrototype = headerFieldPrototype; } /** * List of <code>ComparableInfo</code> instances the compare fields should * be generated for * * <p> * For each comparable, a copy of the fields configured for the * <code>Group</code> will be created for the comparison view * </p> * * @return comparables to generate fields for */ @BeanTagAttribute(name = "comparables", type = BeanTagAttribute.AttributeType.LISTBEAN) public List<ComparableInfo> getComparables() { return this.comparables; } /** * Setter for the list of comparable info instances * * @param comparables */ public void setComparables(List<ComparableInfo> comparables) { this.comparables = comparables; } /** * @see org.kuali.rice.krad.uif.modifier.ComponentModifierBase#copy() */ @Override protected <T> void copyProperties(T componentModifier) { super.copyProperties(componentModifier); CompareFieldCreateModifier compareFieldCreateModifierCopy = (CompareFieldCreateModifier) componentModifier; compareFieldCreateModifierCopy.setDefaultOrderSequence(this.defaultOrderSequence); compareFieldCreateModifierCopy.setGenerateCompareHeaders(this.generateCompareHeaders); if(comparables != null) { List<ComparableInfo> comparables = Lists.newArrayListWithExpectedSize(getComparables().size()); for (ComparableInfo comparable : this.comparables) { comparables.add((ComparableInfo)comparable.copy()); } compareFieldCreateModifierCopy.setComparables(comparables); } if (this.headerFieldPrototype != null) { compareFieldCreateModifierCopy.setHeaderFieldPrototype((Header)this.headerFieldPrototype.copy()); } } }
apache-2.0
mifos/1.4.x
application/src/main/java/org/mifos/application/accounts/struts/actionforms/AccountApplyPaymentActionForm.java
11933
/* * Copyright (c) 2005-2009 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.application.accounts.struts.actionforms; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import java.util.ResourceBundle; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.struts.Globals; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.mifos.accounts.servicefacade.AccountTypeDto; import org.mifos.application.accounts.util.helpers.AccountConstants; import org.mifos.application.login.util.helpers.LoginConstants; import org.mifos.framework.business.util.helpers.MethodNameConstants; import org.mifos.framework.exceptions.InvalidDateException; import org.mifos.framework.security.util.UserContext; import org.mifos.framework.struts.actionforms.BaseActionForm; import org.mifos.framework.util.helpers.Constants; import org.mifos.framework.util.helpers.DateUtils; import org.mifos.framework.util.helpers.DoubleConversionResult; import org.mifos.framework.util.helpers.FilePaths; public class AccountApplyPaymentActionForm extends BaseActionForm { private String input; private String transactionDateDD; private String transactionDateMM; private String transactionDateYY; private String amount; private String receiptId; private String receiptDateDD; private String receiptDateMM; private String receiptDateYY; private String paymentTypeId; private String globalAccountNum; private String accountId; private String prdOfferingName; private boolean amountCannotBeZero = true; public boolean amountCannotBeZero() { return this.amountCannotBeZero; } public void setAmountCannotBeZero(boolean amountCannotBeZero) { this.amountCannotBeZero = amountCannotBeZero; } public String getPrdOfferingName() { return prdOfferingName; } public void setPrdOfferingName(String prdOfferingName) { this.prdOfferingName = prdOfferingName; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getInput() { return input; } @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { String methodCalled = request.getParameter(MethodNameConstants.METHOD); ActionErrors errors = new ActionErrors(); ResourceBundle resources = ResourceBundle.getBundle(FilePaths.ACCOUNTS_UI_RESOURCE_PROPERTYFILE, getUserLocale(request)); if (methodCalled != null && methodCalled.equals("preview")) { ActionErrors errors2 = validateDate(getTransactionDate(), resources.getString("accounts.date_of_trxn"), request); if (null != errors2 && !errors2.isEmpty()) errors.add(errors2); if (getPaymentTypeId() == null || getPaymentTypeId().equals("")) { errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY, resources.getString("accounts.mode_of_payment"))); } if (getReceiptDate() != null && !getReceiptDate().equals("")) { errors2 = validateDate(getReceiptDate(), resources.getString("accounts.receiptdate"), request); if (null != errors2 && !errors2.isEmpty()) errors.add(errors2); } String accountType = (String) request.getSession().getAttribute(Constants.ACCOUNT_TYPE); if (accountType != null && accountType.equals(AccountTypeDto.LOAN_ACCOUNT.name())) { if (getAmount() == null || getAmount().equals("")) { errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY, resources.getString("accounts.amt"))); } } validateAmount(errors,getUserLocale(request)); } if (!errors.isEmpty()) { request.setAttribute(Globals.ERROR_KEY, errors); request.setAttribute("methodCalled", methodCalled); } return errors; } protected ActionErrors validateDate(String date, String fieldName, HttpServletRequest request) { ActionErrors errors = null; java.sql.Date sqlDate = null; if (date != null && !date.equals("")) { try { sqlDate = DateUtils.getDateAsSentFromBrowser(date); if (DateUtils.whichDirection(sqlDate) > 0) { errors = new ActionErrors(); errors.add(AccountConstants.ERROR_FUTUREDATE, new ActionMessage(AccountConstants.ERROR_FUTUREDATE, fieldName)); } } catch (InvalidDateException ide) { errors = new ActionErrors(); errors.add(AccountConstants.ERROR_INVALIDDATE, new ActionMessage(AccountConstants.ERROR_INVALIDDATE, fieldName)); } } else { errors = new ActionErrors(); errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY, fieldName)); } return errors; } protected Locale getUserLocale(HttpServletRequest request) { Locale locale = null; HttpSession session = request.getSession(); if (session != null) { UserContext userContext = (UserContext) session.getAttribute(LoginConstants.USERCONTEXT); if (null != userContext) { locale = userContext.getCurrentLocale(); } } return locale; } protected void validateAmount(ActionErrors errors, Locale locale) { DoubleConversionResult conversionResult = validateAmount(getAmount(), AccountConstants.ACCOUNT_AMOUNT, errors, locale, FilePaths.ACCOUNTS_UI_RESOURCE_PROPERTYFILE); if (amountCannotBeZero() && conversionResult.getErrors().size() == 0 && !(conversionResult.getDoubleValue() > 0.0)) { addError(errors, AccountConstants.ACCOUNT_AMOUNT, AccountConstants.ERRORS_MUST_BE_GREATER_THAN_ZERO, lookupLocalizedPropertyValue(AccountConstants.ACCOUNT_AMOUNT, locale, FilePaths.ACCOUNTS_UI_RESOURCE_PROPERTYFILE)); } } public void setInput(String input) { this.input = input; } public String getPaymentTypeId() { return paymentTypeId; } public void setPaymentTypeId(String paymentTypeId) { this.paymentTypeId = paymentTypeId; } public String getReceiptDate() { if (StringUtils.isNotBlank(receiptDateDD) && StringUtils.isNotBlank(receiptDateMM) && StringUtils.isNotBlank(receiptDateYY)) { return receiptDateDD + "/" + receiptDateMM + "/" + receiptDateYY; } return null; } public void setReceiptDate(String receiptDate) throws InvalidDateException { if (StringUtils.isBlank(receiptDate)) { receiptDateDD = null; receiptDateMM = null; receiptDateYY = null; } else { Calendar cal = new GregorianCalendar(); java.sql.Date date = DateUtils.getDateAsSentFromBrowser(receiptDate); cal.setTime(date); receiptDateDD = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)); receiptDateMM = Integer.toString(cal.get(Calendar.MONTH) + 1); receiptDateYY = Integer.toString(cal.get(Calendar.YEAR)); } } public String getReceiptId() { return receiptId; } public void setReceiptId(String receiptId) { this.receiptId = receiptId; } public String getTransactionDate() { if (StringUtils.isNotBlank(transactionDateDD) && StringUtils.isNotBlank(transactionDateMM) && StringUtils.isNotBlank(transactionDateYY)) { String transactionDate = ""; if (transactionDateDD.length() < 2) transactionDate = transactionDate + "0" + transactionDateDD; else transactionDate = transactionDate + transactionDateDD; if (transactionDateMM.length() < 2) transactionDate = transactionDate + "/" + "0" + transactionDateMM; else transactionDate = transactionDate + "/" + transactionDateMM; transactionDate = transactionDate + "/" + transactionDateYY; return transactionDate; } return null; } public void setTransactionDate(String receiptDate) throws InvalidDateException { if (StringUtils.isBlank(receiptDate)) { transactionDateDD = null; transactionDateMM = null; transactionDateYY = null; } else { Calendar cal = new GregorianCalendar(); java.sql.Date date = DateUtils.getDateAsSentFromBrowser(receiptDate); cal.setTime(date); transactionDateDD = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)); transactionDateMM = Integer.toString(cal.get(Calendar.MONTH) + 1); transactionDateYY = Integer.toString(cal.get(Calendar.YEAR)); } } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getGlobalAccountNum() { return globalAccountNum; } public void setGlobalAccountNum(String globalAccountNum) { this.globalAccountNum = globalAccountNum; } protected void clear() throws InvalidDateException { this.amount = null; this.paymentTypeId = null; setReceiptDate(null); this.receiptId = null; } public String getReceiptDateDD() { return receiptDateDD; } public void setReceiptDateDD(String receiptDateDD) { this.receiptDateDD = receiptDateDD; } public String getReceiptDateMM() { return receiptDateMM; } public void setReceiptDateMM(String receiptDateMM) { this.receiptDateMM = receiptDateMM; } public String getReceiptDateYY() { return receiptDateYY; } public void setReceiptDateYY(String receiptDateYY) { this.receiptDateYY = receiptDateYY; } public String getTransactionDateDD() { return transactionDateDD; } public void setTransactionDateDD(String transactionDateDD) { this.transactionDateDD = transactionDateDD; } public String getTransactionDateMM() { return transactionDateMM; } public void setTransactionDateMM(String transactionDateMM) { this.transactionDateMM = transactionDateMM; } public String getTransactionDateYY() { return transactionDateYY; } public void setTransactionDateYY(String transactionDateYY) { this.transactionDateYY = transactionDateYY; } }
apache-2.0
ceryle/FitGridView
library/src/main/java/co/ceryle/fitgridview/FitGridView.java
4604
/* * Copyright (C) 2016 ceryle * * 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 co.ceryle.fitgridview; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.widget.GridView; public class FitGridView extends GridView { public FitGridView(Context context) { super(context); init(null); } public FitGridView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public FitGridView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public FitGridView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs); } private int column, row; private void init(AttributeSet attrs) { getAttributes(attrs); setStretchMode(GridView.STRETCH_COLUMN_WIDTH); setNumColumns(column); } private void getAttributes(AttributeSet attrs) { if (null == attrs) return; TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.FitGridView); column = typedArray.getInt(R.styleable.FitGridView_column, 0); row = typedArray.getInt(R.styleable.FitGridView_row, 0); typedArray.recycle(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); remeasure(w, h); updateAdapter(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); remeasure(width, height); setMeasuredDimension(width, height); } /** * use it to update view if you have changed width/height, grid size or adapter. */ private void updateAdapter() { if (null == fitGridAdapter) return; fitGridAdapter.setNumRows(row); fitGridAdapter.setNumColumns(column); fitGridAdapter.setColumnHeight(itemHeight); fitGridAdapter.setColumnWidth(itemWidth); setAdapter(fitGridAdapter); } public void update() { remeasure(getMeasuredWidth(), getMeasuredHeight()); updateAdapter(); } /** * @param displayWidth sets max available width for grid view * @param displayHeight sets max available height for grid view */ public void setDimension(float displayWidth, float displayHeight) { itemWidth = (int) displayWidth / column; itemHeight = (int) displayHeight / row; updateAdapter(); } private int itemWidth = 0, itemHeight = 0; private void remeasure(int width, int height) { itemWidth = width / (column == 0 ? 1 : column); itemHeight = height / (row == 0 ? 1 : row); } /** * @return Number of columns associated with the view */ @Override public int getNumColumns() { return column; } /** * @return Number of rows associated with the view */ public int getNumRows() { return row; } /** * @param column sets the desired number of columns in the grid */ public void setNumColumns(int column) { this.column = column; super.setNumColumns(column); } /** * @param row sets the desired number of row in the grid */ public void setNumRows(int row) { this.row = row; } private FitGridAdapter fitGridAdapter; /** * @param fitGridAdapter sets your adapter later in updateAdapter method. */ public void setFitGridAdapter(FitGridAdapter fitGridAdapter) { this.fitGridAdapter = fitGridAdapter; } }
apache-2.0
openegovplatform/OEPv2
oep-core-ssomgt-portlet/docroot/WEB-INF/src/org/oep/core/ssomgt/service/impl/UserSyncLocalServiceImpl.java
1623
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.oep.core.ssomgt.service.impl; import org.oep.core.ssomgt.service.base.UserSyncLocalServiceBaseImpl; /** * The implementation of the user sync local service. * * <p> * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.oep.core.ssomgt.service.UserSyncLocalService} interface. * * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM. * </p> * * @author trungdk * @see org.oep.core.ssomgt.service.base.UserSyncLocalServiceBaseImpl * @see org.oep.core.ssomgt.service.UserSyncLocalServiceUtil */ public class UserSyncLocalServiceImpl extends UserSyncLocalServiceBaseImpl { /* * NOTE FOR DEVELOPERS: * * Never reference this interface directly. Always use {@link org.oep.core.ssomgt.service.UserSyncLocalServiceUtil} to access the user sync local service. */ }
apache-2.0
KonkerLabs/konker-platform
konker.registry.idm.resourceserver/src/main/java/com/konkerlabs/platform/registry/idm/services/MongoTokenStore.java
10983
package com.konkerlabs.platform.registry.idm.services; import com.konkerlabs.platform.registry.business.model.AccessToken; import com.konkerlabs.platform.registry.business.model.RefreshToken; import com.konkerlabs.platform.registry.business.repositories.AccessTokenRepository; import com.konkerlabs.platform.registry.business.repositories.OauthClientDetailRepository; import com.konkerlabs.platform.registry.business.repositories.RefreshTokenRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2RefreshToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator; import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; @Component public class MongoTokenStore implements TokenStore, InitializingBean { private static final Logger LOG = LoggerFactory.getLogger(MongoTokenStore.class); @Autowired private AccessTokenRepository tokenRepository; @Autowired private RefreshTokenRepository refreshTokenRepository; @Autowired private OauthClientDetailRepository oauthClientDetailRepository; private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator(); private ExtractTokenKeyDigester extractTokenKeyDigester = new MD5ExtractTokenKeyDigester(); private static final int MIN_DELAY_TIME = 100; private static final int MAX_DELAY_TIME = 250; public MongoTokenStore() { } @Override public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { final String authenticationId = authenticationKeyGenerator.extractKey(authentication); OAuth2AccessToken accessToken = null; try { AccessToken token = tokenRepository.findAccessTokenByAuthenticationId(authenticationId); accessToken = token != null ? token.token() : null; } catch (IllegalArgumentException e) { LOG.error("Could not extract access token for authentication {}", authentication); } if (accessToken != null && !authenticationId.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) { removeAccessToken(accessToken.getValue()); storeAccessToken(accessToken, authentication); } return accessToken; } @Override public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { LOG.debug("Call storeAccessToken, token = {}, authentication = {}", token, authentication); String refreshToken = token.getRefreshToken() != null ? token.getRefreshToken().getValue() : null; AccessToken accessToken = tokenRepository.findOne(extractTokenKey(token.getValue())); if (accessToken != null) { accessToken.token(token); accessToken.setAuthenticationId(authenticationKeyGenerator.extractKey(authentication)); accessToken.authentication(authentication); accessToken.setRefreshToken(extractTokenKey(refreshToken)); } else { accessToken = AccessToken.builder() .tokenId(extractTokenKey(token.getValue())) .authenticationId(authenticationKeyGenerator.extractKey(authentication)) .username(authentication.isClientOnly() ? null : authentication.getName()) .clientId(authentication.getOAuth2Request().getClientId()) .refreshToken(extractTokenKey(refreshToken)) .build(); accessToken.token(token); accessToken.authentication(authentication); } tokenRepository.save(accessToken); Random random = new Random(); int delayTime = random.nextInt(MAX_DELAY_TIME - MIN_DELAY_TIME) + MIN_DELAY_TIME; try { Thread.sleep(delayTime); } catch (InterruptedException e) { LOG.error("Error on login silence timer..."); } } @Override public OAuth2AccessToken readAccessToken(String tokenValue) { LOG.trace("Call readAccessToken, tokenValue = {}", tokenValue); OAuth2AccessToken token = null; try { final String tokenId = extractTokenKey(tokenValue); final AccessToken accessToken = tokenRepository.findOne(tokenId); token = accessToken == null ? null : accessToken.token(); } catch (IllegalArgumentException e) { LOG.warn("Failed to deserialize access token for {}", tokenValue); removeAccessToken(tokenValue); } return token; } @Override public void removeAccessToken(OAuth2AccessToken token) { removeAccessToken(token.getValue()); } @Override public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { return readAuthentication(token.getValue()); } @Override public OAuth2Authentication readAuthentication(String token) { LOG.trace("Call readAuthentication, token = {}", token); OAuth2Authentication authentication = null; try { final String tokenId = extractTokenKey(token); AccessToken accessToken = tokenRepository.findOne(tokenId); authentication = accessToken == null ? null : accessToken.authentication(); } catch (IllegalArgumentException e) { LOG.warn("Failed to deserialize authentication for {}", token); removeAccessToken(token); } return authentication; } protected void removeAccessToken(String tokenValue) { final String tokenId = extractTokenKey(tokenValue); tokenRepository.delete(tokenId); } @Override public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { LOG.debug("Call storeRefreshToken, refreshToken = {}, authentication = {}", refreshToken, authentication); RefreshToken token = new RefreshToken() .tokenId(extractTokenKey(refreshToken.getValue())) .token(refreshToken) .authentication(authentication); refreshTokenRepository.save(token); } @Override public OAuth2RefreshToken readRefreshToken(String tokenValue) { LOG.debug("Call readRefreshToken, tokenValue = {}", tokenValue); OAuth2RefreshToken refreshToken = null; try { final String tokenId = extractTokenKey(tokenValue); RefreshToken refreshTokenFounded = refreshTokenRepository.findOne(tokenId); refreshToken = refreshTokenFounded == null ? null : refreshTokenFounded.token(); } catch (IllegalArgumentException e) { LOG.warn("Failed to deserialize refresh token for token {}", tokenValue); removeRefreshToken(tokenValue); } return refreshToken; } @Override public void removeRefreshToken(OAuth2RefreshToken token) { removeRefreshToken(token.getValue()); } protected void removeRefreshToken(String token) { final String tokenId = extractTokenKey(token); refreshTokenRepository.delete(tokenId); } @Override public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) { return readAuthenticationForRefreshToken(token.getValue()); } protected OAuth2Authentication readAuthenticationForRefreshToken(String tokenValue) { OAuth2Authentication authentication = null; try { final String tokenId = extractTokenKey(tokenValue); RefreshToken refreshToken = refreshTokenRepository.findOne(tokenId); authentication = refreshToken == null ? null : refreshToken.authentication(); } catch (IllegalArgumentException e) { LOG.warn("Failed to deserialize access token for {}", tokenValue); removeRefreshToken(tokenValue); } return authentication; } @Override public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) { removeAccessTokenUsingRefreshToken(refreshToken.getValue()); } protected void removeAccessTokenUsingRefreshToken(String refreshTokenValue) { final String refreshToken = extractTokenKey(refreshTokenValue); tokenRepository.removeAccessTokenByRefreshToken(refreshToken); } @Override public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) { LOG.debug("Call findTokensByClientId, clientId = {}", clientId); List<OAuth2AccessToken> accessTokens = new ArrayList<>(); List<AccessToken> tokenList = tokenRepository.findAccessTokensByClientId(clientId); for (AccessToken token : tokenList) { final OAuth2AccessToken accessToken = token.token(); if (accessToken != null) { accessTokens.add(accessToken); } } return accessTokens; } @Override public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) { LOG.debug("Call findTokensByUserName, clientId = {}, username = {}", clientId, userName); List<OAuth2AccessToken> accessTokens = new ArrayList<>(); List<AccessToken> tokenList = tokenRepository.findAccessTokensByClientIdAndUsername(clientId, userName); for (AccessToken token : tokenList) { final OAuth2AccessToken accessToken = token.token(); if (accessToken != null) { accessTokens.add(accessToken); } } return accessTokens; } protected String extractTokenKey(String value) { return this.extractTokenKeyDigester.digest(value); } public void setTokenRepository(AccessTokenRepository tokenRepository) { this.tokenRepository = tokenRepository; } public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) { this.authenticationKeyGenerator = authenticationKeyGenerator; } public void setExtractTokenKeyDigester(ExtractTokenKeyDigester extractTokenKeyDigester) { this.extractTokenKeyDigester = extractTokenKeyDigester; } @Override public void afterPropertiesSet() throws Exception { Assert.notNull(tokenRepository); Assert.notNull(authenticationKeyGenerator); } }
apache-2.0
sam0411/SpringBoot
src/main/java/com/fil/ap/swagger/SwaggerController.java
1753
package com.fil.ap.swagger; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.fil.ap.rabbitmq.pojo.User; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponse; @Api(value = "/ee/memberaccountscheme", description = "gets some data from a servlet", consumes="application/json") @RestController @RequestMapping(value = "/ee/memberaccountscheme") public class SwaggerController { @ApiOperation(value = "Get notification history", response = User.class) @ApiResponses(value = { @ApiResponse(code = 600, message = "Invalid ID supplied"), @ApiResponse(code = 604, message = "Pet not found") }) @ApiImplicitParams({ @ApiImplicitParam(name = "APP_ID", value = "app id", required = true, dataType = "string", paramType = "header"), @ApiImplicitParam(name = "HKID_PP_NO", value = "hkid", required = false, dataType = "string", paramType = "query") }) @RequestMapping(value = "/notificationhistory", method = RequestMethod.GET) @ResponseBody public User getUser( @RequestHeader(required = false, value = "APP_ID") String appId, @RequestParam(required = true, value = "HKID_PP_NO") String hkid ) { return null; } }
apache-2.0
SHAF-WORK/shaf
core/src/test/java/org/shaf/core/_helper_/CrashDistributedProcess.java
2007
/** * Copyright 2014-2015 SHAF-WORK * * 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.shaf.core._helper_; import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.shaf.core.anno.JobInput; import org.shaf.core.anno.JobOutput; import org.shaf.core.anno.Tag; import org.shaf.core.process.type.dist.DistributedContext; /** * A dummy {@link CrashDistributedProcess}. * * @author Mykola Galushka */ @JobInput(formatClass = TextInputFormat.class) @JobOutput(formatClass = TextOutputFormat.class, keyClass = LongWritable.class, valueClass = Text.class) @Tag(cmd = "dis", descr = "dummy distributed process") public class CrashDistributedProcess extends DummyDistributedProcess { /** * Performs mapping. */ @Override public void map(LongWritable key, Text value, DistributedContext<LongWritable, Text, LongWritable, Text> context) throws IOException, InterruptedException { super.map(key, value, context); throw new IOException("The mapper is failed."); } /** * Performs reducing. */ @Override public void reduce(LongWritable key, Iterable<Text> values, DistributedContext<LongWritable, Text, LongWritable, Text> context) throws IOException, InterruptedException { super.reduce(key, values, context); throw new IOException("The reducer is failed."); } }
apache-2.0
skubit/skubit-comics
app/src/main/java/com/skubit/comics/provider/collection/CollectionSelection.java
7505
package com.skubit.comics.provider.collection; import java.util.Date; import android.content.Context; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import com.skubit.comics.provider.base.AbstractSelection; /** * Selection for the {@code collection} table. */ public class CollectionSelection extends AbstractSelection<CollectionSelection> { @Override protected Uri baseUri() { return CollectionColumns.CONTENT_URI; } /** * Query the given content resolver using this selection. * * @param contentResolver The content resolver to query. * @param projection A list of which columns to return. Passing null will return all columns, which is inefficient. * @param sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort * order, which may be unordered. * @return A {@code CollectionCursor} object, which is positioned before the first entry, or null. */ public CollectionCursor query(ContentResolver contentResolver, String[] projection, String sortOrder) { Cursor cursor = contentResolver.query(uri(), projection, sel(), args(), sortOrder); if (cursor == null) return null; return new CollectionCursor(cursor); } /** * Equivalent of calling {@code query(contentResolver, projection, null)}. */ public CollectionCursor query(ContentResolver contentResolver, String[] projection) { return query(contentResolver, projection, null); } /** * Equivalent of calling {@code query(contentResolver, projection, null, null)}. */ public CollectionCursor query(ContentResolver contentResolver) { return query(contentResolver, null, null); } /** * Query the given content resolver using this selection. * * @param context The context to use for the query. * @param projection A list of which columns to return. Passing null will return all columns, which is inefficient. * @param sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort * order, which may be unordered. * @return A {@code CollectionCursor} object, which is positioned before the first entry, or null. */ public CollectionCursor query(Context context, String[] projection, String sortOrder) { Cursor cursor = context.getContentResolver().query(uri(), projection, sel(), args(), sortOrder); if (cursor == null) return null; return new CollectionCursor(cursor); } /** * Equivalent of calling {@code query(context, projection, null)}. */ public CollectionCursor query(Context context, String[] projection) { return query(context, projection, null); } /** * Equivalent of calling {@code query(context, projection, null, null)}. */ public CollectionCursor query(Context context) { return query(context, null, null); } public CollectionSelection id(long... value) { addEquals("collection." + CollectionColumns._ID, toObjectArray(value)); return this; } public CollectionSelection cid(String... value) { addEquals(CollectionColumns.CID, value); return this; } public CollectionSelection cidNot(String... value) { addNotEquals(CollectionColumns.CID, value); return this; } public CollectionSelection cidLike(String... value) { addLike(CollectionColumns.CID, value); return this; } public CollectionSelection cidContains(String... value) { addContains(CollectionColumns.CID, value); return this; } public CollectionSelection cidStartsWith(String... value) { addStartsWith(CollectionColumns.CID, value); return this; } public CollectionSelection cidEndsWith(String... value) { addEndsWith(CollectionColumns.CID, value); return this; } public CollectionSelection name(String... value) { addEquals(CollectionColumns.NAME, value); return this; } public CollectionSelection nameNot(String... value) { addNotEquals(CollectionColumns.NAME, value); return this; } public CollectionSelection nameLike(String... value) { addLike(CollectionColumns.NAME, value); return this; } public CollectionSelection nameContains(String... value) { addContains(CollectionColumns.NAME, value); return this; } public CollectionSelection nameStartsWith(String... value) { addStartsWith(CollectionColumns.NAME, value); return this; } public CollectionSelection nameEndsWith(String... value) { addEndsWith(CollectionColumns.NAME, value); return this; } public CollectionSelection tags(String... value) { addEquals(CollectionColumns.TAGS, value); return this; } public CollectionSelection tagsNot(String... value) { addNotEquals(CollectionColumns.TAGS, value); return this; } public CollectionSelection tagsLike(String... value) { addLike(CollectionColumns.TAGS, value); return this; } public CollectionSelection tagsContains(String... value) { addContains(CollectionColumns.TAGS, value); return this; } public CollectionSelection tagsStartsWith(String... value) { addStartsWith(CollectionColumns.TAGS, value); return this; } public CollectionSelection tagsEndsWith(String... value) { addEndsWith(CollectionColumns.TAGS, value); return this; } public CollectionSelection coverart(String... value) { addEquals(CollectionColumns.COVERART, value); return this; } public CollectionSelection coverartNot(String... value) { addNotEquals(CollectionColumns.COVERART, value); return this; } public CollectionSelection coverartLike(String... value) { addLike(CollectionColumns.COVERART, value); return this; } public CollectionSelection coverartContains(String... value) { addContains(CollectionColumns.COVERART, value); return this; } public CollectionSelection coverartStartsWith(String... value) { addStartsWith(CollectionColumns.COVERART, value); return this; } public CollectionSelection coverartEndsWith(String... value) { addEndsWith(CollectionColumns.COVERART, value); return this; } public CollectionSelection type(String... value) { addEquals(CollectionColumns.TYPE, value); return this; } public CollectionSelection typeNot(String... value) { addNotEquals(CollectionColumns.TYPE, value); return this; } public CollectionSelection typeLike(String... value) { addLike(CollectionColumns.TYPE, value); return this; } public CollectionSelection typeContains(String... value) { addContains(CollectionColumns.TYPE, value); return this; } public CollectionSelection typeStartsWith(String... value) { addStartsWith(CollectionColumns.TYPE, value); return this; } public CollectionSelection typeEndsWith(String... value) { addEndsWith(CollectionColumns.TYPE, value); return this; } }
apache-2.0
cwurm/elasticsearch
modules/lang-mustache/src/test/java/org/elasticsearch/script/mustache/MustacheScriptEngineTests.java
6735
/* * 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.script.mustache; import com.github.mustachejava.MustacheFactory; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.script.CompiledScript; import org.elasticsearch.script.ScriptService; import org.elasticsearch.test.ESTestCase; import org.junit.Before; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.Charset; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.equalTo; /** * Mustache based templating test */ public class MustacheScriptEngineTests extends ESTestCase { private MustacheScriptEngineService qe; private MustacheFactory factory; @Before public void setup() { qe = new MustacheScriptEngineService(Settings.Builder.EMPTY_SETTINGS); factory = new CustomMustacheFactory(true); } public void testSimpleParameterReplace() { Map<String, String> compileParams = Collections.singletonMap("content_type", "application/json"); { String template = "GET _search {\"query\": " + "{\"boosting\": {" + "\"positive\": {\"match\": {\"body\": \"gift\"}}," + "\"negative\": {\"term\": {\"body\": {\"value\": \"solr\"}" + "}}, \"negative_boost\": {{boost_val}} } }}"; Map<String, Object> vars = new HashMap<>(); vars.put("boost_val", "0.3"); BytesReference o = (BytesReference) qe.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "", "mustache", qe.compile(null, template, compileParams)), vars).run(); assertEquals("GET _search {\"query\": {\"boosting\": {\"positive\": {\"match\": {\"body\": \"gift\"}}," + "\"negative\": {\"term\": {\"body\": {\"value\": \"solr\"}}}, \"negative_boost\": 0.3 } }}", new String(o.toBytes(), Charset.forName("UTF-8"))); } { String template = "GET _search {\"query\": " + "{\"boosting\": {" + "\"positive\": {\"match\": {\"body\": \"gift\"}}," + "\"negative\": {\"term\": {\"body\": {\"value\": \"{{body_val}}\"}" + "}}, \"negative_boost\": {{boost_val}} } }}"; Map<String, Object> vars = new HashMap<>(); vars.put("boost_val", "0.3"); vars.put("body_val", "\"quick brown\""); BytesReference o = (BytesReference) qe.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "", "mustache", qe.compile(null, template, compileParams)), vars).run(); assertEquals("GET _search {\"query\": {\"boosting\": {\"positive\": {\"match\": {\"body\": \"gift\"}}," + "\"negative\": {\"term\": {\"body\": {\"value\": \"\\\"quick brown\\\"\"}}}, \"negative_boost\": 0.3 } }}", new String(o.toBytes(), Charset.forName("UTF-8"))); } } public void testEscapeJson() throws IOException { { StringWriter writer = new StringWriter(); factory.encode("hello \n world", writer); assertThat(writer.toString(), equalTo("hello \\n world")); } { StringWriter writer = new StringWriter(); factory.encode("\n", writer); assertThat(writer.toString(), equalTo("\\n")); } Character[] specialChars = new Character[]{ '\"', '\\', '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000B', '\u000C', '\u000E', '\u000F', '\u001F'}; String[] escapedChars = new String[]{ "\\\"", "\\\\", "\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", "\\u0008", "\\u0009", "\\u000B", "\\u000C", "\\u000E", "\\u000F", "\\u001F"}; int iters = scaledRandomIntBetween(100, 1000); for (int i = 0; i < iters; i++) { int rounds = scaledRandomIntBetween(1, 20); StringWriter expect = new StringWriter(); StringWriter writer = new StringWriter(); for (int j = 0; j < rounds; j++) { String s = getChars(); writer.write(s); expect.write(s); int charIndex = randomInt(7); writer.append(specialChars[charIndex]); expect.append(escapedChars[charIndex]); } StringWriter target = new StringWriter(); factory.encode(writer.toString(), target); assertThat(expect.toString(), equalTo(target.toString())); } } private String getChars() { String string = randomRealisticUnicodeOfCodepointLengthBetween(0, 10); for (int i = 0; i < string.length(); i++) { if (isEscapeChar(string.charAt(i))) { return string.substring(0, i); } } return string; } /** * From https://www.ietf.org/rfc/rfc4627.txt: * * All Unicode characters may be placed within the * quotation marks except for the characters that must be escaped: * quotation mark, reverse solidus, and the control characters (U+0000 * through U+001F). * */ private static boolean isEscapeChar(char c) { switch (c) { case '"': case '\\': return true; } if (c < '\u002F') return true; return false; } }
apache-2.0
ostap0207/remotify.me
remotify.android/Remotify/src/main/java/com/google/zxing/client/android/LocaleManager.java
7131
/* * Copyright (C) 2008 ZXing 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.zxing.client.android; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * Handles any locale-specific logic for the client. * * @author Sean Owen */ public final class LocaleManager { private static final String DEFAULT_TLD = "com"; private static final String DEFAULT_COUNTRY = "US"; private static final String DEFAULT_LANGUAGE = "en"; /** * Locales (well, countries) where Google web search is available. * These should be kept in sync with our translations. */ private static final Map<String,String> GOOGLE_COUNTRY_TLD; static { GOOGLE_COUNTRY_TLD = new HashMap<String,String>(); GOOGLE_COUNTRY_TLD.put("AR", "com.ar"); // ARGENTINA GOOGLE_COUNTRY_TLD.put("AU", "com.au"); // AUSTRALIA GOOGLE_COUNTRY_TLD.put("BR", "com.br"); // BRAZIL GOOGLE_COUNTRY_TLD.put("BG", "bg"); // BULGARIA GOOGLE_COUNTRY_TLD.put(Locale.CANADA.getCountry(), "ca"); GOOGLE_COUNTRY_TLD.put(Locale.CHINA.getCountry(), "cn"); GOOGLE_COUNTRY_TLD.put("CZ", "cz"); // CZECH REPUBLIC GOOGLE_COUNTRY_TLD.put("DK", "dk"); // DENMARK GOOGLE_COUNTRY_TLD.put("FI", "fi"); // FINLAND GOOGLE_COUNTRY_TLD.put(Locale.FRANCE.getCountry(), "fr"); GOOGLE_COUNTRY_TLD.put(Locale.GERMANY.getCountry(), "de"); GOOGLE_COUNTRY_TLD.put("GR", "gr"); // GREECE GOOGLE_COUNTRY_TLD.put("HU", "hu"); // HUNGARY GOOGLE_COUNTRY_TLD.put("ID", "co.id"); // INDONESIA GOOGLE_COUNTRY_TLD.put("IL", "co.il"); // ISRAEL GOOGLE_COUNTRY_TLD.put(Locale.ITALY.getCountry(), "it"); GOOGLE_COUNTRY_TLD.put(Locale.JAPAN.getCountry(), "co.jp"); GOOGLE_COUNTRY_TLD.put(Locale.KOREA.getCountry(), "co.kr"); GOOGLE_COUNTRY_TLD.put("NL", "nl"); // NETHERLANDS GOOGLE_COUNTRY_TLD.put("PL", "pl"); // POLAND GOOGLE_COUNTRY_TLD.put("PT", "pt"); // PORTUGAL GOOGLE_COUNTRY_TLD.put("RU", "ru"); // RUSSIA GOOGLE_COUNTRY_TLD.put("SK", "sk"); // SLOVAK REPUBLIC GOOGLE_COUNTRY_TLD.put("SI", "si"); // SLOVENIA GOOGLE_COUNTRY_TLD.put("ES", "es"); // SPAIN GOOGLE_COUNTRY_TLD.put("SE", "se"); // SWEDEN GOOGLE_COUNTRY_TLD.put("CH", "ch"); // SWITZERLAND GOOGLE_COUNTRY_TLD.put(Locale.TAIWAN.getCountry(), "tw"); GOOGLE_COUNTRY_TLD.put("TR", "com.tr"); // TURKEY GOOGLE_COUNTRY_TLD.put(Locale.UK.getCountry(), "co.uk"); GOOGLE_COUNTRY_TLD.put(Locale.US.getCountry(), "com"); } /** * Google Product Search for mobile is available in fewer countries than web search. See here: * http://support.google.com/merchants/bin/answer.py?hl=en-GB&answer=160619 */ private static final Map<String,String> GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD; static { GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD = new HashMap<String,String>(); GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put("AU", "com.au"); // AUSTRALIA //GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put(Locale.CHINA.getCountry(), "cn"); GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put(Locale.FRANCE.getCountry(), "fr"); GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put(Locale.GERMANY.getCountry(), "de"); GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put(Locale.ITALY.getCountry(), "it"); GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put(Locale.JAPAN.getCountry(), "co.jp"); GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put("NL", "nl"); // NETHERLANDS GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put("ES", "es"); // SPAIN GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put("CH", "ch"); // SWITZERLAND GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put(Locale.UK.getCountry(), "co.uk"); GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD.put(Locale.US.getCountry(), "com"); } /** * Book search is offered everywhere that web search is available. */ private static final Map<String,String> GOOGLE_BOOK_SEARCH_COUNTRY_TLD = GOOGLE_COUNTRY_TLD; private static final Collection<String> TRANSLATED_HELP_ASSET_LANGUAGES = Arrays.asList("de", "en", "es", "fr", "it", "ja", "ko", "nl", "pt", "ru", "zh-rCN", "zh-rTW"); private LocaleManager() {} /** * @return country-specific TLD suffix appropriate for the current default locale * (e.g. "co.uk" for the United Kingdom) */ public static String getCountryTLD(Context context) { return doGetTLD(GOOGLE_COUNTRY_TLD, context); } /** * The same as above, but specifically for Google Product Search. * @return The top-level domain to use. */ public static String getProductSearchCountryTLD(Context context) { return doGetTLD(GOOGLE_PRODUCT_SEARCH_COUNTRY_TLD, context); } /** * The same as above, but specifically for Google Book Search. * @return The top-level domain to use. */ public static String getBookSearchCountryTLD(Context context) { return doGetTLD(GOOGLE_BOOK_SEARCH_COUNTRY_TLD, context); } /** * Does a given URL point to Google Book Search, regardless of domain. * * @param url The address to check. * @return True if this is a Book Search URL. */ public static boolean isBookSearchUrl(String url) { return url.startsWith("http://google.com/books") || url.startsWith("http://books.google."); } private static String getSystemCountry() { Locale locale = Locale.getDefault(); return locale == null ? DEFAULT_COUNTRY : locale.getCountry(); } private static String getSystemLanguage() { Locale locale = Locale.getDefault(); if (locale == null) { return DEFAULT_LANGUAGE; } String language = locale.getLanguage(); // Special case Chinese if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(language)) { return language + "-r" + getSystemCountry(); } return language; } public static String getTranslatedAssetLanguage() { String language = getSystemLanguage(); return TRANSLATED_HELP_ASSET_LANGUAGES.contains(language) ? language : DEFAULT_LANGUAGE; } private static String doGetTLD(Map<String,String> map, Context context) { String tld = map.get(getCountry(context)); return tld == null ? DEFAULT_TLD : tld; } public static String getCountry(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String countryOverride = prefs.getString(PreferencesActivity.KEY_SEARCH_COUNTRY, null); if (countryOverride != null && countryOverride.length() > 0 && !"-".equals(countryOverride)) { return countryOverride; } return getSystemCountry(); } }
apache-2.0
prasenjit-net/boot-test
shared-service/src/main/java/net/prasenjit/sharedservice/DataMaker.java
2366
/* * Copyright (c) 2016 Prasenjit Purohit * * 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.prasenjit.sharedservice; import net.prasenjit.sharedservice.domain.DataType; import net.prasenjit.sharedservice.domain.ItemData; import net.prasenjit.sharedservice.domain.ProfileItem; import net.prasenjit.sharedservice.repository.ProfileItemRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.Collections; /** * Created by pp03582 on 2/23/2016. */ @Component public class DataMaker implements CommandLineRunner { @Autowired private ProfileItemRepository itemRepository; @Override public void run(String... args) throws Exception { ProfileItem pi = new ProfileItem(); pi.setProfileId("profile1"); pi.setItemKey("key1"); pi.setItemValue(ItemData.builder().dataType(DataType.STRING).data("value1").build()); itemRepository.saveAndFlush(pi); pi = new ProfileItem(); pi.setProfileId("profile1"); pi.setItemKey("key2"); pi.setItemValue(ItemData.builder().dataType(DataType.STRING).data("value2").build()); itemRepository.saveAndFlush(pi); pi = new ProfileItem(); pi.setProfileId("profile1"); pi.setItemKey("key-list"); pi.setItemValue(ItemData.builder().dataType(DataType.LIST).data(Collections.singletonList("value1")).build()); itemRepository.saveAndFlush(pi); pi = new ProfileItem(); pi.setProfileId("profile1"); pi.setItemKey("key-map"); pi.setItemValue(ItemData.builder().dataType(DataType.HASH).data(Collections.singletonMap("key1", "value1")).build()); itemRepository.saveAndFlush(pi); } }
apache-2.0
KritikalFabric/corefabric.io
src/main/java/org/kritikal/fabric/net/smtp/SmtpTransactionStateEnum.java
193
package org.kritikal.fabric.net.smtp; /** * Created by ben on 5/14/14. */ public enum SmtpTransactionStateEnum { INITIAL, HELO, STARTTLS, MAIL_FROM, RCPT_TO, DATA, }
apache-2.0
austriapro/ebinterface-ubl-mapping
src/main/java/at/austriapro/ebinterface/ubl/from/EbiNamespaceContext.java
2363
/* * Copyright (c) 2010-2015 Bundesrechenzentrum GmbH - www.brz.gv.at * Copyright (c) 2015-2022 AUSTRIAPRO - www.austriapro.at * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package at.austriapro.ebinterface.ubl.from; import javax.xml.XMLConstants; import com.helger.ebinterface.CEbInterface; import com.helger.xml.CXML; import com.helger.xml.namespace.MapBasedNamespaceContext; import com.helger.xsds.xmldsig.CXMLDSig; /** * A special map-based namespace context that maps XML prefixes to namespace * URLs. * * @author Philip Helger */ public class EbiNamespaceContext extends MapBasedNamespaceContext { public EbiNamespaceContext () { addMapping (CXML.XML_NS_PREFIX_XSI, XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI); addMapping (CXML.XML_NS_PREFIX_XSD, XMLConstants.W3C_XML_SCHEMA_NS_URI); addMapping (CXMLDSig.DEFAULT_PREFIX, CXMLDSig.NAMESPACE_URI); addMapping ("eb30", CEbInterface.EBINTERFACE_30_NS); addMapping ("eb302", CEbInterface.EBINTERFACE_302_NS); addMapping ("eb40", CEbInterface.EBINTERFACE_40_NS); addMapping ("eb40e", CEbInterface.EBINTERFACE_40_NS_EXT); addMapping ("eb40s", CEbInterface.EBINTERFACE_40_NS_SV); addMapping ("eb41", CEbInterface.EBINTERFACE_41_NS); addMapping ("eb41e", CEbInterface.EBINTERFACE_41_NS_EXT); addMapping ("eb41s", CEbInterface.EBINTERFACE_41_NS_SV); addMapping ("eb42", CEbInterface.EBINTERFACE_42_NS); addMapping ("eb42e", CEbInterface.EBINTERFACE_42_NS_EXT); addMapping ("eb42s", CEbInterface.EBINTERFACE_42_NS_SV); addMapping ("eb43", CEbInterface.EBINTERFACE_43_NS); addMapping ("eb43e", CEbInterface.EBINTERFACE_43_NS_EXT); addMapping ("eb43s", CEbInterface.EBINTERFACE_43_NS_SV); addMapping ("eb50", CEbInterface.EBINTERFACE_50_NS); addMapping ("eb60", CEbInterface.EBINTERFACE_60_NS); } }
apache-2.0
jtgeiger/grison
lib/src/main/java/com/sibilantsolutions/grison/driver/foscam/mapper/DtoToEntityMapper.java
167
package com.sibilantsolutions.grison.driver.foscam.mapper; import java.util.function.Function; public interface DtoToEntityMapper<I, O> extends Function<I, O> { }
apache-2.0
jboss-logging/slf4j-jboss-logmanager
src/test/java/org/slf4j/impl/LoggerTestCase.java
5790
/* * JBoss, Home of Professional Open Source. * * Copyright 2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slf4j.impl; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.logging.Level; import java.util.logging.LogRecord; import org.jboss.logmanager.ExtHandler; import org.jboss.logmanager.ExtLogRecord; import org.jboss.logmanager.LogContext; import org.jboss.logmanager.LogContextSelector; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.slf4j.Marker; import org.slf4j.helpers.BasicMarker; import org.slf4j.helpers.BasicMarkerFactory; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class LoggerTestCase { private static final LogContext LOG_CONTEXT = LogContext.create(); private static final java.util.logging.Logger ROOT = LOG_CONTEXT.getLogger(""); private static final QueueHandler HANDLER = new QueueHandler(); private static final LogContextSelector DEFAULT_SELECTOR = LogContext.getLogContextSelector(); @BeforeClass public static void configureLogManager() { LogContext.setLogContextSelector(() -> LOG_CONTEXT); ROOT.addHandler(HANDLER); } @AfterClass public static void cleanup() throws Exception { LOG_CONTEXT.close(); LogContext.setLogContextSelector(DEFAULT_SELECTOR); } @After public void clearHandler() { HANDLER.close(); } @Test public void testLogger() { final Logger logger = LoggerFactory.getLogger(LoggerTestCase.class); Assert.assertTrue(expectedTypeMessage(Slf4jLogger.class, logger.getClass()), logger instanceof Slf4jLogger); // Ensure the logger logs something final String testMsg = "This is a test message"; logger.info(testMsg); ExtLogRecord record = HANDLER.messages.poll(); Assert.assertNotNull(record); Assert.assertEquals(testMsg, record.getMessage()); Assert.assertNull(record.getParameters()); // Test a formatted message logger.info("This is a test formatted {}", "{message}"); record = HANDLER.messages.poll(); Assert.assertNotNull(record); Assert.assertEquals("This is a test formatted {message}", record.getFormattedMessage()); Assert.assertArrayEquals("Expected parameter not found.", new Object[] {"{message}"}, record.getParameters()); } @Test public void testLoggerWithExceptions() { final Logger logger = LoggerFactory.getLogger(LoggerTestCase.class); final RuntimeException e = new RuntimeException("Test exception"); final String testMsg = "This is a test message"; logger.info(testMsg, e); LogRecord record = HANDLER.messages.poll(); Assert.assertNotNull(record); Assert.assertEquals(testMsg, record.getMessage()); Assert.assertEquals("Cause is different from the expected cause", e, record.getThrown()); // Test format with the last parameter being the throwable which should set be set on the record logger.info("This is a test formatted {}", "{message}", e); record = HANDLER.messages.poll(); Assert.assertNotNull(record); Assert.assertEquals("This is a test formatted {message}", record.getMessage()); Assert.assertEquals("Cause is different from the expected cause", e, record.getThrown()); } @Test public void testLoggerWithMarkers() { final Logger logger = LoggerFactory.getLogger(LoggerTestCase.class); final Marker marker = new BasicMarkerFactory().getMarker("test"); logger.info(marker, "log message"); LogRecord record = HANDLER.messages.poll(); Assert.assertNotNull(record); // TODO: record.getMarker() must be same instance of "marker" } @Test public void testMDC() { Assert.assertSame(expectedTypeMessage(Slf4jMDCAdapter.class, MDC.getMDCAdapter().getClass()), MDC.getMDCAdapter().getClass(), Slf4jMDCAdapter.class); final String key = Long.toHexString(System.currentTimeMillis()); MDC.put(key, "value"); Assert.assertEquals("MDC value should be \"value\"", "value", MDC.get(key)); Assert.assertEquals("MDC value should be \"value\"", "value", org.jboss.logmanager.MDC.get(key)); } private static String expectedTypeMessage(final Class<?> expected, final Class<?> found) { return String.format("Expected type %s but found type %s", expected.getName(), found.getName()); } private static class QueueHandler extends ExtHandler { final BlockingDeque<ExtLogRecord> messages = new LinkedBlockingDeque<>(); @Override protected void doPublish(final ExtLogRecord record) { messages.add(record); } @Override public void flush() { } @Override public void close() throws SecurityException { messages.clear(); setLevel(Level.ALL); } } }
apache-2.0
dlazaro66/iTunesArtistExample
app/src/main/java/com/dlazaro66/itunesartistsexample/artistList/ArtistListActivity.java
4540
package com.dlazaro66.itunesartistsexample.artistList; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import com.dlazaro66.itunesartistsexample.R; import com.dlazaro66.itunesartistsexample.artistDetail.ArtistDetailActivity; import com.dlazaro66.itunesartistsexample.common.BaseActivity; import com.dlazaro66.itunesartistsexample.model.Artist; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; /** * @description Activity which show a list of artists. */ public class ArtistListActivity extends BaseActivity implements ArtistListView, SwipeRefreshLayout.OnRefreshListener { @InjectView(R.id.toolbar) Toolbar toolbar; @InjectView(R.id.recycler_view) RecyclerView recyclerView; @InjectView(R.id.activity_main_swipe_refresh_layout) SwipeRefreshLayout swipeRefreshLayout; ArtistListPresenter presenter; private View latestPressedView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_artist_list); ButterKnife.inject(this); setSupportActionBar(toolbar); getSupportActionBar().setTitle(getString(R.string.itunes_bands)); swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.primary), getResources().getColor(R.color.accent)); swipeRefreshLayout.setOnRefreshListener(this); recyclerView.setLayoutManager(new GridLayoutManager(this, getResources().getInteger(R.integer.artist_list_number_of_rows))); recyclerView.setItemAnimator(new DefaultItemAnimator()); enableWorkaroundForSwipeRefreshLayoutAndReclyclerView(swipeRefreshLayout); presenter = new ArtistListPresenter(); presenter.onViewReady(this); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); presenter.onDetachedView(); } @Override public void showLoadingView() { swipeRefreshLayout.setRefreshing(true); } @Override public void hideLoadingView() { swipeRefreshLayout.setRefreshing(false); } @Override public void renderResults(List<Artist> artistList) { ArtistAdapter adapter = new ArtistAdapter(artistList); adapter.setOnItemClickListener(new ArtistAdapter.OnItemClickListener() { @Override public void onItemClick(View v, Artist artist) { latestPressedView= v; presenter.onArtistSelected(artist); } }); recyclerView.setAdapter(adapter); } @Override public void showErrorMessage() { Snackbar.make(findViewById(android.R.id.content), R.string.error, Snackbar.LENGTH_LONG) .setAction(R.string.retry, new View.OnClickListener() { @Override public void onClick(View v) { presenter.onRetryButtonPressed(); } }) .show(); } @Override public void openArtistDetailActivity(Artist artist) { Intent intent = ArtistDetailActivity.getCallingIntent(this, artist); ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation( this, latestPressedView, getString(R.string.artist_cover_transition_id) ); ActivityCompat.startActivity(this, intent, options.toBundle()); } @Override public void onRefresh() { presenter.onRefreshPulled(); } // That's a workaround for a reported issue // @see https://code.google.com/p/android/issues/detail?id=77712 // TODO try to fix ASAP private void enableWorkaroundForSwipeRefreshLayoutAndReclyclerView(SwipeRefreshLayout swipeRefreshLayout) { swipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics())); } }
apache-2.0
bbxyard/bbxyard
yard/skills/66-java/mp-demo/src/main/java/com/bbxyard/mp/demo/dto/HttpRespMsg.java
1428
package com.bbxyard.mp.demo.dto; public class HttpRespMsg { private int code; // 状态码 private String desc; // 描述 private Object data; // 负载数据 private String errmsg; // 错误信息 public HttpRespMsg(Object data, int code) { this.data = data; this.code = code; } public HttpRespMsg(String errmsg, int code) { this.errmsg = errmsg; this.code = code; } public static HttpRespMsg Ok(Object data) { return new HttpRespMsg(data, 200); } public static HttpRespMsg Error(String errmsg, int code) { return new HttpRespMsg(errmsg, code); } @Override public String toString() { String dataStr = data.toString(); String s = String.format("{ \"code\": %d, \"desc\": \"%s\", \"errmsg\": \"%s\", \"data\": %s }", code, desc, errmsg, dataStr); return s; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } }
apache-2.0
BlueBoxWare/LibGDXPlugin
gen/com/gmail/blueboxware/libgdxplugin/filetypes/skin/psi/SkinStringLiteral.java
428
// This is a generated file. Not intended for manual editing. package com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface SkinStringLiteral extends SkinValue { @NotNull String getValue(); void setValue(@NotNull String string); @Nullable SkinPropertyName asPropertyName(); boolean isQuoted(); }
apache-2.0
flex-oss/flex-ui
flex-ui-core/src/main/java/org/cdlflex/ui/markup/html/basic/DateLabel.java
1945
/** * 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.cdlflex.ui.markup.html.basic; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.apache.wicket.model.IModel; import org.apache.wicket.util.convert.converter.DateConverter; /** * A Label that displays a Date using a custom DateFormat to render it. */ public class DateLabel extends ConvertingLabel<Date> { private static final long serialVersionUID = 1L; private DateFormat dateFormat; private DateConverter converter = new DateConverter() { private static final long serialVersionUID = 1L; @Override public DateFormat getDateFormat(Locale locale) { DateFormat format = DateLabel.this.getDateFormat(); return (format == null) ? super.getDateFormat(locale) : format; } }; public DateLabel(String id) { super(id); } public DateLabel(String id, IModel<Date> model) { this(id, null, model); } public DateLabel(String id, DateFormat format, IModel<Date> model) { super(id, model); setDateFormat(format); } public DateFormat getDateFormat() { return dateFormat; } public void setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public DateConverter getConverter() { return converter; } }
apache-2.0
jporras66/8583core
8583core/src/main/java/com/indarsoft/iso8583core/coretypes/F005.java
619
package com.indarsoft.iso8583core.coretypes; import com.indarsoft.iso8583core.types.Field; import com.indarsoft.iso8583core.types.TypeFixed; /** Application : ISO8583CORE - Class F005 - Amount, settlement. * */ public class F005 extends TypeFixed { private F005 (byte[] bytearr, Field field) { super( bytearr, field ) ; if ( ! super.isValid() ){ return; } } /** Static constructor . * * @param bytearr * @return {@link F005 } */ protected static F005 get ( byte[] bytearr, Field field ){ return new F005 ( bytearr, field ) ; } }
apache-2.0
j3whalen/GlimmrApp
app/src/glimmr/common/OAuthUtils.java
3061
package java.com.bourke.glimmr.common; import com.bourke.glimmr.BuildConfig; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.bourke.glimmr.activities.ExploreActivity; import com.bourke.glimmr.common.*; import com.googlecode.flickrjandroid.oauth.OAuth; import com.googlecode.flickrjandroid.oauth.OAuthToken; import com.googlecode.flickrjandroid.people.User; public class OAuthUtils { private static final String TAG = "Glimmr/OAuthUtils"; public static boolean isLoggedIn(Context context) { OAuth oauth = loadAccessToken(context); boolean isLoggedIn = (oauth != null && oauth.getUser() != null); if (BuildConfig.DEBUG) Log.d(TAG, "isLoggedIn: " + isLoggedIn); return isLoggedIn; } public static OAuth loadAccessToken(Context context) { SharedPreferences prefs = context.getSharedPreferences( com.bourke.glimmr.common.Constants.PREFS_NAME, Context.MODE_PRIVATE); String oauthTokenString = prefs.getString(com.bourke.glimmr.common.Constants.KEY_OAUTH_TOKEN, null); String tokenSecret = prefs.getString(com.bourke.glimmr.common.Constants.KEY_TOKEN_SECRET, null); String userName = prefs.getString(com.bourke.glimmr.common.Constants.KEY_ACCOUNT_USER_NAME, null); String userId = prefs.getString(com.bourke.glimmr.common.Constants.KEY_ACCOUNT_USER_ID, null); OAuth oauth = null; if (oauthTokenString != null && tokenSecret != null && userName != null && userId != null) { oauth = new OAuth(); OAuthToken oauthToken = new OAuthToken(); oauth.setToken(oauthToken); oauthToken.setOauthToken(oauthTokenString); oauthToken.setOauthTokenSecret(tokenSecret); User user = new User(); user.setUsername(userName); user.setId(userId); oauth.setUser(user); } else { Log.w(TAG, "No saved oauth token found"); return null; } return oauth; } /** * Clear all user data from SharedPreferences and return to ExploreActivity. * @param context */ public static void logout(Context context) { SharedPreferences prefs = context.getSharedPreferences( com.bourke.glimmr.common.Constants.PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.remove(com.bourke.glimmr.common.Constants.KEY_OAUTH_TOKEN); editor.remove(com.bourke.glimmr.common.Constants.KEY_TOKEN_SECRET); editor.remove(com.bourke.glimmr.common.Constants.KEY_ACCOUNT_USER_NAME); editor.remove(com.bourke.glimmr.common.Constants.KEY_ACCOUNT_USER_ID); editor.commit(); Intent exploreActivity = new Intent(context, ExploreActivity.class); exploreActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(exploreActivity); } }
apache-2.0
xroocky/ZhiHuRiBao
app/src/main/java/net/roocky/zhihuribao/Module/Fragment/HomeFragment.java
7912
package net.roocky.zhihuribao.Module.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.android.volley.Response; import com.bigkoo.convenientbanner.ConvenientBanner; import net.roocky.zhihuribao.Base.BaseHttpFragment; import net.roocky.zhihuribao.Http.Jackson; import net.roocky.zhihuribao.Model.NewsItem; import net.roocky.zhihuribao.Model.Request.BeforeNews; import net.roocky.zhihuribao.Model.Request.LatestNews; import net.roocky.zhihuribao.Model.Story; import net.roocky.zhihuribao.Model.TopNewsItem; import net.roocky.zhihuribao.Model.TopStory; import net.roocky.zhihuribao.Module.Activity.ArticleContentActivity; import net.roocky.zhihuribao.Module.Adapter.HomeRecyclerAdapter; import net.roocky.zhihuribao.R; import net.roocky.zhihuribao.Util.DateUtil; import net.roocky.zhihuribao.Widget.BottomRecyclerView; import net.roocky.zhihuribao.Widget.RefreshLayout; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Random; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by roocky on 03/02. * * 首页Fragment * */ public class HomeFragment extends BaseHttpFragment implements RefreshLayout.OnLoadListener, BottomRecyclerView.OnScrollingListener { @Bind(R.id.brv_home) BottomRecyclerView brvHome; @Bind(R.id.rl_home) RefreshLayout rlHome; private List<TopNewsItem> topNewsItems = new ArrayList<>(); private List<NewsItem> newsItems = new ArrayList<>(); private HomeRecyclerAdapter adapter; private String date; private List<Integer> datePosition = new ArrayList<>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); ButterKnife.bind(this, view); brvHome.setHasFixedSize(true); brvHome.setLayoutManager(new LinearLayoutManager(getActivity())); brvHome.setOnScrollingListener(this); //监听滑动的位置来设置ActionBar的title rlHome.setColorSchemeResources(android.R.color.holo_blue_light); rlHome.setOnRefreshListener(this); //下拉刷新 rlHome.setOnLoadListener(this); //上拉加载 //实现进入界面自动刷新 rlHome.post(new Runnable() { @Override public void run() { rlHome.setRefreshing(true); //打开刷新动画 new Thread(new getRefresh()).start(); //提交刷新请求 } }); return view; } @Override protected String getRefreshUrl() { return getString(R.string.urlLatestNews); } //下拉刷新请求(HttpRequest)完成响应 @Override protected Response.Listener<JSONObject> getRefreshListener() { return new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { topNewsItems.clear(); newsItems.clear(); datePosition.clear(); datePosition.add(1); LatestNews latestNews = Jackson.getClass(jsonObject.toString(), LatestNews.class); if (latestNews != null) { date = latestNews.getDate(); List<TopStory> topStories = latestNews.getTop_stories(); List<Story> stories = latestNews.getStories(); newsItems.add(new NewsItem(0, date, 0, null)); //为日期项提供显示空间 for (int i = 0; i < topStories.size(); i++) { topNewsItems.add(new TopNewsItem(topStories.get(i).getId(), topStories.get(i).getTitle(), topStories.get(i).getImage())); } for (int i = 0; i < stories.size(); i++) { newsItems.add(new NewsItem(stories.get(i).getId(), stories.get(i).getTitle(), new Random().nextInt(1000), stories.get(i).getImages())); } datePosition.add(newsItems.size() + 1); adapter = new HomeRecyclerAdapter(getActivity(), topNewsItems, newsItems); if (brvHome == null) return; brvHome.setAdapter(adapter); rlHome.post(new Runnable() { @Override public void run() { rlHome.setRefreshing(false); //关闭刷新 } }); adapter.setOnItemClickListener(new HomeRecyclerAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(getActivity(), ArticleContentActivity.class); intent.putExtra("id", newsItems.get(position - 1).getId()); startActivity(intent); } }); } } }; } @Override protected String getLoadUrl() { return "news/before/" + date; } //上拉加载请求(HttpRequest)完成响应 @Override protected Response.Listener<JSONObject> getLoadListener() { return new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { newsItems.remove(newsItems.size() - 1); //移除ProgressBar BeforeNews beforeNews = Jackson.getClass(jsonObject.toString(), BeforeNews.class); assert beforeNews != null; date = beforeNews.getDate(); List<Story> stories = beforeNews.getStories(); //"2"包含了 顶部图片 和 当前正在添加的日期项 newsItems.add(new NewsItem(0, date, 0, null)); for (int i = 0; i < stories.size(); i ++) { newsItems.add(new NewsItem(stories.get(i).getId(), stories.get(i).getTitle(), new Random().nextInt(1000), stories.get(i).getImages())); } datePosition.add(newsItems.size() + 1); adapter.notifyDataSetChanged(); rlHome.setLoading(false); } }; } //上拉加载回调方法 @Override public void onLoad() { rlHome.setLoading(true); //设置当前为加载状态 newsItems.add(null); //为ProgressBar提供显示空间 adapter.notifyDataSetChanged(); //刷新数据(显示ProgressBar) new Thread(new getLoad()).start(); } @Override public void onScrolling() { int firstVisible = ((LinearLayoutManager)brvHome.getLayoutManager()).findFirstVisibleItemPosition(); if (datePosition.contains(firstVisible)) { String date = DateUtil.dateFormat(newsItems.get(firstVisible - 1).getTitle(), "MM月dd日") + " " + DateUtil.getChinaDayOfWeek(newsItems.get(firstVisible - 1).getTitle()); if (firstVisible != 1) { //ActionBar设置title为日期 ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(date); } else { //ActionBar设置title为“今日热闻” ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getString(R.string.todayNews)); } } else if (firstVisible == 0) { //ActionBar设置title为“首页” ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getString(R.string.mn_home)); } } }
apache-2.0
oehme/analysing-gradle-performance
my-lib/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p38/Test779.java
2164
package org.gradle.test.performance.mediummonolithicjavaproject.p38; import org.junit.Test; import static org.junit.Assert.*; public class Test779 { Production779 objectUnderTest = new Production779(); @Test public void testProperty0() { Production776 value = new Production776(); objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { Production777 value = new Production777(); objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { Production778 value = new Production778(); objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
apache-2.0
Stratio/Explorer
server/src/main/java/com/stratio/explorer/socket/explorerOperations/RunParagraphOperation.java
3010
/** * Copyright (C) 2015 Stratio (http://stratio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stratio.explorer.socket.explorerOperations; import com.google.common.base.Strings; import com.stratio.explorer.notebook.Note; import com.stratio.explorer.notebook.Notebook; import com.stratio.explorer.notebook.Paragraph; import com.stratio.explorer.socket.ConnectionManager; import com.stratio.explorer.socket.IExplorerOperation; import com.stratio.explorer.socket.Message; import com.stratio.explorer.socket.ExplorerOperationException; import org.java_websocket.WebSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Map; /** * Created by jmgomez on 3/09/15. */ public class RunParagraphOperation implements IExplorerOperation { private static final Logger LOG = LoggerFactory.getLogger(RunParagraphOperation.class); @Override public void execute(WebSocket conn, Notebook notebook, Message messagereceived) { try { final String paragraphId = (String) messagereceived.get("id"); if (paragraphId != null) { final Note note = notebook.getNote(ConnectionManager.getInstance().getOpenNoteId(conn)); Paragraph p = note.getParagraph(paragraphId); String text = (String) messagereceived.get("paragraph"); p.setText(text); p.setTitle((String) messagereceived.get("title")); Map<String, Object> params = (Map<String, Object>) messagereceived.get("params"); p.settings.setParams(params); Map<String, Object> config = (Map<String, Object>) messagereceived.get("config"); config.put("tableHide", false); p.setConfig(config); // if it's the last paragraph, let's add a new one boolean isTheLastParagraph = note.getLastParagraph().getId().equals(p.getId()); if (!Strings.isNullOrEmpty(text) && isTheLastParagraph) { note.addParagraph(); } note.persist(); ConnectionManager.getInstance().broadcastNote(note); note.run(paragraphId); } }catch(IOException ioe){ String msg = "A exception happens in when we are trying to execute paragraph."+ioe.getMessage(); LOG.error(msg); new ExplorerOperationException(msg,ioe); } } }
apache-2.0
boneman1231/org.apache.felix
trunk/tools/mangen/src/main/java/org/apache/felix/tool/mangen/rule/GenericRule.java
3177
/* * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.felix.tool.mangen.rule; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import org.apache.felix.tool.mangen.GenericHandlerItemImpl; import org.apache.felix.tool.mangen.Rule; /** * Holder for common Rule handling methods, such as reporting * * @version $Revision: 27 $ * @author <A HREF="mailto:robw@ascert.com">Rob Walker</A> */ public abstract class GenericRule extends GenericHandlerItemImpl implements Rule { ////////////////////////////////////////////////// // STATIC VARIABLES ////////////////////////////////////////////////// ////////////////////////////////////////////////// // STATIC PUBLIC METHODS ////////////////////////////////////////////////// ////////////////////////////////////////////////// // INSTANCE VARIABLES ////////////////////////////////////////////////// /** Holds buffered rule output in case a rule report is requested */ public ByteArrayOutputStream rptBuf = new ByteArrayOutputStream(); public PrintStream rptOut = new PrintStream(rptBuf); ////////////////////////////////////////////////// // CONSTRUCTORS ////////////////////////////////////////////////// public GenericRule() { } ////////////////////////////////////////////////// // ACCESSOR METHODS ////////////////////////////////////////////////// ////////////////////////////////////////////////// // PUBLIC INSTANCE METHODS ////////////////////////////////////////////////// ////////////////////////////////////////////////// // INTERFACE METHODS - Rule ////////////////////////////////////////////////// public void report(PrintStream rpt) throws IOException { rptBuf.writeTo(rpt); } ////////////////////////////////////////////////// // PROTECTED INSTANCE METHODS ////////////////////////////////////////////////// ////////////////////////////////////////////////// // PRIVATE INSTANCE METHODS ////////////////////////////////////////////////// ////////////////////////////////////////////////// // STATIC INNER CLASSES ////////////////////////////////////////////////// ////////////////////////////////////////////////// // NON-STATIC INNER CLASSES ////////////////////////////////////////////////// }
apache-2.0
sarl/sarl
main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/binding/BindingFactory.java
16150
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2021 the original authors 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 io.sarl.lang.mwe2.binding; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import com.ibm.icu.text.MessageFormat; import org.eclipse.xtend2.lib.StringConcatenationClient; import org.eclipse.xtext.util.Strings; import org.eclipse.xtext.xtext.generator.model.GuiceModuleAccess; import org.eclipse.xtext.xtext.generator.model.GuiceModuleAccess.BindKey; import org.eclipse.xtext.xtext.generator.model.GuiceModuleAccess.BindValue; import org.eclipse.xtext.xtext.generator.model.GuiceModuleAccess.Binding; import org.eclipse.xtext.xtext.generator.model.TypeReference; /** * An injected element. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ public class BindingFactory { private static final String CONFIGURE_PREFIX = "configure"; //$NON-NLS-1$ private static final String BIND_PREFIX = "bind"; //$NON-NLS-1$ private static final String REFERENCE_PREFIX = "ref "; //$NON-NLS-1$ private WeakReference<GuiceModuleAccess> module; private String name; private final Set<Binding> bindings = new HashSet<>(); private final List<Binding> removableBindings = new ArrayList<>(); /** Change the name of the factory. * * @param name the name. */ public void setName(String name) { this.name = name; } /** Change the associated Guice module. * * @param module the associated Guice module. */ public void setGuiceModule(GuiceModuleAccess module) { this.module = new WeakReference<>(module); } /** Bind an annotated element. * * @param bind the type to bind. * @param annotatedWith the annotation to consider. * @param to the target type. * @param functionName the optional function name. * @return the binding element. */ protected Binding bindAnnotatedWith(TypeReference bind, TypeReference annotatedWith, TypeReference to, String functionName) { final StringConcatenationClient client = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation builder) { builder.append("binder.bind("); //$NON-NLS-1$ builder.append(bind); builder.append(".class).annotatedWith("); //$NON-NLS-1$ builder.append(annotatedWith); builder.append(".class).to("); //$NON-NLS-1$ builder.append(to); builder.append(".class);"); //$NON-NLS-1$ } }; String fctname = functionName; if (Strings.isEmpty(fctname)) { fctname = bind.getSimpleName(); } final BindKey key = new GuiceModuleAccess.BindKey(formatFunctionName(fctname), null, false, false); final BindValue statements = new BindValue(null, null, false, Collections.singletonList(client)); return new Binding(key, statements, true, this.name); } /** Bind an annotated element. * * @param bind the type to bind. * @param annotatedWith the annotation to consider. * @param to the instance. * @param functionName the optional function name. * @return the binding element. */ protected Binding bindAnnotatedWithToInstance(TypeReference bind, TypeReference annotatedWith, String to, String functionName) { final StringConcatenationClient client = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation builder) { builder.append("binder.bind("); //$NON-NLS-1$ builder.append(bind); builder.append(".class).annotatedWith("); //$NON-NLS-1$ builder.append(annotatedWith); builder.append(".class).toInstance("); //$NON-NLS-1$ builder.append(to); builder.append(".class);"); //$NON-NLS-1$ } }; String fctname = functionName; if (Strings.isEmpty(fctname)) { fctname = bind.getSimpleName(); } final BindKey key = new GuiceModuleAccess.BindKey(formatFunctionName(fctname), null, false, false); final BindValue statements = new BindValue(null, null, false, Collections.singletonList(client)); return new Binding(key, statements, true, this.name); } /** Bind a type annotated with a name of the given value. * * @param bind the type to bind. * @param name the name to consider. * @param to the target type. * @param functionName the optional function name. * @return the binding element. */ protected Binding bindAnnotatedWithName(TypeReference bind, String name, TypeReference to, String functionName) { String tmpName = Strings.emptyIfNull(name); if (tmpName.startsWith(REFERENCE_PREFIX)) { tmpName = tmpName.substring(REFERENCE_PREFIX.length()).trim(); } else { tmpName = "\"" + tmpName + "\""; //$NON-NLS-1$//$NON-NLS-2$ } final String unferencedName = tmpName; final StringConcatenationClient client = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation builder) { builder.append("binder.bind("); //$NON-NLS-1$ builder.append(bind); builder.append(".class).annotatedWith(Names.named("); //$NON-NLS-1$ builder.append(unferencedName); builder.append(")).to("); //$NON-NLS-1$ builder.append(to); builder.append(".class);"); //$NON-NLS-1$ } }; String fctname = functionName; if (Strings.isEmpty(fctname)) { fctname = name; } final BindKey key = new GuiceModuleAccess.BindKey(formatFunctionName(fctname), null, false, false); final BindValue statements = new BindValue(null, null, false, Collections.singletonList(client)); return new Binding(key, statements, true, this.name); } /** Bind a type annotated with a name of the given value. * * @param bind the type to bind. * @param name the name to consider. * @param to the instance. * @param functionName the optional function name. * @return the binding element. */ protected Binding bindAnnotatedWithNameToInstance(TypeReference bind, String name, String to, String functionName) { String tmpName = Strings.emptyIfNull(name); if (tmpName.startsWith(REFERENCE_PREFIX)) { tmpName = tmpName.substring(REFERENCE_PREFIX.length()).trim(); } else { tmpName = "\"" + tmpName + "\""; //$NON-NLS-1$//$NON-NLS-2$ } final String unferencedName = tmpName; final StringConcatenationClient client = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation builder) { builder.append("binder.bind("); //$NON-NLS-1$ builder.append(bind); builder.append(".class).annotatedWith(Names.named("); //$NON-NLS-1$ builder.append(unferencedName); builder.append(")).toInstance("); //$NON-NLS-1$ builder.append(to); builder.append(".class);"); //$NON-NLS-1$ } }; String fctname = functionName; if (Strings.isEmpty(fctname)) { fctname = name; } final BindKey key = new GuiceModuleAccess.BindKey(formatFunctionName(fctname), null, false, false); final BindValue statements = new BindValue(null, null, false, Collections.singletonList(client)); return new Binding(key, statements, true, this.name); } /** Bind a type to an instance expression. * * @param bind the type to bind. * @param functionName the name of the binding function. It may be {@code null} for the default name. * @param instanceExpression the expression that represents the instance. * @param isSingleton indicates if the instance is a singleton. * @param isEager indicates if the instance is an eager singleton. * @return the binding element. */ protected Binding bindToInstance(TypeReference bind, String functionName, String instanceExpression, boolean isSingleton, boolean isEager) { final BindKey type; final BindValue value; if (!Strings.isEmpty(functionName) && functionName.startsWith(CONFIGURE_PREFIX)) { final String fname = functionName.substring(CONFIGURE_PREFIX.length()); type = new BindKey(Strings.toFirstUpper(fname), null, isSingleton, isEager); final StringConcatenationClient client = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation builder) { builder.append("binder.bind("); //$NON-NLS-1$ builder.append(bind); builder.append(".class).toInstance("); //$NON-NLS-1$ builder.append(instanceExpression); builder.append(");"); //$NON-NLS-1$ } }; value = new BindValue(null, null, false, Collections.singletonList(client)); } else { String fname = functionName; if (fname != null && fname.startsWith(BIND_PREFIX)) { fname = fname.substring(BIND_PREFIX.length()); } type = new BindKey(Strings.toFirstUpper(fname), bind, isSingleton, isEager); final StringConcatenationClient client = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation builder) { builder.append(instanceExpression); } }; value = new BindValue(client, null, false, Collections.emptyList()); } return new Binding(type, value, true, this.name); } /** Bind a type to concrete type. * * @param bind the type to bind. * @param functionName the name of the binding function. It may be {@code null} for the default name. * @param to the concrete type. * @param isSingleton indicates if the instance is a singleton. * @param isEager indicates if the instance is an eager singleton. * @param isProvider indicates if the binding is for a provider. * @return the binding element. */ protected Binding bindToType( TypeReference bind, String functionName, TypeReference to, boolean isSingleton, boolean isEager, boolean isProvider) { final BindKey type; final BindValue value; if (!Strings.isEmpty(functionName) && functionName.startsWith(CONFIGURE_PREFIX)) { final String fname = functionName.substring(CONFIGURE_PREFIX.length()); type = new GuiceModuleAccess.BindKey(Strings.toFirstUpper(fname), null, false, false); final StringConcatenationClient client; if (isProvider) { client = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation builder) { builder.append("binder.bind("); //$NON-NLS-1$ builder.append(bind); builder.append(".class).toProvider("); //$NON-NLS-1$ builder.append(to); builder.append(".class);"); //$NON-NLS-1$ } }; } else { client = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation builder) { builder.append("binder.bind("); //$NON-NLS-1$ builder.append(bind); builder.append(".class).to("); //$NON-NLS-1$ builder.append(to); builder.append(".class);"); //$NON-NLS-1$ } }; } value = new BindValue(null, null, false, Collections.singletonList(client)); } else { String fname = functionName; if (fname != null && fname.startsWith(BIND_PREFIX)) { fname = fname.substring(BIND_PREFIX.length()); } type = new BindKey(Strings.toFirstUpper(fname), bind, isSingleton, isEager); value = new BindValue(null, to, false, Collections.emptyList()); } return new Binding(type, value, true, this.name); } private static Binding findBinding(Set<Binding> bindings, Binding binding) { for (final Binding bnd : bindings) { if (Objects.equals(bnd, binding)) { return bnd; } } return null; } private static String formatFunctionName(String name) { String formattedName = name; if (formattedName.startsWith(CONFIGURE_PREFIX)) { formattedName = formattedName.substring(CONFIGURE_PREFIX.length()); } else if (formattedName.startsWith(BIND_PREFIX)) { formattedName = formattedName.substring(BIND_PREFIX.length()); } return Strings.toFirstUpper(formattedName); } /** Add the binding. * * @param binding the binding to add. * @param override indicates if the binding could override an existing element. */ public void add(Binding binding, boolean override) { final Set<Binding> moduleBindings = this.module.get().getBindings(); final Binding otherBinding = findBinding(moduleBindings, binding); if (!override) { if (otherBinding != null) { throw new IllegalArgumentException(MessageFormat.format( "Forbidden override of {0} by {1}.", //$NON-NLS-1$ otherBinding, binding)); } } else if (otherBinding != null) { this.removableBindings.add(otherBinding); } if (!this.bindings.add(binding)) { throw new IllegalArgumentException( MessageFormat.format("Duplicate binding for {0} in {1}", binding.getKey(), this.name)); //$NON-NLS-1$ } } /** Put the bindings to the associated module. */ public void contributeToModule() { final GuiceModuleAccess module = this.module.get(); if (!this.removableBindings.isEmpty()) { // Ok, we are broking the Java secutiry manager. // But it's for having something working! try { final Field field = module.getClass().getDeclaredField("bindings"); //$NON-NLS-1$ // TODO Is this compatible with Java 11? field.setAccessible(true); final Collection<?> hiddenBindings = (Collection<?>) field.get(module); hiddenBindings.removeAll(this.removableBindings); } catch (Exception exception) { throw new IllegalStateException(exception); } } module.addAll(this.bindings); } private static TypeReference typeRef(String qualifiedName) { int index = qualifiedName.indexOf('$'); if (index > 0) { String classname = qualifiedName.substring(0, index); final String innerClasses = qualifiedName.substring(index + 1); index = classname.lastIndexOf('.'); if (index >= 0) { final String packageName = classname.substring(0, index); classname = classname.substring(index + 1) + '.' + innerClasses; return new TypeReference(packageName, classname); } } return TypeReference.typeRef(qualifiedName); } /** Convert a binding element to a Guive binding. * * @param element the element to convert. * @return the Guice binding. */ public Binding toBinding(BindingElement element) { final TypeReference typeReference = typeRef(element.getBind()); final String annotatedWith = element.getAnnotatedWith(); final String annotatedWithName = element.getAnnotatedWithName(); if (!Strings.isEmpty(annotatedWith)) { final TypeReference annotationType = typeRef(annotatedWith); if (element.isInstance()) { return bindAnnotatedWithToInstance(typeReference, annotationType, element.getTo(), element.getFunctionName()); } final TypeReference typeReference2 = typeRef(element.getTo()); return bindAnnotatedWith(typeReference, annotationType, typeReference2, element.getFunctionName()); } if (!Strings.isEmpty(annotatedWithName)) { if (element.isInstance()) { return bindAnnotatedWithNameToInstance(typeReference, annotatedWithName, element.getTo(), element.getFunctionName()); } final TypeReference typeReference2 = typeRef(element.getTo()); return bindAnnotatedWithName(typeReference, annotatedWithName, typeReference2, element.getFunctionName()); } if (element.isInstance()) { return bindToInstance(typeReference, element.getFunctionName(), element.getTo(), element.isSingleton(), element.isEager()); } final TypeReference typeReference2 = typeRef(element.getTo()); return bindToType( typeReference, element.getFunctionName(), typeReference2, element.isSingleton(), element.isEager(), element.isProvider()); } }
apache-2.0
anky21/Remember-Names
app/src/main/java/me/anky/connectid/data/source/local/TagsColumns.java
682
package me.anky.connectid.data.source.local; import net.simonvt.schematic.annotation.AutoIncrement; import net.simonvt.schematic.annotation.DataType; import net.simonvt.schematic.annotation.DefaultValue; import net.simonvt.schematic.annotation.NotNull; import net.simonvt.schematic.annotation.PrimaryKey; /** * Created by Anky An on 30/09/2017. * anky25@gmail.com */ public interface TagsColumns { @DataType(DataType.Type.INTEGER) @PrimaryKey @AutoIncrement String _ID = "_id"; @DataType(DataType.Type.TEXT) @NotNull String TAG = "tag"; @DataType(DataType.Type.TEXT) @DefaultValue("null") String CONNECTION_IDS = "connection_ids"; }
apache-2.0
jloisel/elastic-crud
db-integration-test/src/test/java/com/jeromeloisel/db/integration/test/ElasticTest.java
600
package com.jeromeloisel.db.integration.test; import org.elasticsearch.client.IndicesAdminClient; import org.junit.Test; import static org.junit.Assert.assertNotNull; public class ElasticTest extends SpringElasticSearchTest { @Test public void shouldAutowire() { assertNotNull(client); final IndicesAdminClient indices = client.admin().indices(); indices.prepareCreate("test").execute().actionGet(); flush("test"); indices.prepareDelete("test").execute().actionGet(); } @Test @Override public void shouldAutowireClient() { super.shouldAutowireClient(); } }
apache-2.0
semanticanalyzer/nlproc_sdk_sample_code
src/main/java/com/semanticanalyzer/TopicUploader.java
3199
package com.semanticanalyzer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import com.semanticanalyzer.dao.ArticleEntry; import com.semanticanalyzer.mappers.ArticleEntryMapper; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.List; @Slf4j public class TopicUploader { private final static String mashapeKey = "[PUT YOUR MASHAPE TOPIC API KEY HERE]"; private TopicUploader() {} public static void main(String[] args) { if (args.length < 1) { log.info("Please specify the resource_id to load from the db"); return; } TopicUploader topicUploader = new TopicUploader(); topicUploader.uploadDBEntries(args[0]); } private SqlSessionFactory initSqlSessionFactory() { String resource = "mybatis-config.xml"; try (InputStream inputStream = Resources.getResourceAsStream(resource)) { return new SqlSessionFactoryBuilder().build(inputStream, System.getenv("DB_ENVIRONMENT")); } catch (IOException e) { log.error("Error initializing SQL factory: {}", e); throw new RuntimeException(e); } } private void uploadDBEntries(String resourceId) { SqlSessionFactory sqlSessionFactory = initSqlSessionFactory(); try(SqlSession sqlSession = sqlSessionFactory.openSession()) { ArticleEntryMapper mapper = sqlSession.getMapper(ArticleEntryMapper.class); List<ArticleEntry> articleEntries = mapper.loadEntriesFromDB(resourceId); System.out.println("Loaded entries from DB: " + articleEntries.size()); uploadArticlesToTopicAPI(articleEntries); } } private void uploadArticlesToTopicAPI(List<ArticleEntry> articleEntries) { articleEntries.forEach( this::uploadArticleToTopicAPI ); } private void uploadArticleToTopicAPI(ArticleEntry x) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); try { String body = "[" + gson.toJson(x) + "]"; System.out.println("Sending body for id: " + x.getId()); HttpResponse<JsonNode> response = Unirest.post("https://dmitrykey-insiderapi-v1.p.mashape.com/articles/uploadJson") .header("X-Mashape-Key", mashapeKey) .header("Content-Type", "application/json") .header("Accept", "application/json") .body(body) .asJson(); System.out.println("TopicAPI response:" + response.getBody().toString()); } catch (UnirestException e) { log.error("Error: {}", e); System.err.println("Error: " + e.getMessage()); } } }
apache-2.0
graphhopper/graphhopper
core/src/main/java/com/graphhopper/routing/lm/LandmarkSuggestion.java
2814
package com.graphhopper.routing.lm; import com.graphhopper.routing.util.EdgeFilter; import com.graphhopper.storage.index.LocationIndex; import com.graphhopper.storage.index.Snap; import com.graphhopper.util.Helper; import com.graphhopper.util.shapes.BBox; import com.graphhopper.util.shapes.GHPoint; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * This class collects landmarks from an external source for one subnetwork to avoid the expensive and sometimes * suboptimal automatic landmark finding process. */ public class LandmarkSuggestion { private final List<Integer> nodeIds; private final BBox box; public LandmarkSuggestion(List<Integer> nodeIds, BBox box) { this.nodeIds = nodeIds; this.box = box; } public List<Integer> getNodeIds() { return nodeIds; } public BBox getBox() { return box; } /** * The expected format is lon,lat per line where lines starting with characters will be ignored. You can create * such a file manually via geojson.io -> Save as CSV. Optionally add a second line with * <pre>#BBOX:minLat,minLon,maxLat,maxLon</pre> * <p> * to specify an explicit bounding box. TODO: support GeoJSON instead. */ public static LandmarkSuggestion readLandmarks(String file, LocationIndex locationIndex) throws IOException { // landmarks should be suited for all vehicles EdgeFilter edgeFilter = EdgeFilter.ALL_EDGES; List<String> lines = Helper.readFile(file); List<Integer> landmarkNodeIds = new ArrayList<>(); BBox bbox = BBox.createInverse(false); int lmSuggestionIdx = 0; String errors = ""; for (String lmStr : lines) { if (lmStr.startsWith("#BBOX:")) { bbox = BBox.parseTwoPoints(lmStr.substring("#BBOX:".length())); continue; } else if (lmStr.isEmpty() || Character.isAlphabetic(lmStr.charAt(0))) { continue; } GHPoint point = GHPoint.fromStringLonLat(lmStr); if (point == null) throw new RuntimeException("Invalid format " + lmStr + " for point " + lmSuggestionIdx); lmSuggestionIdx++; Snap result = locationIndex.findClosest(point.lat, point.lon, edgeFilter); if (!result.isValid()) { errors += "Cannot find close node found for landmark suggestion[" + lmSuggestionIdx + "]=" + point + ".\n"; continue; } bbox.update(point.lat, point.lon); landmarkNodeIds.add(result.getClosestNode()); } if (!errors.isEmpty()) throw new RuntimeException(errors); return new LandmarkSuggestion(landmarkNodeIds, bbox); } }
apache-2.0
griffon-plugins/griffon-jpa-plugin
subprojects/griffon-jpa-core/src/main/java/org/codehaus/griffon/runtime/jpa/JpaModule.java
2262
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2014-2020 The author and/or original authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.griffon.runtime.jpa; import griffon.core.Configuration; import griffon.core.addon.GriffonAddon; import griffon.core.injection.Module; import griffon.plugins.jpa.JpaSettingsFactory; import griffon.plugins.jpa.EntityManagerHandler; import griffon.plugins.jpa.JpaSettingsStorage; import org.codehaus.griffon.runtime.core.injection.AbstractModule; import org.codehaus.griffon.runtime.util.ResourceBundleProvider; import org.kordamp.jipsy.ServiceProviderFor; import javax.inject.Named; import java.util.ResourceBundle; import static griffon.util.AnnotationUtils.named; /** * @author Andres Almiray */ @Named("jpa") @ServiceProviderFor(Module.class) public class JpaModule extends AbstractModule { @Override protected void doConfigure() { // tag::bindings[] bind(ResourceBundle.class) .withClassifier(named("jpa")) .toProvider(new ResourceBundleProvider("Jpa")) .asSingleton(); bind(Configuration.class) .withClassifier(named("jpa")) .to(DefaultJpaConfiguration.class) .asSingleton(); bind(JpaSettingsStorage.class) .to(DefaultJpaSettingsStorage.class) .asSingleton(); bind(JpaSettingsFactory.class) .to(DefaultJpaSettingsFactory.class) .asSingleton(); bind(EntityManagerHandler.class) .to(DefaultEntityManagerHandler.class) .asSingleton(); bind(GriffonAddon.class) .to(JpaAddon.class) .asSingleton(); // end::bindings[] } }
apache-2.0
YeDaxia/SqliteLookup
src/com/darcye/sqlitelookup/app/DbTablesActivity.java
4203
package com.darcye.sqlitelookup.app; import java.io.File; import java.util.List; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.darcye.sqlite.DaoFactory; import com.darcye.sqlite.DbSqlite; import com.darcye.sqlite.IBaseDao; import com.darcye.sqlitelookup.R; import com.darcye.sqlitelookup.adapter.SimpleListAdapter; import com.darcye.sqlitelookup.dialog.SelectorDialog; import com.darcye.sqlitelookup.dialog.SelectorDialog.OnItemSelectedListener; import com.darcye.sqlitelookup.model.SqliteMaster; /** * show tables of db * @author Darcy * */ public class DbTablesActivity extends BaseActivity implements OnItemSelectedListener{ public static final String EXTRA_DB_PATH = "db-path"; private static final String[] SELECT_ITEMS = {"Table Design","Table Data"}; private RecyclerView mRvTableList; private TableListAdapter mTableListAdapter; private SelectorDialog mDlgSelect; private String mSelectTable; private String mDbPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_db_tables); mRvTableList = findView(R.id.list_db_tables); mRvTableList.setLayoutManager(new LinearLayoutManager(this)); mDbPath = getIntent().getStringExtra(EXTRA_DB_PATH); mDlgSelect = new SelectorDialog(this); mDlgSelect.setSelectItems(SELECT_ITEMS, this); enableBack(); File dbFile = new File(mDbPath); setMainTitle(String.format("Tables In %s", dbFile.getName())); listTables(); } @Override public void onSelected(int position) { if(position == 0){ selectTableDesign(mSelectTable); }else{ selectTableData(mSelectTable); } } private void selectTableDesign(String tableName){ Intent designIntent = new Intent(this,TableDesignActivity.class); designIntent.putExtra(TableDesignActivity.EXTRA_DB_PATH, mDbPath); designIntent.putExtra(TableDesignActivity.EXTRA_TABLE_NAME, tableName); startActivity(designIntent); } private void selectTableData(String tableName){ Intent dataIntent = new Intent(this,TableDataActivity.class); dataIntent.putExtra(TableDataActivity.EXTRA_DB_PATH, mDbPath); dataIntent.putExtra(TableDataActivity.EXTRA_TABLE_NAME, tableName); startActivity(dataIntent); } private void listTables(){ new GetDbTablesTask().execute(); } class GetDbTablesTask extends AsyncTask<Void, Void, List<SqliteMaster>>{ @Override protected List<SqliteMaster> doInBackground(Void... params) { SQLiteDatabase db = SQLiteDatabase.openDatabase(mDbPath, null, SQLiteDatabase.OPEN_READONLY); DbSqlite dbSqlite = new DbSqlite(null, db); IBaseDao<SqliteMaster> masterDao = DaoFactory.createGenericDao(dbSqlite, SqliteMaster.class); List<SqliteMaster> tables = masterDao.query(new String[]{"name"}, "type=?", new String[]{"table"}, null); dbSqlite.closeDB(); return tables; } @Override protected void onPostExecute(List<SqliteMaster> result) { super.onPostExecute(result); mTableListAdapter = new TableListAdapter(DbTablesActivity.this, result); mRvTableList.setAdapter(mTableListAdapter); } } class TableListAdapter extends SimpleListAdapter<SqliteMaster>{ private List<SqliteMaster> data; public TableListAdapter(Context context, List<SqliteMaster> data) { super(context, data); this.data = data; } @Override public void onBindViewHolder(SimpleItemViewHodler viewHolder, int position) { final SqliteMaster table = data.get(position); viewHolder.ivIcon.setImageResource(R.drawable.ic_table); viewHolder.tvText.setText(table.name); viewHolder.itemView.setOnLongClickListener((new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { mSelectTable = table.name; mDlgSelect.show(); return true; } })); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { selectTableDesign(table.name); } }); } } }
apache-2.0
static-void/gcalsync2-0
src/com/gcalsync/cal/phonecal/PhoneCalClient.java
13430
/* Copyright 2007 batcage@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * * Changes: * --/nov/2007 Agustin * -getGCalId: now it uses the phoneCalId * -setBoolean: added * dec/2007 Agustin * -insertEvent, updateEvent: ignores events which RepeatRule is not supported by the phone */ package com.gcalsync.cal.phonecal; import com.gcalsync.cal.IdCorrelation; import com.gcalsync.cal.Recurrence; import com.gcalsync.store.Store; import com.gcalsync.log.*; import javax.microedition.pim.Event; import javax.microedition.pim.EventList; import javax.microedition.pim.PIM; import javax.microedition.pim.PIMException; import java.util.Enumeration; import java.util.Hashtable; import javax.microedition.pim.RepeatRule; /** * @author Thomas Oldervoll, thomas@zenior.no * @author $Author: batcage $ * @version $Rev: 32 $ * @date $Date: 2006-12-26 23:43:46 -0500 (Tue, 26 Dec 2006) $ */ public class PhoneCalClient { public int createdCount = 0; public int updatedCount = 0; public int removedCount = 0; private EventList phoneEventList; private static int[][] supportedRecurrenceFields = null; public PhoneCalClient() { if (phoneEventList == null) { try { PIM pim = PIM.getInstance(); phoneEventList = (EventList) pim.openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); } catch (Exception e) {} } } private PhoneCalClient(EventList phoneEventList) { this.phoneEventList = phoneEventList; } /** * Creates a new PhoneCalClient for the specified list of events. * @param listName Name of a list, or null for no list * @return A PhoneCalClient for the specifed list, or null if the * list does not exist */ public static PhoneCalClient createPhoneCalClient(String listName, boolean write) { try { PIM pim = PIM.getInstance(); if(listName == null) { EventList phoneEventList = (EventList) pim.openPIMList(PIM.EVENT_LIST, write ? PIM.READ_WRITE : PIM.READ_ONLY); return new PhoneCalClient(phoneEventList); } String[] ss = pim.listPIMLists(PIM.EVENT_LIST); boolean found = false; for(int i = 0; i < ss.length && !found; i++) { if(ss[i].equalsIgnoreCase(listName)) { found = true; } } if(!found) { return null; } EventList phoneEventList = (EventList) pim.openPIMList(PIM.EVENT_LIST, write ? PIM.READ_WRITE : PIM.READ_ONLY, listName); return new PhoneCalClient(phoneEventList); }catch(Exception e) { return null; } } public void close() { try { phoneEventList.close(); } catch (PIMException e) { ErrorHandler.showError("Failed to close phone calendar, events may not have been saved", e); } } public Enumeration getPhoneEvents(long startDate, long endDate) throws PIMException { return getPhoneEventList().items(EventList.OCCURRING, startDate, endDate, false); } private EventList getPhoneEventList() throws PIMException { if (phoneEventList == null) { PIM pim = PIM.getInstance(); phoneEventList = (EventList) pim.openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); } return phoneEventList; } public String getStringField(Event phoneEvent, int field) { try { if (phoneEvent.getPIMList().isSupportedField(field) && (phoneEvent.countValues(field) > 0)) { return phoneEvent.getString(field, 0); } else { // TODO: log all unsupported fields, but only once return null; } }catch(Exception e) { return null; } } public void setStringField(Event phoneEvent, int field, String value) { if (phoneEvent.getPIMList().isSupportedField(field)) { if (phoneEvent.countValues(field) == 0) { phoneEvent.addString(field, Event.ATTR_NONE, value); } else { phoneEvent.setString(field, 0, Event.ATTR_NONE, value); } } // TODO: log all unsupported fields, but only once } public long getDateField(Event phoneEvent, int field) { if (phoneEvent.getPIMList().isSupportedField(field) && (phoneEvent.countValues(field) > 0)) { return phoneEvent.getDate(field, 0); } else { // TODO: log all unsupported fields, but only once return 0; } } public void setDateField(Event phoneEvent, int field, long value) { if (phoneEvent.getPIMList().isSupportedField(field)) { if (phoneEvent.countValues(field) == 0) { phoneEvent.addDate(field, Event.ATTR_NONE, value); } else { phoneEvent.setDate(field, 0, Event.ATTR_NONE, value); } } // TODO: log all unsupported fields, but only once } public int getIntField(Event phoneEvent, int field) { try { if (phoneEvent.getPIMList().isSupportedField(field) && (phoneEvent.countValues(field) > 0)) { return phoneEvent.getInt(field, 0); } else { // TODO: log all unsupported fields, but only once return -1; } }catch(Exception e) { return -1; } } public void setIntField(Event phoneEvent, int field, int value) { if (phoneEvent.getPIMList().isSupportedField(field)) { if (phoneEvent.countValues(field) == 0) { phoneEvent.addInt(field, Event.ATTR_NONE, value); } else { phoneEvent.setInt(field, 0, Event.ATTR_NONE, value); } } // TODO: log all unsupported fields, but only once } /** * Gets the value of a boolean field * @param phoneEvent The phone event to use * @param field The field to get the value for * @return 0=false 1=true -1=fild unsuported */ public int getBooleanField(Event phoneEvent, int field) { if (phoneEvent.getPIMList().isSupportedField(field)) { if(phoneEvent.countValues(field) > 0) { return phoneEvent.getBoolean(field, 0) == true ? 1 : 0; } else { return 0; } } else { // TODO: log all unsupported fields, but only once return -1; } } /** * Sets the value of a boolean field * @param phoneEvent The Event onto which set the value * @param field The field to set * @param value The boolean value to set * @return True if the field is supported, false otherwise */ public boolean setBooleanField(Event phoneEvent, int field, boolean value) { if (phoneEvent.getPIMList().isSupportedField(field)) { if (phoneEvent.countValues(field) == 0) { phoneEvent.addBoolean(field, Event.ATTR_NONE, value); } else { phoneEvent.setBoolean(field, 0, Event.ATTR_NONE, value); } return true; } else { return false; } } public String getPhoneId(Event phoneEvent) { int idField = findIdField(); String phoneId = phoneEvent.getString(idField, 0); return phoneId; } public String getGCalId(Event phoneEvent) { String phoneId = getPhoneId(phoneEvent); String gcalId = (String) Store.getIdCorrelator().phoneIdToGcalId.get(phoneId); //#ifdef DEBUG_INFO //# System.out.println("Read " + phoneId + " -> " + gcalId); //#endif return gcalId; } public void setGCalId(Event phoneEvent, String gCalId) { int idField = findIdField(); IdCorrelation idCorrelation = new IdCorrelation(); idCorrelation.phoneCalId = phoneEvent.getString(idField, 0); idCorrelation.gCalId = gCalId; //#ifdef DEBUG_INFO //# System.out.println("Storing " + idCorrelation.phoneCalId + " -> " + idCorrelation.gCalId); //#endif Store.addCorrelation(idCorrelation); } private int findIdField() { if (phoneEventList.isSupportedField(Event.UID)) { return Event.UID; } else if (phoneEventList.isSupportedField(Event.LOCATION)) { return Event.LOCATION; } else if (phoneEventList.isSupportedField(Event.NOTE)) { return Event.NOTE; } else { throw new IllegalStateException("Cannot store ID, neither UID, LOCATION nor NOTE is supported"); } } public Event createEvent() { return phoneEventList.createEvent(); } public boolean insertEvent(Event phoneEvent, String gCalId) throws PIMException { boolean success; try { Hashtable correctRR = Recurrence.getRepeatRuleInfo(phoneEvent.getRepeat()); phoneEvent.commit(); RepeatRule phoneRR = phoneEvent.getRepeat(); if(!Recurrence.repeatRuleEquals(phoneRR, correctRR)) { ((EventList)phoneEvent.getPIMList()).removeEvent(phoneEvent); success = false; } else { setGCalId(phoneEvent, gCalId); createdCount++; success = true; } } catch (Exception e) { success = false; e.printStackTrace(); } return success; } public boolean updateEvent(Event phoneEvent) throws PIMException { boolean success; try { Hashtable correctRR = Recurrence.getRepeatRuleInfo(phoneEvent.getRepeat()); phoneEvent.commit(); RepeatRule phoneRR = phoneEvent.getRepeat(); //check if the phone supports the repeat rule (if set) if(!Recurrence.repeatRuleEquals(phoneRR, correctRR)) { ((EventList)phoneEvent.getPIMList()).removeEvent(phoneEvent); success = false; } else { updatedCount++; success = true; } } catch (Exception e) { success = false; } return success; } public boolean removeEvent(Event event) throws PIMException { boolean success; try { phoneEventList.removeEvent(event); try {event.commit();} catch (Exception e) {} removedCount++; success = true; } catch (Exception e) { success = false; } return success; } public void removeDownloadedEvents() { try { EventList phoneEventList = getPhoneEventList(); Hashtable phoneIdToGcalId = Store.getIdCorrelator().phoneIdToGcalId; Enumeration allPhoneEventsEnum = phoneEventList.items(); int idField = findIdField(); while (allPhoneEventsEnum.hasMoreElements()) { Event phoneEvent = (Event) allPhoneEventsEnum.nextElement(); String phoneId = phoneEvent.getString(idField, 0); if (phoneIdToGcalId.get(phoneId) != null) { removeEvent(phoneEvent); } } } catch (PIMException e) { ErrorHandler.showError("Failed to delete downloaded events", e); } } private boolean shouldDownload() throws Exception { try { return Store.getOptions().download; }catch(Exception e) { throw new GCalException(this.getClass(), "shouldDownload", e); } } public static int[][] getSupportedRecurrenceFields() { if(supportedRecurrenceFields == null) { try { PIM pim = PIM.getInstance(); EventList phoneEventList = (EventList) pim.openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE); supportedRecurrenceFields = new int[4][]; supportedRecurrenceFields[0] = phoneEventList.getSupportedRepeatRuleFields(RepeatRule.DAILY); supportedRecurrenceFields[1] = phoneEventList.getSupportedRepeatRuleFields(RepeatRule.WEEKLY); supportedRecurrenceFields[2] = phoneEventList.getSupportedRepeatRuleFields(RepeatRule.MONTHLY); supportedRecurrenceFields[3] = phoneEventList.getSupportedRepeatRuleFields(RepeatRule.YEARLY); } catch (Exception e) {} } return supportedRecurrenceFields; } }
apache-2.0
SeaCloudsEU/SoftCare-Case-Study
softcare-ws/src/main/java/eu/ehealth/db/DbConstants.java
1121
package eu.ehealth.db; import eu.ehealth.SystemDictionary; /** * * @author a572832 * */ public class DbConstants { // DIGEST ALGORITHMS: [MD2, MD5, SHA, SHA-256, SHA-384, SHA-512] // PBE ALGORITHMS: [PBEWITHMD5ANDDES, PBEWITHMD5ANDTRIPLEDES, PBEWITHSHA1ANDDESEDE, PBEWITHSHA1ANDRC2_40] protected static final String passwordJasyptHibernateDB = "jasypt"; protected static final String algorithmJasyptHibernateDB = "PBEWithMD5AndTripleDES"; protected static final String registerNameJasyptHibernateDB = "strongHibernateStringEncryptor"; protected static final String passwordHibernateCfg = "jasypt"; protected static final String algorithmHibernateCfg = "PBEWITHSHA1ANDDESEDE"; protected static int poolSizePsswdStoredJasyptHibernateDB = 4; protected static final String algorithmPsswdStoredJasyptHibernateDB = "SHA-1"; protected static final int iterationsPsswdStoredJasyptHibernateDB = 100; static { try { poolSizePsswdStoredJasyptHibernateDB = Runtime.getRuntime().availableProcessors(); } catch (Exception ex) { SystemDictionary.logException(ex); } } }
apache-2.0
duchengzhen/Android-WheelDateTimePicker
WheelDateTimePicker_library/src/main/java/calv1n/datetime/dependency/Lunar.java
25077
package calv1n.datetime.dependency; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 农历工具类 * Created by duchengzhen on 2014/7/22. */ public class Lunar { public static void main(String[] args) { Lunar l = new Lunar(System.currentTimeMillis()); System.out.println("节气:" + l.getTermString()); System.out.println("干支历:" + l.getCyclicalDateString()); System.out.println("星期" + l.getDayOfWeek()); System.out.println("农历" + l.getLunarDateString()); } private final static int[] lunarInfo = { 0x4bd8, 0x4ae0, 0xa570, 0x54d5, 0xd260, 0xd950, 0x5554, 0x56af, 0x9ad0, 0x55d2, 0x4ae0, 0xa5b6, 0xa4d0, 0xd250, 0xd295, 0xb54f, 0xd6a0, 0xada2, 0x95b0, 0x4977, 0x497f, 0xa4b0, 0xb4b5, 0x6a50, 0x6d40, 0xab54, 0x2b6f, 0x9570, 0x52f2, 0x4970, 0x6566, 0xd4a0, 0xea50, 0x6a95, 0x5adf, 0x2b60, 0x86e3, 0x92ef, 0xc8d7, 0xc95f, 0xd4a0, 0xd8a6, 0xb55f, 0x56a0, 0xa5b4, 0x25df, 0x92d0, 0xd2b2, 0xa950, 0xb557, 0x6ca0, 0xb550, 0x5355, 0x4daf, 0xa5b0, 0x4573, 0x52bf, 0xa9a8, 0xe950, 0x6aa0, 0xaea6, 0xab50, 0x4b60, 0xaae4, 0xa570, 0x5260, 0xf263, 0xd950, 0x5b57, 0x56a0, 0x96d0, 0x4dd5, 0x4ad0, 0xa4d0, 0xd4d4, 0xd250, 0xd558, 0xb540, 0xb6a0, 0x95a6, 0x95bf, 0x49b0, 0xa974, 0xa4b0, 0xb27a, 0x6a50, 0x6d40, 0xaf46, 0xab60, 0x9570, 0x4af5, 0x4970, 0x64b0, 0x74a3, 0xea50, 0x6b58, 0x5ac0, 0xab60, 0x96d5, 0x92e0, 0xc960, 0xd954, 0xd4a0, 0xda50, 0x7552, 0x56a0, 0xabb7, 0x25d0, 0x92d0, 0xcab5, 0xa950, 0xb4a0, 0xbaa4, 0xad50, 0x55d9, 0x4ba0, 0xa5b0, 0x5176, 0x52bf, 0xa930, 0x7954, 0x6aa0, 0xad50, 0x5b52, 0x4b60, 0xa6e6, 0xa4e0, 0xd260, 0xea65, 0xd530, 0x5aa0, 0x76a3, 0x96d0, 0x4afb, 0x4ad0, 0xa4d0, 0xd0b6, 0xd25f, 0xd520, 0xdd45, 0xb5a0, 0x56d0, 0x55b2, 0x49b0, 0xa577, 0xa4b0, 0xaa50, 0xb255, 0x6d2f, 0xada0, 0x4b63, 0x937f, 0x49f8, 0x4970, 0x64b0, 0x68a6, 0xea5f, 0x6b20, 0xa6c4, 0xaaef, 0x92e0, 0xd2e3, 0xc960, 0xd557, 0xd4a0, 0xda50, 0x5d55, 0x56a0, 0xa6d0, 0x55d4, 0x52d0, 0xa9b8, 0xa950, 0xb4a0, 0xb6a6, 0xad50, 0x55a0, 0xaba4, 0xa5b0, 0x52b0, 0xb273, 0x6930, 0x7337, 0x6aa0, 0xad50, 0x4b55, 0x4b6f, 0xa570, 0x54e4, 0xd260, 0xe968, 0xd520, 0xdaa0, 0x6aa6, 0x56df, 0x4ae0, 0xa9d4, 0xa4d0, 0xd150, 0xf252, 0xd520 }; private final static int[] solarTermInfo = { 0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072, 240693, 263343, 285989, 308563, 331033, 353350, 375494, 397447, 419210, 440795, 462224, 483532, 504758 }; public final static String[] Tianan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" }; public final static String[] Deqi = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" }; public final static String[] Animals = { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" }; public final static String[] solarTerm = { "小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至" }; public final static String[] lunarNumber = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" }; public final static String[] lunarString2 = { "初", "十", "廿", "卅", "正", "腊", "冬", "闰" }; /** * 国历节日 *表示放假日 */ private final static String[] sFtv = { "0101*元旦", "0214 情人节", "0308 妇女节", "0312 植树节", "0315 消费者权益日", "0401 愚人节", "0501*劳动节", "0504 青年节", "0509 郝维节", "0512 护士节", "0601 儿童节", "0701 建党节 香港回归纪念", "0801 建军节", "0808 父亲节", "0816 燕衔泥节", "0909 毛泽东逝世纪念", "0910 教师节", "0928 孔子诞辰", "1001*国庆节", "1006 老人节", "1024 联合国日", "1111 光棍节", "1112 孙中山诞辰纪念", "1220 澳门回归纪念", "1225 圣诞节", "1226 毛泽东诞辰纪念" }; /** * 农历节日 *表示放假日 */ private final static String[] lFtv = { "0101*春节、弥勒佛诞", "0106 定光佛诞", "0115 元宵节", "0208 释迦牟尼佛出家", "0215 释迦牟尼佛涅槃", "0209 海空上师诞", "0219 观世音菩萨诞", "0221 普贤菩萨诞", "0316 准提菩萨诞", "0404 文殊菩萨诞", "0408 释迦牟尼佛诞", "0415 佛吉祥日——释迦牟尼佛诞生、成道、涅槃三期同一庆(即南传佛教国家的卫塞节)", "0505 端午节", "0513 伽蓝菩萨诞", "0603 护法韦驮尊天菩萨诞", "0619 观世音菩萨成道——此日放生、念佛,功德殊胜", "0707 七夕情人节", "0713 大势至菩萨诞", "0715 中元节", "0724 龙树菩萨诞", "0730 地藏菩萨诞", "0815 中秋节", "0822 燃灯佛诞", "0909 重阳节", "0919 观世音菩萨出家纪念日", "0930 药师琉璃光如来诞", "1005 达摩祖师诞", "1107 阿弥陀佛诞", "1208 释迦如来成道日,腊八节", "1224 小年", "1229 华严菩萨诞", "0100*除夕" }; /** * 某月的第几个星期几 */ private static String[] wFtv = { "0520 母亲节", "0716 合作节", "0730 被奴役国家周" }; private static int toInt(String str) { try { return Integer.parseInt(str); } catch (Exception e) { return -1; } } private final static Pattern sFreg = Pattern.compile("^(\\d{2})(\\d{2})([\\s\\*])(.+)$"); private final static Pattern wFreg = Pattern.compile("^(\\d{2})(\\d)(\\d)([\\s\\*])(.+)$"); private synchronized void findFestival() { int sM = this.getSolarMonth(); int sD = this.getSolarDay(); int lM = this.getLunarMonth(); int lD = this.getLunarDay(); int sy = this.getSolarYear(); Matcher m; for (int i = 0; i < Lunar.sFtv.length; i++) { m = Lunar.sFreg.matcher(Lunar.sFtv[i]); if (m.find()) { if (sM == Lunar.toInt(m.group(1)) && sD == Lunar.toInt(m.group(2))) { this.isSFestival = true; this.sFestivalName = m.group(4); if ("*".equals(m.group(3))) this.isHoliday = true; break; } } } for (int i = 0; i < Lunar.lFtv.length; i++) { m = Lunar.sFreg.matcher(Lunar.lFtv[i]); if (m.find()) { if (lM == Lunar.toInt(m.group(1)) && lD == Lunar.toInt(m.group(2))) { this.isLFestival = true; this.lFestivalName = m.group(4); if ("*".equals(m.group(3))) this.isHoliday = true; break; } } } // 月周节日 int w, d; for (int i = 0; i < Lunar.wFtv.length; i++) { m = Lunar.wFreg.matcher(Lunar.wFtv[i]); if (m.find()) { if (this.getSolarMonth() == Lunar.toInt(m.group(1))) { w = Lunar.toInt(m.group(2)); d = Lunar.toInt(m.group(3)); if (this.solar.get(Calendar.WEEK_OF_MONTH) == w && this.solar.get(Calendar.DAY_OF_WEEK) == d) { this.isSFestival = true; this.sFestivalName += "|" + m.group(5); if ("*".equals(m.group(4))) this.isHoliday = true; } } } } if (sy > 1874 && sy < 1909) this.description = "光绪" + (((sy - 1874) == 1) ? "元" : "" + (sy - 1874)); if (sy > 1908 && sy < 1912) this.description = "宣统" + (((sy - 1908) == 1) ? "元" : String.valueOf(sy - 1908)); if (sy > 1911 && sy < 1950) this.description = "民国" + (((sy - 1911) == 1) ? "元" : String.valueOf(sy - 1911)); if (sy > 1949) this.description = "共和国" + (((sy - 1949) == 1) ? "元" : String.valueOf(sy - 1949)); this.description += "年"; this.sFestivalName = this.sFestivalName.replaceFirst("^\\|", ""); this.isFinded = true; } private boolean isFinded = false; private boolean isSFestival = false; private boolean isLFestival = false; private String sFestivalName = ""; private String lFestivalName = ""; private String description = ""; private boolean isHoliday = false; private Calendar solar; private int lunarYear; private int lunarMonth; private int lunarDay; private boolean isLeap; private boolean isLeapYear; private int solarYear; private int solarMonth; private int solarDay; private int cyclicalYear = 0; private int cyclicalMonth = 0; private int cyclicalDay = 0; private int maxDayInMonth = 29; /** * 返回农历年闰月月份 * * @param lunarYear 指定农历年份(数字) * @return 该农历年闰月的月份(数字, 没闰返回0) */ private static int getLunarLeapMonth(int lunarYear) { // 数据表中,每个农历年用16bit来表示, // 前12bit分别表示12个月份的大小月,最后4bit表示闰月 // 若4bit全为1或全为0,表示没闰, 否则4bit的值为闰月月份 int leapMonth = Lunar.lunarInfo[lunarYear - 1900] & 0xf; leapMonth = (leapMonth == 0xf ? 0 : leapMonth); return leapMonth; } /** * 返回农历年闰月的天数 * * @param lunarYear 指定农历年份(数字) * @return 该农历年闰月的天数(数字) */ private static int getLunarLeapDays(int lunarYear) { // 下一年最后4bit为1111,返回30(大月) // 下一年最后4bit不为1111,返回29(小月) // 若该年没有闰月,返回0 return Lunar.getLunarLeapMonth(lunarYear) > 0 ? ((Lunar.lunarInfo[lunarYear - 1899] & 0xf) == 0xf ? 30 : 29) : 0; } /** * 返回农历年的总天数 * * @param lunarYear 指定农历年份(数字) * @return 该农历年的总天数(数字) */ private static int getLunarYearDays(int lunarYear) { // 按小月计算,农历年最少有12 * 29 = 348天 int daysInLunarYear = 348; // 数据表中,每个农历年用16bit来表示, // 前12bit分别表示12个月份的大小月,最后4bit表示闰月 // 每个大月累加一天 for (int i = 0x8000; i > 0x8; i >>= 1) { daysInLunarYear += ((Lunar.lunarInfo[lunarYear - 1900] & i) != 0) ? 1 : 0; } // 加上闰月天数 daysInLunarYear += Lunar.getLunarLeapDays(lunarYear); return daysInLunarYear; } /** * 返回农历年正常月份的总天数 * * @param lunarYear 指定农历年份(数字) * @param lunarMonth 指定农历月份(数字) * @return 该农历年闰月的月份(数字, 没闰返回0) */ private static int getLunarMonthDays(int lunarYear, int lunarMonth) { // 数据表中,每个农历年用16bit来表示, // 前12bit分别表示12个月份的大小月,最后4bit表示闰月 return ((Lunar.lunarInfo[lunarYear - 1900] & (0x10000 >> lunarMonth)) != 0) ? 30 : 29; } /** * 取 Date 对象中用全球标准时间 (UTC) 表示的日期 * * @param date 指定日期 * @return UTC 全球标准时间 (UTC) 表示的日期 */ public static synchronized int getUTCDay(Date date) { Lunar.makeUTCCalendar(); synchronized (utcCal) { utcCal.clear(); utcCal.setTimeInMillis(date.getTime()); return utcCal.get(Calendar.DAY_OF_MONTH); } } private static GregorianCalendar utcCal = null; private static synchronized void makeUTCCalendar() { if (Lunar.utcCal == null) { Lunar.utcCal = new GregorianCalendar(TimeZone.getTimeZone("UTC")); } } /** * 返回全球标准时间 (UTC) (或 GMT) 的 1970 年 1 月 1 日到所指定日期之间所间隔的毫秒数。 * * @param y 指定年份 * @param m 指定月份 * @param d 指定日期 * @param h 指定小时 * @param min 指定分钟 * @param sec 指定秒数 * @return 全球标准时间 (UTC) (或 GMT) 的 1970 年 1 月 1 日到所指定日期之间所间隔的毫秒数 */ public static synchronized long UTC(int y, int m, int d, int h, int min, int sec) { Lunar.makeUTCCalendar(); synchronized (utcCal) { utcCal.clear(); utcCal.set(y, m, d, h, min, sec); return utcCal.getTimeInMillis(); } } /** * 返回公历年节气的日期 * * @param solarYear 指定公历年份(数字) * @param index 指定节气序号(数字,0从小寒算起) * @return 日期(数字, 所在月份的第几天) */ private static int getSolarTermDay(int solarYear, int index) { long l = (long) 31556925974.7 * (solarYear - 1900) + solarTermInfo[index] * 60000L; l = l + Lunar.UTC(1900, 0, 6, 2, 5, 0); return Lunar.getUTCDay(new Date(l)); } /** * 通过 Date 对象构建农历信息 * * @param date 指定日期对象 */ public Lunar(Date date) { if (date == null) date = new Date(); this.init(date.getTime()); } /** * 通过 TimeInMillis 构建农历信息 * * @param TimeInMillis */ public Lunar(long TimeInMillis) { this.init(TimeInMillis); } private void init(long TimeInMillis) { this.solar = Calendar.getInstance(); this.solar.setTimeInMillis(TimeInMillis); Calendar baseDate = new GregorianCalendar(1900, 0, 31); long offset = (TimeInMillis - baseDate.getTimeInMillis()) / 86400000; // 按农历年递减每年的农历天数,确定农历年份 this.lunarYear = 1900; int daysInLunarYear = Lunar.getLunarYearDays(this.lunarYear); while (this.lunarYear < 2100 && offset >= daysInLunarYear) { offset -= daysInLunarYear; daysInLunarYear = Lunar.getLunarYearDays(++this.lunarYear); } // 农历年数字 // 按农历月递减每月的农历天数,确定农历月份 int lunarMonth = 1; // 所在农历年闰哪个月,若没有返回0 int leapMonth = Lunar.getLunarLeapMonth(this.lunarYear); // 是否闰年 this.isLeapYear = leapMonth > 0; // 闰月是否递减 boolean leapDec = false; boolean isLeap = false; int daysInLunarMonth = 0; while (lunarMonth < 13 && offset > 0) { if (isLeap && leapDec) { // 如果是闰年,并且是闰月 // 所在农历年闰月的天数 daysInLunarMonth = Lunar.getLunarLeapDays(this.lunarYear); leapDec = false; } else { // 所在农历年指定月的天数 daysInLunarMonth = Lunar.getLunarMonthDays(this.lunarYear, lunarMonth); } if (offset < daysInLunarMonth) { break; } offset -= daysInLunarMonth; if (leapMonth == lunarMonth && !isLeap) { // 下个月是闰月 leapDec = true; isLeap = true; } else { // 月份递增 lunarMonth++; } } this.maxDayInMonth = daysInLunarMonth; // 农历月数字 this.lunarMonth = lunarMonth; // 是否闰月 this.isLeap = (lunarMonth == leapMonth && isLeap); // 农历日数字 this.lunarDay = (int) offset + 1; // 取得干支历 this.getCyclicalData(); } /** * 取干支历 不是历年,历月干支,而是中国的从立春节气开始的节月,是中国的太阳十二宫,阳历的。 */ private void getCyclicalData() { this.solarYear = this.solar.get(Calendar.YEAR); this.solarMonth = this.solar.get(Calendar.MONTH); this.solarDay = this.solar.get(Calendar.DAY_OF_MONTH); // 干支历 int cyclicalYear = 0; int cyclicalMonth = 0; int cyclicalDay = 0; // 干支年 1900年立春後为庚子年(60进制36) int term2 = Lunar.getSolarTermDay(solarYear, 2); // 立春日期 // 依节气调整二月分的年柱, 以立春为界 if (solarMonth < 1 || (solarMonth == 1 && solarDay < term2)) { cyclicalYear = (solarYear - 1900 + 36 - 1) % 60; } else { cyclicalYear = (solarYear - 1900 + 36) % 60; } // 干支月 1900年1月小寒以前为 丙子月(60进制12) int firstNode = Lunar.getSolarTermDay(solarYear, solarMonth * 2); // 传回当月「节」为几日开始 // 依节气月柱, 以「节」为界 if (solarDay < firstNode) { cyclicalMonth = ((solarYear - 1900) * 12 + solarMonth + 12) % 60; } else { cyclicalMonth = ((solarYear - 1900) * 12 + solarMonth + 13) % 60; } // 当月一日与 1900/1/1 相差天数 // 1900/1/1与 1970/1/1 相差25567日, 1900/1/1 日柱为甲戌日(60进制10) cyclicalDay = (int) (Lunar.UTC(solarYear, solarMonth, solarDay, 0, 0, 0) / 86400000 + 25567 + 10) % 60; this.cyclicalYear = cyclicalYear; this.cyclicalMonth = cyclicalMonth; this.cyclicalDay = cyclicalDay; } /** * 取农历年生肖 * * @return 农历年生肖(例:龙) */ public String getAnimalString() { return Lunar.Animals[(this.lunarYear - 4) % 12]; } /** * 返回公历日期的节气字符串 * * @return 二十四节气字符串, 若不是节气日, 返回空串(例:冬至) */ public String getTermString() { // 二十四节气 String termString = ""; if (Lunar.getSolarTermDay(solarYear, solarMonth * 2) == solarDay) { termString = Lunar.solarTerm[solarMonth * 2]; } else if (Lunar.getSolarTermDay(solarYear, solarMonth * 2 + 1) == solarDay) { termString = Lunar.solarTerm[solarMonth * 2 + 1]; } return termString; } /** * 取得干支历字符串 * * @return 干支历字符串(例:甲子年甲子月甲子日) */ public String getCyclicalDateString() { return this.getCyclicaYear() + "年" + this.getCyclicaMonth() + "月" + this.getCyclicaDay() + "日"; } /** * 年份天干 * * @return 年份天干 */ public int getTiananY() { return Lunar.getTianan(this.cyclicalYear); } /** * 月份天干 * * @return 月份天干 */ public int getTiananM() { return Lunar.getTianan(this.cyclicalMonth); } /** * 日期天干 * * @return 日期天干 */ public int getTiananD() { return Lunar.getTianan(this.cyclicalDay); } /** * 年份地支 * * @return 年分地支 */ public int getDeqiY() { return Lunar.getDeqi(this.cyclicalYear); } /** * 月份地支 * * @return 月份地支 */ public int getDeqiM() { return Lunar.getDeqi(this.cyclicalMonth); } /** * 日期地支 * * @return 日期地支 */ public int getDeqiD() { return Lunar.getDeqi(this.cyclicalDay); } /** * 取得干支年字符串 * * @return 干支年字符串 */ public String getCyclicaYear() { return Lunar.getCyclicalString(this.cyclicalYear); } /** * 取得干支月字符串 * * @return 干支月字符串 */ public String getCyclicaMonth() { return Lunar.getCyclicalString(this.cyclicalMonth); } /** * 取得干支日字符串 * * @return 干支日字符串 */ public String getCyclicaDay() { return Lunar.getCyclicalString(this.cyclicalDay); } /** * 返回农历日期字符串 * * @return 农历日期字符串 */ public String getLunarDayString() { return Lunar.getLunarDayString(this.lunarDay); } /** * 返回农历日期字符串 * * @return 农历日期字符串 */ public String getLunarMonthString() { return (this.isLeap() ? "闰" : "") + Lunar.getLunarMonthString(this.lunarMonth); } /** * 返回农历日期字符串 * * @return 农历日期字符串 */ public String getLunarYearString() { return Lunar.getLunarYearString(this.lunarYear); } /** * 返回农历表示字符串 * * @return 农历字符串(例:甲子年正月初三) */ public String getLunarDateString() { return this.getLunarYearString() + "年" + this.getLunarMonthString() + "月" + this.getLunarDayString() + "日"; } /** * 农历年是否是闰月 * * @return 农历年是否是闰月 */ public boolean isLeap() { return isLeap; } /** * 农历年是否是闰年 * * @return 农历年是否是闰年 */ public boolean isLeapYear() { return isLeapYear; } /** * 当前农历月是否是大月 * * @return 当前农历月是大月 */ public boolean isBigMonth() { return this.getMaxDayInMonth() > 29; } /** * 当前农历月有多少天 * * @return 当前农历月有多少天 */ public int getMaxDayInMonth() { return this.maxDayInMonth; } /** * 农历日期 * * @return 农历日期 */ public int getLunarDay() { return lunarDay; } /** * 农历月份 * * @return 农历月份 */ public int getLunarMonth() { return lunarMonth; } /** * 农历年份 * * @return 农历年份 */ public int getLunarYear() { return lunarYear; } /** * 公历日期 * * @return 公历日期 */ public int getSolarDay() { return solarDay; } /** * 公历月份 * * @return 公历月份 (不是从0算起) */ public int getSolarMonth() { return solarMonth + 1; } /** * 公历年份 * * @return 公历年份 */ public int getSolarYear() { return solarYear; } /** * 星期几 * * @return 星期几(星期日为:1, 星期六为:7) */ public int getDayOfWeek() { return this.solar.get(Calendar.DAY_OF_WEEK); } /** * 黑色星期五 * * @return 是否黑色星期五 */ public boolean isBlackFriday() { return (this.getSolarDay() == 13 && this.solar.get(Calendar.DAY_OF_WEEK) == 6); } /** * 是否是今日 * * @return 是否是今日 */ public boolean isToday() { Calendar clr = Calendar.getInstance(); return clr.get(Calendar.YEAR) == this.solarYear && clr.get(Calendar.MONTH) == this.solarMonth && clr.get(Calendar.DAY_OF_MONTH) == this.solarDay; } /** * 取得公历节日名称 * * @return 公历节日名称, 如果不是节日返回空串 */ public String getSFestivalName() { return this.sFestivalName; } /** * 取得农历节日名称 * * @return 农历节日名称, 如果不是节日返回空串 */ public String getLFestivalName() { return this.lFestivalName; } /** * 是否是农历节日 * * @return 是否是农历节日 */ public boolean isLFestival() { if (!this.isFinded) this.findFestival(); return this.isLFestival; } /** * 是否是公历节日 * * @return 是否是公历节日 */ public boolean isSFestival() { if (!this.isFinded) this.findFestival(); return this.isSFestival; } /** * 是否是节日 * * @return 是否是节日 */ public boolean isFestival() { return this.isSFestival() || this.isLFestival(); } /** * 是否是放假日 * * @return 是否是放假日 */ public boolean isHoliday() { if (!this.isFinded) this.findFestival(); return this.isHoliday; } /** * 其它日期说明 * * @return 日期说明(如:民国2年) */ public String getDescription() { if (!this.isFinded) this.findFestival(); return this.description; } /** * 干支字符串 * * @param cyclicalNumber 指定干支位置(数字,0为甲子) * @return 干支字符串 */ private static String getCyclicalString(int cyclicalNumber) { return Lunar.Tianan[Lunar.getTianan(cyclicalNumber)] + Lunar.Deqi[Lunar.getDeqi(cyclicalNumber)]; } /** * 获得地支 * * @param cyclicalNumber * @return 地支 (数字) */ private static int getDeqi(int cyclicalNumber) { return cyclicalNumber % 12; } /** * 获得天干 * * @param cyclicalNumber * @return 天干 (数字) */ private static int getTianan(int cyclicalNumber) { return cyclicalNumber % 10; } /** * 返回指定数字的农历年份表示字符串 * * @param lunarYear 农历年份(数字,0为甲子) * @return 农历年份字符串 */ private static String getLunarYearString(int lunarYear) { return Lunar.getCyclicalString(lunarYear - 1900 + 36); } /** * 返回指定数字的农历月份表示字符串 * * @param lunarMonth 农历月份(数字) * @return 农历月份字符串 (例:正) */ private static String getLunarMonthString(int lunarMonth) { String lunarMonthString = ""; if (lunarMonth == 1) { lunarMonthString = Lunar.lunarString2[4]; } else { if (lunarMonth > 9) lunarMonthString += Lunar.lunarString2[1]; if (lunarMonth % 10 > 0) lunarMonthString += Lunar.lunarNumber[lunarMonth % 10]; } return lunarMonthString; } /** * 返回指定数字的农历日表示字符串 * * @param lunarDay 农历日(数字) * @return 农历日字符串 (例: 21对应廿一) */ public static String getLunarDayString(int lunarDay) { if (lunarDay < 1 || lunarDay > 30) return ""; int i1 = lunarDay / 10; int i2 = lunarDay % 10; String c1 = Lunar.lunarString2[i1]; String c2 = Lunar.lunarNumber[i2]; if (lunarDay < 11) c1 = Lunar.lunarString2[0]; if (i2 == 0) c2 = Lunar.lunarString2[1]; return c1 + c2; } public String[] getLunarDays(int daysInLunarMonth) { String[] lunarDays = new String[daysInLunarMonth]; for (int i = 1; i <= daysInLunarMonth; i++) { lunarDays[i] = Lunar.getLunarDayString(i); } return lunarDays; } /** * 将给定的阿拉伯年份(1998)转为汉字显示 * * @param yearNum * @return 如:一九九八年 */ public static String getHansYear(int yearNum) { if (yearNum < 1900) return ""; int year = yearNum / 1000; String str = lunarNumber[year]; year = (yearNum % 1000) / 100; str += lunarNumber[year]; year = ((yearNum % 1000) % 100) / 10; str += lunarNumber[year]; year = ((yearNum % 1000) % 100) % 10; str += lunarNumber[year]; return str + "年"; } /** * 获取当前农历年份 * * @return 例:一九九八年 显示 */ public String getLunarHansYear() { int num = getLunarYear(); int year = num / 1000; String str = lunarNumber[year]; year = (num % 1000) / 100; str += lunarNumber[year]; year = ((num % 1000) % 100) / 10; str += lunarNumber[year]; year = ((num % 1000) % 100) % 10; str += lunarNumber[year]; return str + "年"; } }
apache-2.0
ganjpxm/GAppAs
glib/src/main/java/org/ganjp/glib/core/base/Const.java
1950
/** * Const.java * * Created by Gan Jianping on 07/01/15. * Copyright (c) 2015 Gan Jianping. All rights reserved. */ package org.ganjp.glib.core.base; /** * <p>Global Constant</p> * * @author Gan Jianping * @since 1.0.0 */ public class Const { //------------------------------ Time ----------------------------- public static final int DURATION_SPLASH = 2 * 1000; // 2 seconds public static final int TIMEOUT_CONNECT = 30 * 1000; // 30 seconds public static final int TIMEOUT_SUBMIT_FORM = 20 * 1000; //20 seconds public static final int TIMEOUT_UPLOAD = 2 * 60 * 60000; //2 minitues public static final String DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm:ss"; //------------------------------ File ----------------------------- public static final String IMG_PREFIX = "IMG_"; public static final String IMG_SUFFIX = ".jpg"; public static final String PICTURE_ALBUM = "Pictures"; //----------------------------- Database -------------------------- public static final String COLUMN_LANG = "lang"; public static final String COLUMN_CREATE_TIME = "create_date_time"; public static final String COLUMN_MODIFY_TIMESTAMP = "modify_timestamp"; public static final String COLUMN_DATA_STATE = "data_state"; //----------------------------- Key and value ------------------ public static final String KEY_RESULT = "result"; public static final String VALUE_SUCCESS = "success"; public static final String VALUE_FAIL = "fail"; public static final String VALUE_YES = "yes"; public static final String VALUE_NO = "no"; public static final String VALUE_ACCEPTED = "accepted"; public static final String VALUE_TIMEOUT = "timeout"; //---------------------------------------- Network ---------------------------- public static final String GOOGLE_DOC_VIEW_URL = "https://docs.google.com/gview?embedded=true&url="; }
apache-2.0
termsuite/termsuite-ui
bundles/org.eclipse.e4.ui.progress/src/org/eclipse/e4/ui/progress/internal/ProgressLabelProvider.java
1124
/******************************************************************************* * Copyright (c) 2003, 2015 IBM Corporation and others. * 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.e4.ui.progress.internal; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; /** * The ProgressLabelProvider is a label provider used for viewers * that need anILabelprovider to show JobInfos. */ public class ProgressLabelProvider extends LabelProvider { Image image; @Override public Image getImage(Object element) { return ((JobTreeElement) element).getDisplayImage(); } @Override public String getText(Object element) { return ((JobTreeElement) element).getDisplayString(); } }
apache-2.0
tdj-br/red5-server
src/main/java/org/red5/server/session/SessionManager.java
5765
/* * RED5 Open Source Flash Server - https://github.com/Red5/ * * Copyright (c) 2006-2011 by respective authors (see below). All rights reserved. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later * version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.red5.server.session; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.red5.server.api.scheduling.IScheduledJob; import org.red5.server.api.scheduling.ISchedulingService; import org.red5.server.api.session.ISession; import org.red5.server.util.PropertyConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Manages sessions. * * @author The Red5 Project * @author Paul Gregoire (mondain@gmail.com) */ public class SessionManager { private static final Logger log = LoggerFactory.getLogger(SessionManager.class); private static ConcurrentMap<String, ISession> sessions = new ConcurrentHashMap<String, ISession>(); private static String destinationDirectory; private static Long maxLifetime; private static ISchedulingService schedulingService; // Create a random generator public static final Random rnd = new Random(); public void init() { if (schedulingService != null) { // set to run once per hour schedulingService.addScheduledJob(3600000, new ReaperJob()); } else { log.warn("Session reaper job was not scheduled"); } } public static String getSessionId() { //random int from 1 - 100000 int part1 = rnd.nextInt(99999) + 1; //thread-safe "long" part long part2 = ThreadLocalRandom.current().nextLong(); //current time in millis long part3 = System.currentTimeMillis(); //generate uuid-type id String sessionId = createHash(part1 + "-" + part2 + "-" + part3); log.debug("Session id created: {}", sessionId); return sessionId; } public static ISession createSession() { // create a new session return createSession(getSessionId()); } public static ISession createSession(String sessionId) { // create a new session Session session = new Session(sessionId); session.setDestinationDirectory(destinationDirectory); // add to list sessions.put(sessionId, session); return session; } public static ISession getSession(String sessionId) { return sessions.get(sessionId); } public static ISession removeSession(String sessionId) { return sessions.remove(sessionId); } public String getDestinationDirectory() { return destinationDirectory; } public void setDestinationDirectory(String destinationDir) { log.debug("Setting session destination directory {}", destinationDir); SessionManager.destinationDirectory = destinationDir; } public void setMaxLifetime(String maxLifetime) { if (StringUtils.isNumeric(maxLifetime)) { SessionManager.maxLifetime = Long.valueOf(maxLifetime); } else { SessionManager.maxLifetime = PropertyConverter.convertStringToTimeMillis(maxLifetime); } log.debug("Max lifetime set to {} ms", SessionManager.maxLifetime); } public void setSchedulingService(ISchedulingService schedulingService) { SessionManager.schedulingService = schedulingService; } public static String createHash(String str) { return DigestUtils.md5Hex(str.getBytes()); } /** * Quartz job to kill off old sessions */ private final static class ReaperJob implements IScheduledJob { public ReaperJob() { log.debug("Creating job to remove stale sessions"); } public void execute(ISchedulingService service) { log.debug("Reaper running..."); if (sessions != null) { if (!sessions.isEmpty()) { long now = System.currentTimeMillis(); for (Map.Entry<String, ISession> entry : sessions.entrySet()) { ISession session = entry.getValue(); long creationTime = session.getCreated(); // check if session life exceeds max lifetime if (now - creationTime > SessionManager.maxLifetime) { String key = session.getSessionId(); log.info("Reaper killing stale session: {}", key); sessions.remove(key); session.reset(); session = null; } } } } } } }
apache-2.0
google-code-export/google-api-dfp-java
src/com/google/api/ads/dfp/v201208/ReportErrorReason.java
7151
/** * ReportErrorReason.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201208; public class ReportErrorReason implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected ReportErrorReason(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _DEFAULT = "DEFAULT"; public static final java.lang.String _REPORT_ACCESS_NOT_ALLOWED = "REPORT_ACCESS_NOT_ALLOWED"; public static final java.lang.String _DIMENSION_VIEW_NOT_ALLOWED = "DIMENSION_VIEW_NOT_ALLOWED"; public static final java.lang.String _DIMENSION_COMBINATION_NOT_ALLOWED = "DIMENSION_COMBINATION_NOT_ALLOWED"; public static final java.lang.String _ATTRIBUTE_VIEW_NOT_ALLOWED = "ATTRIBUTE_VIEW_NOT_ALLOWED"; public static final java.lang.String _COLUMN_VIEW_NOT_ALLOWED = "COLUMN_VIEW_NOT_ALLOWED"; public static final java.lang.String _TOO_MANY_CONCURRENT_REPORTS = "TOO_MANY_CONCURRENT_REPORTS"; public static final java.lang.String _REPORT_TOO_BIG = "REPORT_TOO_BIG"; public static final java.lang.String _INVALID_OPERATION_FOR_REPORT_STATE = "INVALID_OPERATION_FOR_REPORT_STATE"; public static final java.lang.String _INVALID_DIMENSIONS = "INVALID_DIMENSIONS"; public static final java.lang.String _INVALID_ATTRIBUTES = "INVALID_ATTRIBUTES"; public static final java.lang.String _INVALID_COLUMNS = "INVALID_COLUMNS"; public static final java.lang.String _INVALID_DIMENSION_FILTERS = "INVALID_DIMENSION_FILTERS"; public static final java.lang.String _INVALID_DATE = "INVALID_DATE"; public static final java.lang.String _END_DATE_TIME_NOT_AFTER_START_TIME = "END_DATE_TIME_NOT_AFTER_START_TIME"; public static final java.lang.String _NOT_NULL = "NOT_NULL"; public static final java.lang.String _ATTRIBUTES_NOT_SUPPORTED_FOR_REQUEST = "ATTRIBUTES_NOT_SUPPORTED_FOR_REQUEST"; public static final java.lang.String _COLUMNS_NOT_SUPPORTED_FOR_REQUESTED_DIMENSIONS = "COLUMNS_NOT_SUPPORTED_FOR_REQUESTED_DIMENSIONS"; public static final java.lang.String _FAILED_TO_STORE_REPORT = "FAILED_TO_STORE_REPORT"; public static final java.lang.String _REPORT_NOT_FOUND = "REPORT_NOT_FOUND"; public static final java.lang.String _SR_CANNOT_RUN_REPORT_IN_ANOTHER_NETWORK = "SR_CANNOT_RUN_REPORT_IN_ANOTHER_NETWORK"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final ReportErrorReason DEFAULT = new ReportErrorReason(_DEFAULT); public static final ReportErrorReason REPORT_ACCESS_NOT_ALLOWED = new ReportErrorReason(_REPORT_ACCESS_NOT_ALLOWED); public static final ReportErrorReason DIMENSION_VIEW_NOT_ALLOWED = new ReportErrorReason(_DIMENSION_VIEW_NOT_ALLOWED); public static final ReportErrorReason DIMENSION_COMBINATION_NOT_ALLOWED = new ReportErrorReason(_DIMENSION_COMBINATION_NOT_ALLOWED); public static final ReportErrorReason ATTRIBUTE_VIEW_NOT_ALLOWED = new ReportErrorReason(_ATTRIBUTE_VIEW_NOT_ALLOWED); public static final ReportErrorReason COLUMN_VIEW_NOT_ALLOWED = new ReportErrorReason(_COLUMN_VIEW_NOT_ALLOWED); public static final ReportErrorReason TOO_MANY_CONCURRENT_REPORTS = new ReportErrorReason(_TOO_MANY_CONCURRENT_REPORTS); public static final ReportErrorReason REPORT_TOO_BIG = new ReportErrorReason(_REPORT_TOO_BIG); public static final ReportErrorReason INVALID_OPERATION_FOR_REPORT_STATE = new ReportErrorReason(_INVALID_OPERATION_FOR_REPORT_STATE); public static final ReportErrorReason INVALID_DIMENSIONS = new ReportErrorReason(_INVALID_DIMENSIONS); public static final ReportErrorReason INVALID_ATTRIBUTES = new ReportErrorReason(_INVALID_ATTRIBUTES); public static final ReportErrorReason INVALID_COLUMNS = new ReportErrorReason(_INVALID_COLUMNS); public static final ReportErrorReason INVALID_DIMENSION_FILTERS = new ReportErrorReason(_INVALID_DIMENSION_FILTERS); public static final ReportErrorReason INVALID_DATE = new ReportErrorReason(_INVALID_DATE); public static final ReportErrorReason END_DATE_TIME_NOT_AFTER_START_TIME = new ReportErrorReason(_END_DATE_TIME_NOT_AFTER_START_TIME); public static final ReportErrorReason NOT_NULL = new ReportErrorReason(_NOT_NULL); public static final ReportErrorReason ATTRIBUTES_NOT_SUPPORTED_FOR_REQUEST = new ReportErrorReason(_ATTRIBUTES_NOT_SUPPORTED_FOR_REQUEST); public static final ReportErrorReason COLUMNS_NOT_SUPPORTED_FOR_REQUESTED_DIMENSIONS = new ReportErrorReason(_COLUMNS_NOT_SUPPORTED_FOR_REQUESTED_DIMENSIONS); public static final ReportErrorReason FAILED_TO_STORE_REPORT = new ReportErrorReason(_FAILED_TO_STORE_REPORT); public static final ReportErrorReason REPORT_NOT_FOUND = new ReportErrorReason(_REPORT_NOT_FOUND); public static final ReportErrorReason SR_CANNOT_RUN_REPORT_IN_ANOTHER_NETWORK = new ReportErrorReason(_SR_CANNOT_RUN_REPORT_IN_ANOTHER_NETWORK); public static final ReportErrorReason UNKNOWN = new ReportErrorReason(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static ReportErrorReason fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { ReportErrorReason enumeration = (ReportErrorReason) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static ReportErrorReason fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ReportErrorReason.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201208", "ReportError.Reason")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
apache-2.0
bss3/ayuda
app/controllers/Application.java
1202
package controllers; import play.*; import play.mvc.*; import views.html.*; public class Application extends Controller { public Result home() { return ok(home.render()); } public Result criar_projeto() { return ok(criar_projeto.render()); } public Result index() { return ok(index.render("Esta funcionando!")); // "Your new application is ready." } public Result info_ong() { return ok(info_ong.render()); } public Result login() { return ok(login.render(false)); } public Result cadastro() { return ok(cadastro.render(false, "")); } public Result pagamento() { return ok(pagamento.render()); } public Result perfil_ong() { return ok(perfil_ong.render()); } public Result menu_logado() { return ok(menu_logado.render()); } public Result projeto() { return ok(projeto.render()); } public Result info_projeto() { return ok(info_projeto.render()); } public Result logoff() { session().clear(); return redirect(routes.Application.index()); } }
apache-2.0
square/dagger
compiler/src/test/java/dagger/tests/integration/codegen/InjectAdapterGenerationTest.java
5403
/* * Copyright (C) 2013 Google Inc. * Copyright (C) 2013 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.tests.integration.codegen; import com.google.testing.compile.JavaFileObjects; import javax.tools.JavaFileObject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.common.truth.Truth.assertAbout; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; import static dagger.tests.integration.ProcessorTestUtils.daggerProcessors; @RunWith(JUnit4.class) public final class InjectAdapterGenerationTest { @Test public void basicInjectAdapter() { JavaFileObject sourceFile = JavaFileObjects.forSourceString("Basic", "" + "import dagger.Module;\n" + "import javax.inject.Inject;\n" + "class Basic {\n" + " static class A { @Inject A() { } }\n" + " static class Foo$Bar {\n" + " @Inject Foo$Bar() { }\n" + " static class Baz { @Inject Baz() { } }\n" + " }\n" + " @Module(injects = { A.class, Foo$Bar.class, Foo$Bar.Baz.class })\n" + " static class AModule { }\n" + "}\n" ); JavaFileObject expectedModuleAdapter = JavaFileObjects.forSourceString("Basic$AModule$$ModuleAdapter", "" + "import dagger.internal.ModuleAdapter;\n" + "import java.lang.Class;\n" + "import java.lang.Override;\n" + "import java.lang.String;\n" + "public final class Basic$AModule$$ModuleAdapter\n" + " extends ModuleAdapter<Basic.AModule> {\n" + " private static final String[] INJECTS = {\n" + " \"members/Basic$A\", \"members/Basic$Foo$Bar\", \"members/Basic$Foo$Bar$Baz\"};\n" + " private static final Class<?>[] STATIC_INJECTIONS = {};\n" + " private static final Class<?>[] INCLUDES = {};\n" + " public Basic$AModule$$ModuleAdapter() {\n" + " super(Basic.AModule.class, INJECTS, STATIC_INJECTIONS, false, INCLUDES,\n" + " true, false);\n" + " }\n" + " @Override public Basic.AModule newModule() {\n" + " return new Basic.AModule();\n" + " }\n" +"}\n" ); JavaFileObject expectedInjectAdapterA = JavaFileObjects.forSourceString("Basic$A$$InjectAdapter", "" + "import dagger.internal.Binding;\n" + "import java.lang.Override;\n" + "public final class Basic$A$$InjectAdapter\n" + " extends Binding<Basic.A> {\n" + " public Basic$A$$InjectAdapter() {\n" + " super(\"Basic$A\", \"members/Basic$A\", NOT_SINGLETON, Basic.A.class);\n" + " }\n" + " @Override public Basic.A get() {\n" + " Basic.A result = new Basic.A();\n" + " return result;\n" + " }\n" + "}\n" ); JavaFileObject expectedInjectAdapterFooBar = JavaFileObjects.forSourceString("Basic$Foo$Bar$$InjectAdapter", "" + "import dagger.internal.Binding;\n" + "import java.lang.Override;\n" + "public final class Basic$Foo$Bar$$InjectAdapter\n" + " extends Binding<Basic.Foo$Bar> {\n" + " public Basic$Foo$Bar$$InjectAdapter() {\n" + " super(\"Basic$Foo$Bar\", \"members/Basic$Foo$Bar\",\n" + " NOT_SINGLETON, Basic.Foo$Bar.class);\n" + " }\n" + " @Override public Basic.Foo$Bar get() {\n" + " Basic.Foo$Bar result = new Basic.Foo$Bar();\n" + " return result;\n" + " }\n" + "}\n" ); JavaFileObject expectedInjectAdapterFooBarBaz = JavaFileObjects.forSourceString("Basic$Foo$Bar$Baz$$InjectAdapter", "" + "import dagger.internal.Binding;\n" + "import java.lang.Override;\n" + "public final class Basic$Foo$Bar$Baz$$InjectAdapter\n" + " extends Binding<Basic.Foo$Bar.Baz> {\n" + " public Basic$Foo$Bar$Baz$$InjectAdapter() {\n" + " super(\"Basic$Foo$Bar$Baz\", \"members/Basic$Foo$Bar$Baz\",\n" + " NOT_SINGLETON, Basic.Foo$Bar.Baz.class);\n" + " }\n" + " @Override public Basic.Foo$Bar.Baz get() {\n" + " Basic.Foo$Bar.Baz result = new Basic.Foo$Bar.Baz();\n" + " return result;\n" + " }\n" + "}\n" ); assertAbout(javaSource()) .that(sourceFile) .processedWith(daggerProcessors()) .compilesWithoutError() .and() .generatesSources(expectedModuleAdapter, expectedInjectAdapterA, expectedInjectAdapterFooBar, expectedInjectAdapterFooBarBaz); } }
apache-2.0
gitee2008/glaf
src/main/java/com/glaf/base/district/web/springmvc/SysDistrictController.java
17318
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glaf.base.district.web.springmvc; import java.io.File; import java.io.IOException; import java.util.*; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.bind.annotation.*; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import com.alibaba.fastjson.*; import com.glaf.core.base.BaseTree; import com.glaf.core.base.ColumnModel; import com.glaf.core.base.TableModel; import com.glaf.core.base.TreeModel; import com.glaf.core.config.SystemProperties; import com.glaf.core.config.ViewProperties; import com.glaf.core.factory.DataServiceFactory; import com.glaf.core.security.*; import com.glaf.core.tree.helper.TreeHelper; import com.glaf.core.tree.helper.TreeUpdateBean; import com.glaf.core.util.*; import com.glaf.base.district.domain.*; import com.glaf.base.district.query.*; import com.glaf.base.district.service.*; import com.glaf.base.modules.sys.model.SysUser; import com.glaf.base.modules.sys.model.TreePermission; import com.glaf.base.modules.sys.query.TreePermissionQuery; import com.glaf.base.modules.sys.service.SysUserService; import com.glaf.base.modules.sys.service.TreePermissionService; import com.glaf.base.utils.XmlToDbImporter; @Controller("/sys/district") @RequestMapping("/sys/district") public class SysDistrictController { protected static final Log logger = LogFactory.getLog(SysDistrictController.class); protected DistrictService districtService; protected SysUserService sysUserService; protected TreePermissionService treePermissionService; public SysDistrictController() { } @ResponseBody @RequestMapping("/delete") public byte[] delete(HttpServletRequest request, ModelMap modelMap) { LoginContext loginContext = RequestUtils.getLoginContext(request); Long id = RequestUtils.getLong(request, "id"); String ids = request.getParameter("ids"); if (StringUtils.isNotEmpty(ids)) { StringTokenizer token = new StringTokenizer(ids, ","); while (token.hasMoreTokens()) { String x = token.nextToken(); if (StringUtils.isNotEmpty(x)) { District district = districtService.getDistrict(Long.valueOf(x)); if (district != null && loginContext.isSystemAdministrator()) { // districtService.deleteById(district.getId()); } } } return ResponseUtils.responseResult(true); } else if (id != null) { District district = districtService.getDistrict(Long.valueOf(id)); if (district != null && loginContext.isSystemAdministrator()) { // districtService.deleteById(district.getId()); return ResponseUtils.responseResult(true); } } return ResponseUtils.responseResult(false); } @RequestMapping("/edit") public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) { RequestUtils.setRequestParameterToAttribute(request); District district = districtService.getDistrict(RequestUtils.getLong(request, "id")); if (district != null) { request.setAttribute("district", district); } Long parentId = RequestUtils.getLong(request, "parentId", 0); List<District> districts = districtService.getDistrictList(parentId); if (district != null) { List<District> children = districtService.getDistrictList(district.getId()); if (districts != null && !districts.isEmpty()) { if (children != null && !children.isEmpty()) { districts.removeAll(children); } districts.remove(district); } } if (parentId > 0) { District parent = districtService.getDistrict(parentId); if (districts == null) { districts = new ArrayList<District>(); } districts.add(parent); } request.setAttribute("trees", districts); request.setAttribute("districts", districts); String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } String x_view = ViewProperties.getString("district.edit"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view, modelMap); } return new ModelAndView("/sys/district/edit", modelMap); } @RequestMapping("/json") @ResponseBody public byte[] json(HttpServletRequest request) throws IOException { LoginContext loginContext = RequestUtils.getLoginContext(request); Map<String, Object> params = RequestUtils.getParameterMap(request); logger.debug("params:" + params); DistrictQuery query = new DistrictQuery(); Tools.populate(query, params); query.deleteFlag(0); query.setActorId(loginContext.getActorId()); query.setLoginContext(loginContext); String actorId = loginContext.getActorId(); if (!loginContext.isSystemAdministrator()) { query.createBy(actorId); } Long parentId = RequestUtils.getLong(request, "parentId", 0); query.parentId(parentId); String gridType = ParamUtils.getString(params, "gridType"); if (gridType == null) { gridType = "easyui"; } int start = 0; int limit = 15; String orderName = null; String order = null; int pageNo = ParamUtils.getInt(params, "page"); limit = ParamUtils.getInt(params, "rows"); start = (pageNo - 1) * limit; orderName = ParamUtils.getString(params, "sortName"); order = ParamUtils.getString(params, "sortOrder"); if (start < 0) { start = 0; } if (limit <= 0) { limit = 100; } JSONObject result = new JSONObject(); int total = districtService.getDistrictCountByQueryCriteria(query); if (total > 0) { result.put("total", total); result.put("totalCount", total); result.put("totalRecords", total); result.put("start", start); result.put("startIndex", start); result.put("limit", limit); result.put("pageSize", limit); if (StringUtils.isNotEmpty(orderName)) { query.setSortOrder(orderName); if (StringUtils.equals(order, "desc")) { query.setSortOrder(" desc "); } } List<District> list = districtService.getDistrictsByQueryCriteria(start, limit, query); if (list != null && !list.isEmpty()) { JSONArray rowsJSON = new JSONArray(); result.put("rows", rowsJSON); for (District district : list) { JSONObject rowJSON = district.toJsonObject(); rowJSON.put("id", district.getId()); rowJSON.put("pId", district.getParentId()); rowJSON.put("districtId", district.getId()); rowJSON.put("districtId", district.getId()); rowJSON.put("startIndex", ++start); rowsJSON.add(rowJSON); } } } else { JSONArray rowsJSON = new JSONArray(); result.put("rows", rowsJSON); result.put("total", total); } return result.toJSONString().getBytes("UTF-8"); } @RequestMapping public ModelAndView list(HttpServletRequest request, ModelMap modelMap) { RequestUtils.setRequestParameterToAttribute(request); String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } return new ModelAndView("/sys/district/list", modelMap); } /** * 显示授权页面 * * @param request * @param modelMap * @return */ @RequestMapping("/privilege") public ModelAndView privilege(HttpServletRequest request, ModelMap modelMap) { RequestUtils.setRequestParameterToAttribute(request); String userId = request.getParameter("userId"); SysUser user = sysUserService.findById(userId); request.setAttribute("user", user); return new ModelAndView("/sys/district/privilege", modelMap); } @ResponseBody @RequestMapping("/reload") public byte[] reload(HttpServletRequest request) { try { XmlToDbImporter imp = new XmlToDbImporter(); String path = SystemProperties.getConfigRootPath() + "/conf/data/district.xml"; logger.debug("load config:" + path); imp.doImport(new File(path), "default"); TreeUpdateBean updateBean = new TreeUpdateBean(); updateBean.updateTreeIds("default", "SYS_DISTRICT", null, "ID_", "PARENTID_", "TREEID_", "LEVEL_", null); return ResponseUtils.responseJsonResult(true); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } return ResponseUtils.responseJsonResult(false); } @ResponseBody @RequestMapping("/saveDistrict") public byte[] saveDistrict(HttpServletRequest request) { Map<String, Object> params = RequestUtils.getParameterMap(request); District district = new District(); try { Tools.populate(district, params); district.setName(request.getParameter("name")); district.setCode(request.getParameter("code")); this.districtService.save(district); return ResponseUtils.responseJsonResult(true); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } return ResponseUtils.responseJsonResult(false); } /** * * * @param request * @return */ @RequestMapping("/saveSort") @ResponseBody public byte[] saveSort(HttpServletRequest request) { String items = request.getParameter("items"); if (StringUtils.isNotEmpty(items)) { int sort = 0; List<TableModel> rows = new ArrayList<TableModel>(); StringTokenizer token = new StringTokenizer(items, ","); while (token.hasMoreTokens()) { String item = token.nextToken(); if (StringUtils.isNotEmpty(item)) { sort++; TableModel t1 = new TableModel(); t1.setTableName("SYS_DISTRICT"); ColumnModel idColumn1 = new ColumnModel(); idColumn1.setColumnName("ID_"); idColumn1.setValue(Long.parseLong(item)); t1.setIdColumn(idColumn1); ColumnModel column = new ColumnModel(); column.setColumnName("SORTNO_"); column.setValue(sort); t1.addColumn(column); rows.add(t1); } } try { DataServiceFactory.getInstance().updateAllTableData(rows); return ResponseUtils.responseResult(true); } catch (Exception ex) { logger.error(ex); } } return ResponseUtils.responseResult(false); } @javax.annotation.Resource public void setDistrictService(DistrictService districtService) { this.districtService = districtService; } @javax.annotation.Resource public void setSysUserService(SysUserService sysUserService) { this.sysUserService = sysUserService; } @javax.annotation.Resource public void setTreePermissionService(TreePermissionService treePermissionService) { this.treePermissionService = treePermissionService; } /** * * @param request * @param modelMap * @return */ @RequestMapping("/showSort") public ModelAndView showSort(HttpServletRequest request, ModelMap modelMap) { RequestUtils.setRequestParameterToAttribute(request); long parentId = RequestUtils.getLong(request, "parentId"); List<District> trees = districtService.getDistrictList(parentId); request.setAttribute("trees", trees); String x_view = ViewProperties.getString("sys.district.showSort"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view, modelMap); } return new ModelAndView("/sys/district/showSort", modelMap); } @ResponseBody @RequestMapping("/treeJson") public byte[] treeJson(HttpServletRequest request) throws IOException { logger.debug("params:" + RequestUtils.getParameterMap(request)); JSONArray array = new JSONArray(); Long parentId = RequestUtils.getLong(request, "id", 0); List<District> districts = null; if (parentId != null) { districts = districtService.getDistrictList(parentId); } if (districts != null && !districts.isEmpty()) { String userId = request.getParameter("userId"); String type = request.getParameter("type"); List<Long> selected = new ArrayList<Long>(); if (StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(userId)) { TreePermissionQuery query = new TreePermissionQuery(); query.type(type); query.userId(userId); List<TreePermission> perms = treePermissionService.list(query); if (perms != null && !perms.isEmpty()) { for (TreePermission p : perms) { selected.add(p.getNodeId()); } } } Map<Long, TreeModel> treeMap = new HashMap<Long, TreeModel>(); List<TreeModel> treeModels = new ArrayList<TreeModel>(); List<Long> districtIds = new ArrayList<Long>(); for (District district : districts) { if (district.getLocked() != 0) { continue; } Map<String, Object> dataMap = new HashMap<String, Object>(); TreeModel tree = new BaseTree(); tree.setId(district.getId()); tree.setParentId(district.getParentId()); tree.setCode(district.getCode()); tree.setName(district.getName()); tree.setSortNo(district.getSortNo()); tree.setIconCls("tree_folder"); if (selected.contains(district.getId())) { if (selected.contains(district.getId())) { tree.setChecked(true); dataMap.put("checked", true); } else { dataMap.put("checked", false); } } tree.setDataMap(dataMap); treeModels.add(tree); districtIds.add(district.getId()); treeMap.put(district.getId(), tree); } // logger.debug("treeModels:" + treeModels.size()); TreeHelper treeHelper = new TreeHelper(); JSONArray jsonArray = treeHelper.getTreeJSONArray(treeModels); for (int i = 0, len = jsonArray.size(); i < len; i++) { JSONObject json = jsonArray.getJSONObject(i); json.put("isParent", true); } // logger.debug(jsonArray.toJSONString()); return jsonArray.toJSONString().getBytes("UTF-8"); } return array.toJSONString().getBytes("UTF-8"); } @ResponseBody @RequestMapping("/treeJson3") public byte[] treeJson3(HttpServletRequest request) throws IOException { logger.debug("params:" + RequestUtils.getParameterMap(request)); JSONArray array = new JSONArray(); Long parentId = RequestUtils.getLong(request, "id", 0); List<District> districts = null; if (parentId != null) { districts = districtService.getDistrictList(parentId); } if (districts != null && !districts.isEmpty()) { String userId = request.getParameter("userId"); String type = request.getParameter("type"); List<Long> selected = new ArrayList<Long>(); if (StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(userId)) { TreePermissionQuery query = new TreePermissionQuery(); query.type(type); query.userId(userId); List<TreePermission> perms = treePermissionService.list(query); if (perms != null && !perms.isEmpty()) { for (TreePermission p : perms) { selected.add(p.getNodeId()); } } } Map<Long, TreeModel> treeMap = new HashMap<Long, TreeModel>(); List<TreeModel> treeModels = new ArrayList<TreeModel>(); List<Long> districtIds = new ArrayList<Long>(); for (District district : districts) { if (district.getLocked() != 0) { continue; } if (district.getLevel() > 3) { continue; } Map<String, Object> dataMap = new HashMap<String, Object>(); TreeModel tree = new BaseTree(); tree.setId(district.getId()); tree.setParentId(district.getParentId()); tree.setCode(district.getCode()); tree.setName(district.getName()); tree.setSortNo(district.getSortNo()); tree.setIconCls("tree_folder"); if (selected.contains(district.getId())) { if (selected.contains(district.getId())) { tree.setChecked(true); dataMap.put("checked", true); } else { dataMap.put("checked", false); } } tree.setDataMap(dataMap); treeModels.add(tree); districtIds.add(district.getId()); treeMap.put(district.getId(), tree); } // logger.debug("treeModels:" + treeModels.size()); TreeHelper treeHelper = new TreeHelper(); JSONArray jsonArray = treeHelper.getTreeJSONArray(treeModels); for (int i = 0, len = jsonArray.size(); i < len; i++) { JSONObject json = jsonArray.getJSONObject(i); json.put("isParent", true); } // logger.debug(jsonArray.toJSONString()); return jsonArray.toJSONString().getBytes("UTF-8"); } return array.toJSONString().getBytes("UTF-8"); } @RequestMapping("/view/{id}") public ModelAndView view(@PathVariable("id") Long id, HttpServletRequest request, ModelMap modelMap) { RequestUtils.setRequestParameterToAttribute(request); District district = districtService.getDistrict(id); request.setAttribute("district", district); String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view); } String x_view = ViewProperties.getString("district.view"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view); } return new ModelAndView("/sys/district/view"); } }
apache-2.0
azkaban/azkaban
azkaban-exec-server/src/main/java/azkaban/execapp/TriggerManager.java
4417
/* * Copyright 2017 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package azkaban.execapp; import azkaban.DispatchMethod; import azkaban.execapp.action.KillExecutionAction; import azkaban.execapp.action.KillJobAction; import azkaban.sla.SlaOption; import azkaban.trigger.Condition; import azkaban.trigger.ConditionChecker; import azkaban.trigger.TriggerAction; import azkaban.trigger.builtin.SlaAlertAction; import azkaban.trigger.builtin.SlaChecker; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.log4j.Logger; @Singleton public class TriggerManager { private static final int SCHEDULED_THREAD_POOL_SIZE = 4; private static final Logger logger = Logger.getLogger(TriggerManager.class); private final ScheduledExecutorService scheduledService; private DispatchMethod dispatchMethod; @Inject public TriggerManager() { this.scheduledService = Executors.newScheduledThreadPool(SCHEDULED_THREAD_POOL_SIZE, new ThreadFactoryBuilder().setNameFormat("azk-trigger-pool-%d").build()); } private Condition createCondition(final SlaOption sla, final int execId, final String checkerName, final String checkerMethod) { final SlaChecker slaFailChecker = new SlaChecker(checkerName, sla, execId); final Map<String, ConditionChecker> slaCheckers = new HashMap<>(); slaCheckers.put(slaFailChecker.getId(), slaFailChecker); return new Condition(slaCheckers, slaFailChecker.getId() + "." + checkerMethod); } private List<TriggerAction> createActions(final SlaOption sla, final int execId) { final List<TriggerAction> actions = new ArrayList<>(); if (sla.hasAlert()) { TriggerAction action = new SlaAlertAction(SlaOption.ACTION_ALERT, sla, execId); } if (sla.hasAlert()) { actions.add(new SlaAlertAction(SlaOption.ACTION_ALERT, sla, execId)); } if(sla.hasKill()) { switch(sla.getType().getComponent()) { case FLOW: actions.add(new KillExecutionAction(SlaOption.ACTION_CANCEL_FLOW, execId, dispatchMethod)); break; case JOB: actions.add(new KillJobAction(SlaOption.ACTION_KILL_JOB, execId, sla.getJobName())); break; default: logger.info("Unknown action type " + sla.getType().getComponent()); break; } } return actions; } @SuppressWarnings("FutureReturnValueIgnored") public void addTrigger(final int execId, final List<SlaOption> slaOptions) { for (final SlaOption slaOption : slaOptions) { final Condition triggerCond = createCondition(slaOption, execId, "slaFailChecker", "isSlaFailed()"); // if whole flow finish before violating sla, just expire the checker final Condition expireCond = createCondition(slaOption, execId, "slaPassChecker", "isSlaPassed" + "()"); final List<TriggerAction> actions = createActions(slaOption, execId); final Trigger trigger = new Trigger(execId, triggerCond, expireCond, actions); final Duration duration = slaOption.getDuration(); final long durationInMillis = duration.toMillis(); logger.info("Adding sla trigger " + slaOption.toString() + " to execution " + execId + ", scheduled to trigger in " + durationInMillis / 1000 + " seconds"); this.scheduledService.schedule(trigger, durationInMillis, TimeUnit.MILLISECONDS); } } public void setDispatchMethod(final DispatchMethod dispatchMethod) { this.dispatchMethod = dispatchMethod; } public void shutdown() { this.scheduledService.shutdownNow(); } }
apache-2.0
DISID/springlets
springlets-data/springlets-data-jpa/src/main/java/io/springlets/data/jpa/config/SpringletsDataJpaAuthenticationAuditorConfiguration.java
1442
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.springlets.data.jpa.config; import io.springlets.data.domain.AuthenticationAuditorAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.AuditorAware; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; /** * Configuration class to register the {@link AuthenticationAuditorAware} * class as the {@link AuditorAware} implementation to use, as well as * enabling the Spring Data's JPA auditing * @author Cèsar Ordiñana at http://www.disid.com[DISID Corporation S.L.] */ @Configuration @EnableJpaAuditing public class SpringletsDataJpaAuthenticationAuditorConfiguration { @Bean public AuditorAware<String> auditorProvider() { return new AuthenticationAuditorAware(); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-iotwireless/src/main/java/com/amazonaws/services/iotwireless/model/transform/ListFuotaTasksResultJsonUnmarshaller.java
3132
/* * 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.iotwireless.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.iotwireless.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ListFuotaTasksResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListFuotaTasksResultJsonUnmarshaller implements Unmarshaller<ListFuotaTasksResult, JsonUnmarshallerContext> { public ListFuotaTasksResult unmarshall(JsonUnmarshallerContext context) throws Exception { ListFuotaTasksResult listFuotaTasksResult = new ListFuotaTasksResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return listFuotaTasksResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("NextToken", targetDepth)) { context.nextToken(); listFuotaTasksResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("FuotaTaskList", targetDepth)) { context.nextToken(); listFuotaTasksResult.setFuotaTaskList(new ListUnmarshaller<FuotaTask>(FuotaTaskJsonUnmarshaller.getInstance()) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return listFuotaTasksResult; } private static ListFuotaTasksResultJsonUnmarshaller instance; public static ListFuotaTasksResultJsonUnmarshaller getInstance() { if (instance == null) instance = new ListFuotaTasksResultJsonUnmarshaller(); return instance; } }
apache-2.0
top-gun007/CleanCampusAPP
MyApplication/app/src/androidTest/java/in/ac/nith/card/ExampleInstrumentedTest.java
734
package in.ac.nith.card; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("in.ac.nith.card", appContext.getPackageName()); } }
apache-2.0
stserp/erp1
source/src/com/baosight/sts/st/ws/service/ServiceWS0001.java
2014
/** * ServiceWS0001.java * * This file was auto-generated from WSDL * by the Apache Axis #axisVersion# #today# WSDL2Java emitter. */ package com.baosight.sts.st.ws.service; public interface ServiceWS0001 extends java.rmi.Remote { public java.lang.String sayHelloEb(java.lang.String in) throws java.rmi.RemoteException; // public com.baosight.sts.st.ws.domain.InvInfoForm[] queryInvInfoEb(com.baosight.sts.st.ws.domain.InvQueForm inModel) throws java.rmi.RemoteException; // public com.baosight.sts.st.ws.domain.PurConAmtInfoForm[] queryPurConAmtInfoEb(com.baosight.sts.st.ws.domain.PurConAmtQueForm inModel) throws java.rmi.RemoteException; // public com.baosight.ssbs.go.ws.domain.ArrayOfPurContForm queryPurContEb(com.baosight.ssbs.go.ws.domain.PurQueForm inModel) throws java.rmi.RemoteException; // public com.baosight.sts.st.ws.domain.PurPayInfoForm[] queryPurPayInfoEb(com.baosight.sts.st.ws.domain.PurPayQueForm inModel) throws java.rmi.RemoteException; // public com.baosight.sts.st.ws.domain.ReceiveInfoForm[] queryReceiveInfoEb(com.baosight.sts.st.ws.domain.ReceiveQueForm inModel) throws java.rmi.RemoteException; public com.baosight.ssbs.go.ws.domain.ArrayOfInvInfoForm queryInvInfoEb(com.baosight.ssbs.go.ws.domain.InvQueForm inModel) throws java.rmi.RemoteException; public com.baosight.ssbs.go.ws.domain.ArrayOfPurConAmtInfoForm queryPurConAmtInfoEb(com.baosight.ssbs.go.ws.domain.PurConAmtQueForm inModel) throws java.rmi.RemoteException; public com.baosight.ssbs.go.ws.domain.ArrayOfPurContForm queryPurContEb(com.baosight.ssbs.go.ws.domain.PurQueForm inModel) throws java.rmi.RemoteException; public com.baosight.ssbs.go.ws.domain.ArrayOfPurPayInfoForm queryPurPayInfoEb(com.baosight.ssbs.go.ws.domain.PurPayQueForm inModel) throws java.rmi.RemoteException; public com.baosight.ssbs.go.ws.domain.ArrayOfReceiveInfoForm queryReceiveInfoEb(com.baosight.ssbs.go.ws.domain.ReceiveQueForm inModel) throws java.rmi.RemoteException; }
apache-2.0
sebastiansemmle/acio
src/test/java/org/apache/commons/io/input/NullReaderTest.java
8327
/* * 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.commons.io.input; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import junit.framework.TestCase; /** * JUnit Test Case for {@link NullReader}. * * @version $Id$ */ public class NullReaderTest extends TestCase { /** Constructor */ public NullReaderTest(String name) { super(name); } /** Set up */ @Override protected void setUp() throws Exception { super.setUp(); } /** Tear Down */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test <code>available()</code> method. */ public void testRead() throws Exception { int size = 5; TestNullReader reader = new TestNullReader(size); for (int i = 0; i < size; i++) { assertEquals("Check Value [" + i + "]", i, reader.read()); } // Check End of File assertEquals("End of File", -1, reader.read()); // Test reading after the end of file try { int result = reader.read(); fail("Should have thrown an IOException, value=[" + result + "]"); } catch (IOException e) { assertEquals("Read after end of file", e.getMessage()); } // Close - should reset reader.close(); assertEquals("Available after close", 0, reader.getPosition()); } /** * Test <code>read(char[])</code> method. */ public void testReadCharArray() throws Exception { char[] chars = new char[10]; Reader reader = new TestNullReader(15); // Read into array int count1 = reader.read(chars); assertEquals("Read 1", chars.length, count1); for (int i = 0; i < count1; i++) { assertEquals("Check Chars 1", i, chars[i]); } // Read into array int count2 = reader.read(chars); assertEquals("Read 2", 5, count2); for (int i = 0; i < count2; i++) { assertEquals("Check Chars 2", count1 + i, chars[i]); } // End of File int count3 = reader.read(chars); assertEquals("Read 3 (EOF)", -1, count3); // Test reading after the end of file try { int count4 = reader.read(chars); fail("Should have thrown an IOException, value=[" + count4 + "]"); } catch (IOException e) { assertEquals("Read after end of file", e.getMessage()); } // reset by closing reader.close(); // Read into array using offset & length int offset = 2; int lth = 4; int count5 = reader.read(chars, offset, lth); assertEquals("Read 5", lth, count5); for (int i = offset; i < lth; i++) { assertEquals("Check Chars 3", i, chars[i]); } } /** * Test when configured to throw an EOFException at the end of file * (rather than return -1). */ public void testEOFException() throws Exception { Reader reader = new TestNullReader(2, false, true); assertEquals("Read 1", 0, reader.read()); assertEquals("Read 2", 1, reader.read()); try { int result = reader.read(); fail("Should have thrown an EOFException, value=[" + result + "]"); } catch (EOFException e) { // expected } } /** * Test <code>mark()</code> and <code>reset()</code> methods. */ public void testMarkAndReset() throws Exception { int position = 0; int readlimit = 10; Reader reader = new TestNullReader(100, true, false); assertTrue("Mark Should be Supported", reader.markSupported()); // No Mark try { reader.reset(); fail("Read limit exceeded, expected IOException "); } catch (IOException e) { assertEquals("No Mark IOException message", "No position has been marked", e.getMessage()); } for (; position < 3; position++) { assertEquals("Read Before Mark [" + position +"]", position, reader.read()); } // Mark reader.mark(readlimit); // Read further for (int i = 0; i < 3; i++) { assertEquals("Read After Mark [" + i +"]", (position + i), reader.read()); } // Reset reader.reset(); // Read From marked position for (int i = 0; i < readlimit + 1; i++) { assertEquals("Read After Reset [" + i +"]", (position + i), reader.read()); } // Reset after read limit passed try { reader.reset(); fail("Read limit exceeded, expected IOException "); } catch (IOException e) { assertEquals("Read limit IOException message", "Marked position [" + position + "] is no longer valid - passed the read limit [" + readlimit + "]", e.getMessage()); } } /** * Test <code>mark()</code> not supported. */ public void testMarkNotSupported() throws Exception { Reader reader = new TestNullReader(100, false, true); assertFalse("Mark Should NOT be Supported", reader.markSupported()); try { reader.mark(5); fail("mark() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { assertEquals("mark() error message", "Mark not supported", e.getMessage()); } try { reader.reset(); fail("reset() should throw UnsupportedOperationException"); } catch (UnsupportedOperationException e) { assertEquals("reset() error message", "Mark not supported", e.getMessage()); } } /** * Test <code>skip()</code> method. */ public void testSkip() throws Exception { Reader reader = new TestNullReader(10, true, false); assertEquals("Read 1", 0, reader.read()); assertEquals("Read 2", 1, reader.read()); assertEquals("Skip 1", 5, reader.skip(5)); assertEquals("Read 3", 7, reader.read()); assertEquals("Skip 2", 2, reader.skip(5)); // only 2 left to skip assertEquals("Skip 3 (EOF)", -1, reader.skip(5)); // End of file try { reader.skip(5); // fail("Expected IOException for skipping after end of file"); } catch (IOException e) { assertEquals("Skip after EOF IOException message", "Skip after end of file", e.getMessage()); } } // ------------- Test NullReader implementation ------------- private static final class TestNullReader extends NullReader { public TestNullReader(int size) { super(size); } public TestNullReader(int size, boolean markSupported, boolean throwEofException) { super(size, markSupported, throwEofException); } @Override protected int processChar() { return ((int)getPosition() - 1); } @Override protected void processChars(char[] chars, int offset, int length) { int startPos = (int)getPosition() - length; for (int i = offset; i < length; i++) { chars[i] = (char)(startPos + i); } } } }
apache-2.0
sequenceiq/cloudbreak
autoscale/src/main/java/com/sequenceiq/periscope/domain/Ambari.java
1598
package com.sequenceiq.periscope.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; @Entity public class Ambari { @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "ambari_generator") @SequenceGenerator(name = "ambari_generator", sequenceName = "ambari_id_seq", allocationSize = 1) private long id; @Column(name = "ambari_host") private String host; @Column(name = "ambari_port") private String port; @Column(name = "ambari_user") private String user; @Column(name = "ambari_pass") private String pass; public Ambari() { } public Ambari(String host, String port, String user, String pass) { this.host = host; this.port = port; this.user = user; this.pass = pass; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } }
apache-2.0
wanliwang/cayman
cm-idea/src/main/java/com/bjorktech/cayman/idea/middleware/mq/custom/MeetHandler.java
236
package com.bjorktech.cayman.idea.middleware.mq.custom; /** * User: sheshan * Date: 2018/7/17 * content: */ public interface MeetHandler { void validate(); void preHandler(); void handler(); void postHander(); }
apache-2.0
eGovFrame/egovframework.rte.root
Foundation/egovframework.rte.fdl.logging/src/test/java/egovframework/rte/fdl/logging/sample/LogLevelInfo.java
411
package egovframework.rte.fdl.logging.sample; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Component; @Component("logLevelInfo") public class LogLevelInfo { protected Log log = LogFactory.getLog(this.getClass()); public void executeSomeLogic() { log.info("INFO - LogLevelInfo.executeSomeLogic executed"); } }
apache-2.0
gureronder/midpoint
model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/controller/ModelController.java
97768
/* * Copyright (c) 2010-2015 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.model.impl.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.xml.namespace.QName; import com.evolveum.midpoint.model.api.AccessCertificationService; import com.evolveum.midpoint.model.api.ProgressListener; import com.evolveum.midpoint.model.api.RoleSelectionSpecification; import com.evolveum.midpoint.model.api.ScriptExecutionException; import com.evolveum.midpoint.model.api.ScriptExecutionResult; import com.evolveum.midpoint.model.api.ScriptingService; import com.evolveum.midpoint.model.api.TaskService; import com.evolveum.midpoint.model.api.WorkflowService; import com.evolveum.midpoint.model.api.hooks.ReadHook; import com.evolveum.midpoint.model.impl.scripting.ExecutionContext; import com.evolveum.midpoint.model.impl.scripting.ScriptingExpressionEvaluator; import com.evolveum.midpoint.prism.ConsistencyCheckScope; import com.evolveum.midpoint.prism.parser.XNodeSerializer; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.wf.api.WorkflowManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationDecisionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationDefinitionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.NodeType; import com.evolveum.midpoint.xml.ns._public.model.model_context_3.LensContextType; import com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingExpressionType; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.jfree.util.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.evolveum.midpoint.audit.api.AuditEventRecord; import com.evolveum.midpoint.audit.api.AuditEventStage; import com.evolveum.midpoint.audit.api.AuditEventType; import com.evolveum.midpoint.audit.api.AuditService; import com.evolveum.midpoint.common.InternalsConfig; import com.evolveum.midpoint.common.crypto.CryptoUtil; import com.evolveum.midpoint.common.refinery.LayerRefinedAttributeDefinition; import com.evolveum.midpoint.common.refinery.LayerRefinedObjectClassDefinition; import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.model.api.ModelAuthorizationAction; import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.api.ModelInteractionService; import com.evolveum.midpoint.model.api.ModelService; import com.evolveum.midpoint.model.api.PolicyViolationException; import com.evolveum.midpoint.model.api.context.ModelContext; import com.evolveum.midpoint.model.api.hooks.HookRegistry; import com.evolveum.midpoint.model.impl.ModelObjectResolver; import com.evolveum.midpoint.model.impl.importer.ImportAccountsFromResourceTaskHandler; import com.evolveum.midpoint.model.impl.importer.ObjectImporter; import com.evolveum.midpoint.model.impl.lens.ChangeExecutor; import com.evolveum.midpoint.model.impl.lens.Clockwork; import com.evolveum.midpoint.model.impl.lens.ContextFactory; import com.evolveum.midpoint.model.impl.lens.LensContext; import com.evolveum.midpoint.model.impl.lens.LensProjectionContext; import com.evolveum.midpoint.model.impl.lens.projector.Projector; import com.evolveum.midpoint.model.impl.util.Utils; import com.evolveum.midpoint.prism.DisplayableValueImpl; import com.evolveum.midpoint.prism.Item; import com.evolveum.midpoint.prism.ItemDefinition; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.PrismContainerValue; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.PrismPropertyValue; import com.evolveum.midpoint.prism.PrismReference; import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.PrismValue; import com.evolveum.midpoint.prism.Visitable; import com.evolveum.midpoint.prism.Visitor; import com.evolveum.midpoint.prism.crypto.Protector; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.ItemPathSegment; import com.evolveum.midpoint.prism.query.AllFilter; import com.evolveum.midpoint.prism.query.AndFilter; import com.evolveum.midpoint.prism.query.EqualFilter; import com.evolveum.midpoint.prism.query.NoneFilter; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectPaging; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.query.OrFilter; import com.evolveum.midpoint.prism.query.TypeFilter; import com.evolveum.midpoint.prism.xml.XsdTypeMapper; import com.evolveum.midpoint.provisioning.api.ProvisioningOperationOptions; import com.evolveum.midpoint.provisioning.api.ProvisioningService; import com.evolveum.midpoint.repo.api.RepoAddOptions; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.cache.RepositoryCache; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.ObjectDeltaOperation; import com.evolveum.midpoint.schema.ObjectSelector; import com.evolveum.midpoint.schema.ResultHandler; import com.evolveum.midpoint.schema.RetrieveOption; import com.evolveum.midpoint.schema.SearchResultList; import com.evolveum.midpoint.schema.SearchResultMetadata; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultRunner; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.security.api.ObjectSecurityConstraints; import com.evolveum.midpoint.security.api.SecurityEnforcer; import com.evolveum.midpoint.security.api.UserProfileService; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.DisplayableValue; import com.evolveum.midpoint.util.exception.AuthorizationException; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ImportOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationDecisionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationPhaseType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorHostType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.LayerType; import com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableRowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectPolicyConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectSynchronizationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectTemplateItemDefinitionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectTemplateType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PropertyAccessType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PropertyLimitationsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SecurityPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.midpoint.xml.ns._public.common.common_3.WfProcessInstanceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.WorkItemType; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * This used to be an interface, but it was switched to class for simplicity. I * don't expect that the implementation of the controller will be ever replaced. * In extreme case the whole Model will be replaced by a different * implementation, but not just the controller. * <p/> * However, the common way to extend the functionality will be the use of hooks * that are implemented here. * <p/> * Great deal of code is copied from the old ModelControllerImpl. * * @author lazyman * @author Radovan Semancik */ @Component public class ModelController implements ModelService, ModelInteractionService, TaskService, WorkflowService, ScriptingService, AccessCertificationService { // Constants for OperationResult public static final String CLASS_NAME_WITH_DOT = ModelController.class.getName() + "."; public static final String ADD_OBJECT_WITH_EXCLUSION = CLASS_NAME_WITH_DOT + "addObjectWithExclusion"; public static final String MODIFY_OBJECT_WITH_EXCLUSION = CLASS_NAME_WITH_DOT + "modifyObjectWithExclusion"; public static final String CHANGE_ACCOUNT = CLASS_NAME_WITH_DOT + "changeAccount"; public static final String GET_SYSTEM_CONFIGURATION = CLASS_NAME_WITH_DOT + "getSystemConfiguration"; public static final String RESOLVE_USER_ATTRIBUTES = CLASS_NAME_WITH_DOT + "resolveUserAttributes"; public static final String RESOLVE_ACCOUNT_ATTRIBUTES = CLASS_NAME_WITH_DOT + "resolveAccountAttributes"; public static final String CREATE_ACCOUNT = CLASS_NAME_WITH_DOT + "createAccount"; public static final String UPDATE_ACCOUNT = CLASS_NAME_WITH_DOT + "updateAccount"; public static final String PROCESS_USER_TEMPLATE = CLASS_NAME_WITH_DOT + "processUserTemplate"; private static final Trace LOGGER = TraceManager.getTrace(ModelController.class); @Autowired(required = true) private Clockwork clockwork; @Autowired(required = true) PrismContext prismContext; @Autowired(required = true) private ProvisioningService provisioning; @Autowired(required = true) private ModelObjectResolver objectResolver; @Autowired(required = true) @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; @Autowired(required = true) private transient ImportAccountsFromResourceTaskHandler importAccountsFromResourceTaskHandler; @Autowired(required = true) private transient ObjectImporter objectImporter; @Autowired(required = false) private HookRegistry hookRegistry; @Autowired(required = true) private TaskManager taskManager; @Autowired(required = false) // not required in all circumstances private WorkflowManager workflowManager; @Autowired private ScriptingExpressionEvaluator scriptingExpressionEvaluator; @Autowired(required = true) private ChangeExecutor changeExecutor; @Autowired(required = true) SystemConfigurationHandler systemConfigurationHandler; @Autowired(required = true) private AuditService auditService; @Autowired(required = true) private SecurityEnforcer securityEnforcer; @Autowired(required = true) private UserProfileService userProfileService; @Autowired(required = true) Projector projector; @Autowired(required = true) Protector protector; @Autowired(required = true) ModelDiagController modelDiagController; @Autowired(required = true) ContextFactory contextFactory; @Autowired(required = true) private SchemaTransformer schemaTransformer; public ModelObjectResolver getObjectResolver() { return objectResolver; } @Override public <T extends ObjectType> PrismObject<T> getObject(Class<T> clazz, String oid, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { Validate.notEmpty(oid, "Object oid must not be null or empty."); Validate.notNull(parentResult, "Operation result must not be null."); Validate.notNull(clazz, "Object class must not be null."); RepositoryCache.enter(); PrismObject<T> object = null; OperationResult result = parentResult.createMinorSubresult(GET_OBJECT); result.addParam("oid", oid); result.addCollectionOfSerializablesAsParam("options", options); result.addParam("class", clazz); GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); try { if (GetOperationOptions.isRaw(rootOptions)) { // MID-2218 QNameUtil.setTemporarilyTolerateUndeclaredPrefixes(true); } ObjectReferenceType ref = new ObjectReferenceType(); ref.setOid(oid); ref.setType(ObjectTypes.getObjectType(clazz).getTypeQName()); Utils.clearRequestee(task); object = objectResolver.getObject(clazz, oid, options, task, result).asPrismObject(); schemaTransformer.applySchemasAndSecurity(object, rootOptions, null, task, result); resolve(object, options, task, result); // resolveNames(object, options, task, result); } catch (SchemaException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ObjectNotFoundException e) { if (GetOperationOptions.isAllowNotFound(rootOptions)){ result.getLastSubresult().setStatus(OperationResultStatus.HANDLED_ERROR); } else { ModelUtils.recordFatalError(result, e); } throw e; } catch (CommunicationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ConfigurationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SecurityViolationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (RuntimeException e) { ModelUtils.recordFatalError(result, e); throw e; } finally { QNameUtil.setTemporarilyTolerateUndeclaredPrefixes(false); RepositoryCache.exit(); } result.cleanupResult(); return object; } protected void resolve(PrismObject<?> object, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, ConfigurationException { if (object == null || options == null) { return; } for (SelectorOptions<GetOperationOptions> option: options) { try{ resolve(object, option, task, result); } catch(ObjectNotFoundException ex){ result.recordFatalError(ex.getMessage(), ex); return; } } } protected void resolveNames(PrismObject<?> object, Collection<SelectorOptions<GetOperationOptions>> options, final Task task, final OperationResult result) throws SchemaException, ObjectNotFoundException { if (object == null || options == null) { return; } // currently, only all-or-nothing names resolving is provided GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); if (!GetOperationOptions.isResolveNames(rootOptions)) { return; } final GetOperationOptions rootOptionsNoResolve = rootOptions.clone(); rootOptionsNoResolve.setResolveNames(false); rootOptionsNoResolve.setResolve(false); rootOptionsNoResolve.setRaw(true); //rootOptionsNoResolve.setAllowNotFound(true); // does not work reliably yet object.accept(new Visitor() { @Override public void visit(Visitable visitable) { if (visitable instanceof PrismReferenceValue) { PrismReferenceValue refVal = (PrismReferenceValue) visitable; PrismObject<?> refObject = refVal.getObject(); String name = null; if (refObject == null) { try { // TODO what about security here?! // TODO use some minimalistic get options (e.g. retrieve name only) refObject = objectResolver.resolve(refVal, "", rootOptionsNoResolve, task, result); if (refObject == null) { // will be used with AllowNotFound above name = "(object not found)"; } } catch (ObjectNotFoundException e) { // actually, this won't occur if AllowNotFound is set to true above (however, for now, it is not) result.muteError(); result.muteLastSubresultError(); name = "(object not found)"; } catch (RuntimeException e) { result.muteError(); result.muteLastSubresultError(); name = "(object cannot be retrieved)"; } } if (refObject != null) { name = PolyString.getOrig(refObject.asObjectable().getName()); } if (StringUtils.isNotEmpty(name)) { refVal.setTargetName(refObject.getName()); } } } }); } private void resolve(PrismObject<?> object, SelectorOptions<GetOperationOptions> option, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, ConfigurationException { if (!GetOperationOptions.isResolve(option.getOptions())) { return; } ObjectSelector selector = option.getSelector(); if (selector == null) { return; } ItemPath path = selector.getPath(); resolve (object, path, option, task, result); } private <O extends ObjectType> void resolve(PrismObject<?> object, ItemPath path, SelectorOptions<GetOperationOptions> option, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, ConfigurationException { if (path == null || path.isEmpty()) { return; } ItemPathSegment first = path.first(); ItemPath rest = path.rest(); QName refName = ItemPath.getName(first); PrismReference reference = object.findReferenceByCompositeObjectElementName(refName); if (reference == null) { // alternatively look up by reference name (e.g. linkRef) reference = object.findReference(refName); if (reference == null) { return;//throw new SchemaException("Cannot resolve: No reference "+refName+" in "+object); } } for (PrismReferenceValue refVal: reference.getValues()) { PrismObject<O> refObject = refVal.getObject(); if (refObject == null) { refObject = objectResolver.resolve(refVal, object.toString(), option.getOptions(), task, result); schemaTransformer.applySchemasAndSecurity(refObject, option.getOptions(), null, task, result); refVal.setObject(refObject); } if (!rest.isEmpty()) { resolve(refObject, rest, option, task, result); } } } @Override public Collection<ObjectDeltaOperation<? extends ObjectType>> executeChanges(final Collection<ObjectDelta<? extends ObjectType>> deltas, ModelExecuteOptions options, Task task, OperationResult parentResult) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { return executeChanges(deltas, options, task, null, parentResult); } /* (non-Javadoc) * @see com.evolveum.midpoint.model.api.ModelService#executeChanges(java.util.Collection, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult) */ @Override public Collection<ObjectDeltaOperation<? extends ObjectType>> executeChanges(final Collection<ObjectDelta<? extends ObjectType>> deltas, ModelExecuteOptions options, Task task, Collection<ProgressListener> statusListeners, OperationResult parentResult) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { Collection<ObjectDeltaOperation<? extends ObjectType>> retval = new ArrayList<>(); OperationResult result = parentResult.createSubresult(EXECUTE_CHANGES); result.addParam(OperationResult.PARAM_OPTIONS, options); // Search filters treatment: if reevaluation is requested, we have to deal with three cases: // 1) for ADD operation: filters contained in object-to-be-added -> these are treated here // 2) for MODIFY operation: filters contained in existing object (not touched by deltas) -> these are treated after the modify operation // 3) for MODIFY operation: filters contained in deltas -> these have to be treated here, because if OID is missing from such a delta, the change would be rejected by the repository if (ModelExecuteOptions.isReevaluateSearchFilters(options)) { for (ObjectDelta<? extends ObjectType> delta : deltas) { Utils.resolveReferences(delta, cacheRepositoryService, false, true, prismContext, result); } } else if (ModelExecuteOptions.isIsImport(options)) { // if plain import is requested, we simply evaluate filters in ADD operation (and we do not force reevaluation if OID is already set) for (ObjectDelta<? extends ObjectType> delta : deltas) { if (delta.isAdd()) { Utils.resolveReferences(delta.getObjectToAdd(), cacheRepositoryService, false, false, prismContext, result); } } } // Make sure everything is encrypted as needed before logging anything. // But before that we need to make sure that we have proper definition, otherwise we // might miss some encryptable data in dynamic schemas applyDefinitions(deltas, options, result); Utils.encrypt(deltas, protector, options, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("MODEL.executeChanges(\n deltas:\n{}\n options:{}", DebugUtil.debugDump(deltas, 2), options); } OperationResultRunner.run(result, new Runnable() { @Override public void run() { for(ObjectDelta<? extends ObjectType> delta: deltas) { delta.checkConsistence(); } } }); RepositoryCache.enter(); try { if (ModelExecuteOptions.isRaw(options)) { // Go directly to repository AuditEventRecord auditRecord = new AuditEventRecord(AuditEventType.EXECUTE_CHANGES_RAW, AuditEventStage.REQUEST); auditRecord.addDeltas(ObjectDeltaOperation.cloneDeltaCollection(deltas)); auditService.audit(auditRecord, task); for(ObjectDelta<? extends ObjectType> delta: deltas) { OperationResult result1 = result.createSubresult(EXECUTE_CHANGE); // MID-2486 if (delta.getObjectTypeClass() == ShadowType.class || delta.getObjectTypeClass() == ResourceType.class) { try { provisioning.applyDefinition(delta, result1); } catch (SchemaException|ObjectNotFoundException|CommunicationException|ConfigurationException|RuntimeException e) { // we can tolerate this - if there's a real problem with definition, repo call below will fail LoggingUtils.logExceptionAsWarning(LOGGER, "Couldn't apply definition on shadow/resource raw-mode delta {} -- continuing the operation.", e, delta); result1.muteLastSubresultError(); } } try { if (delta.isAdd()) { RepoAddOptions repoOptions = new RepoAddOptions(); if (ModelExecuteOptions.isNoCrypt(options)) { repoOptions.setAllowUnencryptedValues(true); } if (ModelExecuteOptions.isOverwrite(options)) { repoOptions.setOverwrite(true); } securityEnforcer.authorize(ModelAuthorizationAction.ADD.getUrl(), null, delta.getObjectToAdd(), null, null, null, result1); String oid = cacheRepositoryService.addObject(delta.getObjectToAdd(), repoOptions, result1); delta.setOid(oid); } else if (delta.isDelete()) { QNameUtil.setTemporarilyTolerateUndeclaredPrefixes(true); // MID-2218 try { if (!securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_ALL_URL, null, null, null, null, null)) { // getting the object is avoided in case of administrator's request in order to allow deleting malformed (unreadable) objects PrismObject<? extends ObjectType> existingObject = cacheRepositoryService.getObject(delta.getObjectTypeClass(), delta.getOid(), null, result1); securityEnforcer.authorize(ModelAuthorizationAction.DELETE.getUrl(), null, existingObject, null, null, null, result1); } if (ObjectTypes.isClassManagedByProvisioning(delta.getObjectTypeClass())) { Utils.clearRequestee(task); provisioning.deleteObject(delta.getObjectTypeClass(), delta.getOid(), ProvisioningOperationOptions.createRaw(), null, task, result1); } else { cacheRepositoryService.deleteObject(delta.getObjectTypeClass(), delta.getOid(), result1); } } finally { QNameUtil.setTemporarilyTolerateUndeclaredPrefixes(false); } } else if (delta.isModify()) { QNameUtil.setTemporarilyTolerateUndeclaredPrefixes(true); // MID-2218 try { PrismObject existingObject = cacheRepositoryService.getObject(delta.getObjectTypeClass(), delta.getOid(), null, result1); securityEnforcer.authorize(ModelAuthorizationAction.MODIFY.getUrl(), null, existingObject, delta, null, null, result1); cacheRepositoryService.modifyObject(delta.getObjectTypeClass(), delta.getOid(), delta.getModifications(), result1); } finally { QNameUtil.setTemporarilyTolerateUndeclaredPrefixes(false); } if (ModelExecuteOptions.isReevaluateSearchFilters(options)) { // treat filters that already exist in the object (case #2 above) reevaluateSearchFilters(delta.getObjectTypeClass(), delta.getOid(), result1); } } else { throw new IllegalArgumentException("Wrong delta type "+delta.getChangeType()+" in "+delta); } } catch (ObjectAlreadyExistsException|SchemaException|ObjectNotFoundException|ConfigurationException|CommunicationException|SecurityViolationException|RuntimeException e) { ModelUtils.recordFatalError(result1, e); throw e; } result1.computeStatus(); retval.add(new ObjectDeltaOperation<>(delta, result1)); } auditRecord.setTimestamp(null); auditRecord.setOutcome(OperationResultStatus.SUCCESS); auditRecord.setEventStage(AuditEventStage.EXECUTION); auditService.audit(auditRecord, task); } else { LensContext<? extends ObjectType> context = contextFactory.createContext(deltas, options, task, result); if (ModelExecuteOptions.isReevaluateSearchFilters(options)) { String m = "ReevaluateSearchFilters option is not fully supported for non-raw operations yet. Filters already present in the object will not be touched."; LOGGER.warn("{} Context = {}", m, context.debugDump()); result.createSubresult(CLASS_NAME_WITH_DOT+"reevaluateSearchFilters").recordWarning(m); } context.setProgressListeners(statusListeners); // Note: Request authorization happens inside clockwork clockwork.run(context, task, result); // prepare return value if (context.getFocusContext() != null) { retval.addAll(context.getFocusContext().getExecutedDeltas()); } for (LensProjectionContext projectionContext : context.getProjectionContexts()) { retval.addAll(projectionContext.getExecutedDeltas()); } } // Clockwork.run sets "in-progress" flag just at the root level // and result.computeStatus() would erase it. // So we deal with it in a special way, in order to preserve this information for the user. if (result.isInProgress()) { result.computeStatus(); if (result.isSuccess()) { result.recordInProgress(); } } else { result.computeStatus(); } result.cleanupResult(); } catch (ObjectAlreadyExistsException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ObjectNotFoundException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SchemaException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ExpressionEvaluationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (CommunicationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ConfigurationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (PolicyViolationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SecurityViolationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (RuntimeException e) { ModelUtils.recordFatalError(result, e); throw e; } finally { RepositoryCache.exit(); } return retval; } private <T extends ObjectType> void reevaluateSearchFilters(Class<T> objectTypeClass, String oid, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException { OperationResult result = parentResult.createSubresult(CLASS_NAME_WITH_DOT+"reevaluateSearchFilters"); try { PrismObject<T> storedObject = cacheRepositoryService.getObject(objectTypeClass, oid, null, result); PrismObject<T> updatedObject = storedObject.clone(); Utils.resolveReferences(updatedObject, cacheRepositoryService, false, true, prismContext, result); ObjectDelta<T> delta = storedObject.diff(updatedObject); if (LOGGER.isTraceEnabled()) { LOGGER.trace("reevaluateSearchFilters found delta: {}", delta.debugDump()); } if (!delta.isEmpty()) { cacheRepositoryService.modifyObject(objectTypeClass, oid, delta.getModifications(), result); } result.recordSuccess(); } catch (SchemaException|ObjectNotFoundException|ObjectAlreadyExistsException|RuntimeException e) { result.recordFatalError("Couldn't reevaluate search filters: "+e.getMessage(), e); throw e; } } @Override public <F extends ObjectType> void recompute(Class<F> type, String oid, Task task, OperationResult parentResult) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { OperationResult result = parentResult.createMinorSubresult(RECOMPUTE); result.addParams(new String[] { "oid", "type" }, oid, type); RepositoryCache.enter(); try { Utils.clearRequestee(task); PrismObject<F> focus = objectResolver.getObject(type, oid, null, task, result).asPrismContainer(); LOGGER.trace("Recomputing {}", focus); LensContext<F> syncContext = contextFactory.createRecomputeContext(focus, task, result); LOGGER.trace("Recomputing {}, context:\n{}", focus, syncContext.debugDump()); clockwork.run(syncContext, task, result); result.computeStatus(); LOGGER.trace("Recomputing of {}: {}", focus, result.getStatus()); result.cleanupResult(); } catch (ExpressionEvaluationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SchemaException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (PolicyViolationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ObjectNotFoundException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ObjectAlreadyExistsException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (CommunicationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ConfigurationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SecurityViolationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (RuntimeException e) { ModelUtils.recordFatalError(result, e); throw e; } finally { RepositoryCache.exit(); } } private void applyDefinitions(Collection<ObjectDelta<? extends ObjectType>> deltas, ModelExecuteOptions options, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { for(ObjectDelta<? extends ObjectType> delta: deltas) { Class<? extends ObjectType> type = delta.getObjectTypeClass(); if (delta.hasCompleteDefinition()) { continue; } if (type == ResourceType.class || ShadowType.class.isAssignableFrom(type)) { try { provisioning.applyDefinition(delta, result); } catch (SchemaException e) { if (ModelExecuteOptions.isRaw(options)) { ModelUtils.recordPartialError(result, e); // just go on, this is raw, we need to continue even without complete schema } else { ModelUtils.recordFatalError(result, e); throw e; } } catch (ObjectNotFoundException e) { if (ModelExecuteOptions.isRaw(options)) { ModelUtils.recordPartialError(result, e); // just go on, this is raw, we need to continue even without complete schema } else { ModelUtils.recordFatalError(result, e); throw e; } } catch (CommunicationException e) { if (ModelExecuteOptions.isRaw(options)) { ModelUtils.recordPartialError(result, e); // just go on, this is raw, we need to continue even without complete schema } else { ModelUtils.recordFatalError(result, e); throw e; } } catch (ConfigurationException e) { if (ModelExecuteOptions.isRaw(options)) { ModelUtils.recordPartialError(result, e); // just go on, this is raw, we need to continue even without complete schema } else { ModelUtils.recordFatalError(result, e); throw e; } } } else { PrismObjectDefinition objDef = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(delta.getObjectTypeClass()); if (objDef == null) { throw new SchemaException("No definition for delta object type class: " + delta.getObjectTypeClass()); } delta.applyDefinition(objDef); } } } // private void encrypt(Collection<ObjectDelta<? extends ObjectType>> deltas, ModelExecuteOptions options, // OperationResult result) { // // Encrypt values even before we log anything. We want to avoid showing unencrypted values in the logfiles // if (!ModelExecuteOptions.isNoCrypt(options)) { // for(ObjectDelta<? extends ObjectType> delta: deltas) { // try { // CryptoUtil.encryptValues(protector, delta); // } catch (EncryptionException e) { // result.recordFatalError(e); // throw new SystemException(e.getMessage(), e); // } // } // } // } /* (non-Javadoc) * @see com.evolveum.midpoint.model.api.ModelInteractionService#previewChanges(com.evolveum.midpoint.prism.delta.ObjectDelta, com.evolveum.midpoint.schema.result.OperationResult) */ @Override public <F extends ObjectType> ModelContext<F> previewChanges( Collection<ObjectDelta<? extends ObjectType>> deltas, ModelExecuteOptions options, Task task, OperationResult parentResult) throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Preview changes input:\n{}", DebugUtil.debugDump(deltas)); } int size = 0; if (deltas != null) { size = deltas.size(); } Collection<ObjectDelta<? extends ObjectType>> clonedDeltas = new ArrayList<ObjectDelta<? extends ObjectType>>(size); if (deltas != null) { for (ObjectDelta delta : deltas){ clonedDeltas.add(delta.clone()); } } OperationResult result = parentResult.createSubresult(PREVIEW_CHANGES); LensContext<F> context = null; try { //used cloned deltas instead of origin deltas, because some of the values should be lost later.. context = contextFactory.createContext(clonedDeltas, options, task, result); // context.setOptions(options); if (LOGGER.isDebugEnabled()) { LOGGER.trace("Preview changes context:\n{}", context.debugDump()); } projector.projectAllWaves(context, "preview", task, result); context.distributeResource(); } catch (ConfigurationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SecurityViolationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (CommunicationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ObjectNotFoundException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SchemaException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ObjectAlreadyExistsException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ExpressionEvaluationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (PolicyViolationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (RuntimeException e) { ModelUtils.recordFatalError(result, e); throw e; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Preview changes output:\n{}", context.debugDump()); } result.computeStatus(); result.cleanupResult(); return context; } @Override public <O extends ObjectType> PrismObjectDefinition<O> getEditObjectDefinition(PrismObject<O> object, AuthorizationPhaseType phase, OperationResult parentResult) throws SchemaException, ConfigurationException, ObjectNotFoundException { OperationResult result = parentResult.createMinorSubresult(GET_EDIT_OBJECT_DEFINITION); PrismObjectDefinition<O> objectDefinition = object.getDefinition().deepClone(true); // TODO: maybe we need to expose owner resolver in the interface? ObjectSecurityConstraints securityConstraints = securityEnforcer.compileSecurityConstraints(object, null); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Security constrains for {}:\n{}", object, securityConstraints==null?"null":securityConstraints.debugDump()); } if (securityConstraints == null) { // Nothing allowed => everything denied result.setStatus(OperationResultStatus.NOT_APPLICABLE); return null; } ObjectTemplateType objectTemplateType; try { objectTemplateType = schemaTransformer.determineObjectTemplate(object.getCompileTimeClass(), phase, result); } catch (ConfigurationException | ObjectNotFoundException e) { result.recordFatalError(e); throw e; } schemaTransformer.applyObjectTemplateToDefinition(objectDefinition, objectTemplateType, result); schemaTransformer.applySecurityConstraints(objectDefinition, securityConstraints, phase); if (object.canRepresent(ShadowType.class)) { PrismObject<ShadowType> shadow = (PrismObject<ShadowType>)object; String resourceOid = ShadowUtil.getResourceOid(shadow); PrismObject<ResourceType> resource; try { resource = provisioning.getObject(ResourceType.class, resourceOid, null, null, result); } catch (CommunicationException | SecurityViolationException e) { throw new ConfigurationException(e.getMessage(), e); } RefinedObjectClassDefinition refinedObjectClassDefinition = getEditObjectClassDefinition(shadow, resource, phase); objectDefinition.getComplexTypeDefinition().replaceDefinition(ShadowType.F_ATTRIBUTES, refinedObjectClassDefinition.toResourceAttributeContainerDefinition()); } result.computeStatus(); return objectDefinition; } @Override public RefinedObjectClassDefinition getEditObjectClassDefinition(PrismObject<ShadowType> shadow, PrismObject<ResourceType> resource, AuthorizationPhaseType phase) throws SchemaException { // TODO: maybe we need to expose owner resolver in the interface? ObjectSecurityConstraints securityConstraints = securityEnforcer.compileSecurityConstraints(shadow, null); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Security constrains for {}:\n{}", shadow, securityConstraints==null?"null":securityConstraints.debugDump()); } if (securityConstraints == null) { return null; } RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); ShadowType shadowType = shadow.asObjectable(); ShadowKindType kind = shadowType.getKind(); String intent = shadowType.getIntent(); RefinedObjectClassDefinition rocd; if (kind != null) { rocd = refinedSchema.getRefinedDefinition(kind, intent); } else { QName objectClassName = shadowType.getObjectClass(); if (objectClassName == null) { // No data. Fall back to the default rocd = refinedSchema.getRefinedDefinition(ShadowKindType.ACCOUNT, (String)null); } else { rocd = refinedSchema.getRefinedDefinition(objectClassName); } } LayerRefinedObjectClassDefinition layeredROCD = rocd.forLayer(LayerType.PRESENTATION); ItemPath attributesPath = new ItemPath(ShadowType.F_ATTRIBUTES); AuthorizationDecisionType attributesReadDecision = schemaTransformer.computeItemDecision(securityConstraints, attributesPath, ModelAuthorizationAction.READ.getUrl(), securityConstraints.getActionDecision(ModelAuthorizationAction.READ.getUrl(), phase), phase); AuthorizationDecisionType attributesAddDecision = schemaTransformer.computeItemDecision(securityConstraints, attributesPath, ModelAuthorizationAction.ADD.getUrl(), securityConstraints.getActionDecision(ModelAuthorizationAction.ADD.getUrl(), phase), phase); AuthorizationDecisionType attributesModifyDecision = schemaTransformer.computeItemDecision(securityConstraints, attributesPath, ModelAuthorizationAction.MODIFY.getUrl(), securityConstraints.getActionDecision(ModelAuthorizationAction.MODIFY.getUrl(), phase), phase); LOGGER.trace("Attributes container access read:{}, add:{}, modify:{}", new Object[]{attributesReadDecision, attributesAddDecision, attributesModifyDecision}); /* * We are going to modify attribute definitions list. * So let's make a (shallow) clone here, although it is probably not strictly necessary. */ layeredROCD = layeredROCD.clone(); for (LayerRefinedAttributeDefinition rAttrDef: layeredROCD.getAttributeDefinitions()) { ItemPath attributePath = new ItemPath(ShadowType.F_ATTRIBUTES, rAttrDef.getName()); AuthorizationDecisionType attributeReadDecision = schemaTransformer.computeItemDecision(securityConstraints, attributePath, ModelAuthorizationAction.READ.getUrl(), attributesReadDecision, phase); AuthorizationDecisionType attributeAddDecision = schemaTransformer.computeItemDecision(securityConstraints, attributePath, ModelAuthorizationAction.ADD.getUrl(), attributesAddDecision, phase); AuthorizationDecisionType attributeModifyDecision = schemaTransformer.computeItemDecision(securityConstraints, attributePath, ModelAuthorizationAction.MODIFY.getUrl(), attributesModifyDecision, phase); LOGGER.trace("Attribute {} access read:{}, add:{}, modify:{}", new Object[]{rAttrDef.getName(), attributeReadDecision, attributeAddDecision, attributeModifyDecision}); if (attributeReadDecision != AuthorizationDecisionType.ALLOW) { rAttrDef.setOverrideCanRead(false); } if (attributeAddDecision != AuthorizationDecisionType.ALLOW) { rAttrDef.setOverrideCanAdd(false); } if (attributeModifyDecision != AuthorizationDecisionType.ALLOW) { rAttrDef.setOverrideCanModify(false); } } // TODO what about activation and credentials? return layeredROCD; } @Override public Collection<? extends DisplayableValue<String>> getActionUrls() { return Arrays.asList(ModelAuthorizationAction.values()); } @Override public <F extends FocusType> RoleSelectionSpecification getAssignableRoleSpecification(PrismObject<F> focus, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ConfigurationException { OperationResult result = parentResult.createMinorSubresult(GET_ASSIGNABLE_ROLE_SPECIFICATION); RoleSelectionSpecification spec = new RoleSelectionSpecification(); ObjectSecurityConstraints securityConstraints = securityEnforcer.compileSecurityConstraints(focus, null); AuthorizationDecisionType decision = securityConstraints.findItemDecision(new ItemPath(FocusType.F_ASSIGNMENT), ModelAuthorizationAction.MODIFY.getUrl(), AuthorizationPhaseType.REQUEST); if (decision == AuthorizationDecisionType.ALLOW) { getAllRoleTypesSpec(spec, result); result.recordSuccess(); return spec; } if (decision == AuthorizationDecisionType.DENY) { result.recordSuccess(); spec.setNoRoleTypes(); spec.setFilter(NoneFilter.createNone()); return spec; } decision = securityConstraints.getActionDecision(ModelAuthorizationAction.MODIFY.getUrl(), AuthorizationPhaseType.REQUEST); if (decision == AuthorizationDecisionType.ALLOW) { getAllRoleTypesSpec(spec, result); result.recordSuccess(); return spec; } if (decision == AuthorizationDecisionType.DENY) { result.recordSuccess(); spec.setNoRoleTypes(); spec.setFilter(NoneFilter.createNone()); return spec; } try { ObjectFilter filter = securityEnforcer.preProcessObjectFilter(ModelAuthorizationAction.ASSIGN.getUrl(), AuthorizationPhaseType.REQUEST, RoleType.class, focus, AllFilter.createAll()); LOGGER.trace("assignableRoleSpec filter: {}", filter); spec.setFilter(filter); if (filter instanceof NoneFilter) { result.recordSuccess(); spec.setNoRoleTypes(); return spec; } else if (filter == null || filter instanceof AllFilter) { getAllRoleTypesSpec(spec, result); result.recordSuccess(); return spec; } else if (filter instanceof OrFilter) { for (ObjectFilter subfilter: ((OrFilter)filter).getConditions()) { DisplayableValue<String> roleTypeDval = getRoleSelectionSpec(subfilter); if (roleTypeDval == null) { // This branch of the OR clause does not have any constraint for roleType // therefore all role types are possible (regardless of other branches, this is OR) spec = new RoleSelectionSpecification(); spec.setFilter(filter); getAllRoleTypesSpec(spec, result); result.recordSuccess(); return spec; } else { spec.addRoleType(roleTypeDval); } } } else { DisplayableValue<String> roleTypeDval = getRoleSelectionSpec(filter); if (roleTypeDval == null) { getAllRoleTypesSpec(spec, result); result.recordSuccess(); return spec; } else { spec.addRoleType(roleTypeDval); } } result.recordSuccess(); return spec; } catch (SchemaException | ConfigurationException | ObjectNotFoundException e) { result.recordFatalError(e); throw e; } } private RoleSelectionSpecification getAllRoleTypesSpec(RoleSelectionSpecification spec, OperationResult result) throws ObjectNotFoundException, SchemaException, ConfigurationException { ObjectTemplateType objectTemplateType = schemaTransformer.determineObjectTemplate(RoleType.class, AuthorizationPhaseType.REQUEST, result); if (objectTemplateType == null) { return spec; } for(ObjectTemplateItemDefinitionType itemDef: objectTemplateType.getItem()) { ItemPathType ref = itemDef.getRef(); if (ref == null) { continue; } ItemPath itemPath = ref.getItemPath(); QName itemName = ItemPath.getName(itemPath.first()); if (itemName == null) { continue; } if (QNameUtil.match(RoleType.F_ROLE_TYPE, itemName)) { ObjectReferenceType valueEnumerationRef = itemDef.getValueEnumerationRef(); if (valueEnumerationRef == null || valueEnumerationRef.getOid() == null) { return spec; } Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(LookupTableType.F_ROW, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)); PrismObject<LookupTableType> lookup = cacheRepositoryService.getObject(LookupTableType.class, valueEnumerationRef.getOid(), options, result); for (LookupTableRowType row: lookup.asObjectable().getRow()) { PolyStringType polyLabel = row.getLabel(); String key = row.getKey(); String label = key; if (polyLabel != null) { label = polyLabel.getOrig(); } DisplayableValue<String> roleTypeDval = new DisplayableValueImpl<>(key, label, null); spec.addRoleType(roleTypeDval); } return spec; } } return spec; } private DisplayableValue<String> getRoleSelectionSpec(ObjectFilter filter) throws SchemaException { if (filter instanceof EqualFilter<?>) { return getRoleSelectionSpecEq((EqualFilter)filter); } else if (filter instanceof AndFilter) { for (ObjectFilter subfilter: ((AndFilter)filter).getConditions()) { if (subfilter instanceof EqualFilter<?>) { DisplayableValue<String> roleTypeDval = getRoleSelectionSpecEq((EqualFilter)subfilter); if (roleTypeDval != null) { return roleTypeDval; } } } return null; } else if (filter instanceof TypeFilter) { return getRoleSelectionSpec(((TypeFilter)filter).getFilter()); } else { throw new UnsupportedOperationException("Unexpected filter "+filter); } } private DisplayableValue<String> getRoleSelectionSpecEq(EqualFilter<String> eqFilter) throws SchemaException { if (QNameUtil.match(RoleType.F_ROLE_TYPE,eqFilter.getElementName())) { List<PrismPropertyValue<String>> ppvs = eqFilter.getValues(); if (ppvs.size() > 1) { throw new SchemaException("More than one value in roleType search filter"); } String roleType = ppvs.get(0).getValue(); DisplayableValue<String> roleTypeDval = new DisplayableValueImpl<>(roleType, roleType, null); return roleTypeDval; } return null; } @Override public CredentialsPolicyType getCredentialsPolicy(PrismObject<UserType> user, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { // TODO: check for user membership in an organization (later versions) OperationResult result = parentResult.createMinorSubresult(GET_CREDENTIALS_POLICY); try { PrismObject<SystemConfigurationType> systemConfiguration = getSystemConfiguration(result); if (systemConfiguration == null) { result.recordNotApplicableIfUnknown(); return null; } ObjectReferenceType secPolicyRef = systemConfiguration.asObjectable().getGlobalSecurityPolicyRef(); if (secPolicyRef == null) { result.recordNotApplicableIfUnknown(); return null; } SecurityPolicyType securityPolicyType; securityPolicyType = objectResolver.resolve(secPolicyRef, SecurityPolicyType.class, null, "security policy referred from system configuration", result); if (securityPolicyType == null) { result.recordNotApplicableIfUnknown(); return null; } CredentialsPolicyType credentialsPolicyType = securityPolicyType.getCredentials(); result.recordSuccess(); return credentialsPolicyType; } catch (ObjectNotFoundException | SchemaException e) { result.recordFatalError(e); throw e; } } private PrismObject<SystemConfigurationType> getSystemConfiguration(OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject<SystemConfigurationType> config = cacheRepositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result); if (LOGGER.isTraceEnabled()) { if (config == null) { LOGGER.warn("No system configuration object"); } else { LOGGER.trace("System configuration version read from repo: " + config.getVersion()); } } return config; } @Override public <T extends ObjectType> SearchResultList<PrismObject<T>> searchObjects(Class<T> type, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { Validate.notNull(type, "Object type must not be null."); Validate.notNull(parentResult, "Result type must not be null."); if (query != null) { ModelUtils.validatePaging(query.getPaging()); } RepositoryCache.enter(); GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); ObjectTypes.ObjectManager searchProvider = ObjectTypes.getObjectManagerForClass(type); if (searchProvider == null || searchProvider == ObjectTypes.ObjectManager.MODEL || GetOperationOptions.isRaw(rootOptions)) { searchProvider = ObjectTypes.ObjectManager.REPOSITORY; } OperationResult result = parentResult.createSubresult(SEARCH_OBJECTS); result.addParams(new String[] { "query", "paging", "searchProvider" }, query, (query != null ? query.getPaging() : "undefined"), searchProvider); query = preProcessQuerySecurity(type, query); if (query != null && query.getFilter() != null && query.getFilter() instanceof NoneFilter) { LOGGER.trace("Security denied the search"); result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Denied"); RepositoryCache.exit(); return new SearchResultList(new ArrayList<>()); } SearchResultList<PrismObject<T>> list = null; try { if (query != null){ if (query.getPaging() == null) { LOGGER.trace("Searching objects with null paging (query in TRACE)."); } else { LOGGER.trace("Searching objects from {} to {} ordered {} by {} (query in TRACE).", new Object[] { query.getPaging().getOffset(), query.getPaging().getMaxSize(), query.getPaging().getDirection(), query.getPaging().getOrderBy() }); } } try { if (GetOperationOptions.isRaw(rootOptions)) { // MID-2218 QNameUtil.setTemporarilyTolerateUndeclaredPrefixes(true); } switch (searchProvider) { case REPOSITORY: list = cacheRepositoryService.searchObjects(type, query, options, result); break; case PROVISIONING: list = provisioning.searchObjects(type, query, options, result); break; case TASK_MANAGER: list = taskManager.searchObjects(type, query, options, result); break; case WORKFLOW: throw new UnsupportedOperationException(); default: throw new AssertionError("Unexpected search provider: " + searchProvider); } result.computeStatus(); result.cleanupResult(); } catch (CommunicationException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (ConfigurationException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (ObjectNotFoundException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (SchemaException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (SecurityViolationException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (RuntimeException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } finally { QNameUtil.setTemporarilyTolerateUndeclaredPrefixes(false); if (LOGGER.isTraceEnabled()) { LOGGER.trace(result.dump(false)); } } if (list == null) { list = new SearchResultList(new ArrayList<PrismObject<T>>()); } for (PrismObject<T> object : list) { if (hookRegistry != null) { for (ReadHook hook : hookRegistry.getAllReadHooks()) { hook.invoke(object, options, task, result); } } resolve(object, options, task, result); // resolveNames(object, options, task, result); } } finally { RepositoryCache.exit(); } schemaTransformer.applySchemasAndSecurityToObjects(list, rootOptions, null, task, result); return list; } @Override public <T extends ObjectType> SearchResultMetadata searchObjectsIterative(Class<T> type, ObjectQuery query, final ResultHandler<T> handler, final Collection<SelectorOptions<GetOperationOptions>> options, final Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { Validate.notNull(type, "Object type must not be null."); Validate.notNull(parentResult, "Result type must not be null."); if (query != null) { ModelUtils.validatePaging(query.getPaging()); } RepositoryCache.enter(); final GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); ObjectTypes.ObjectManager searchProvider = ObjectTypes.getObjectManagerForClass(type); if (searchProvider == null || searchProvider == ObjectTypes.ObjectManager.MODEL || GetOperationOptions.isRaw(rootOptions)) { searchProvider = ObjectTypes.ObjectManager.REPOSITORY; } final OperationResult result = parentResult.createSubresult(SEARCH_OBJECTS); result.addParams(new String[] { "query", "paging", "searchProvider" }, query, (query != null ? query.getPaging() : "undefined"), searchProvider); query = preProcessQuerySecurity(type, query); if (query != null && query.getFilter() != null && query.getFilter() instanceof NoneFilter) { LOGGER.trace("Security denied the search"); result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Denied"); RepositoryCache.exit(); return null; } ResultHandler<T> internalHandler = new ResultHandler<T>() { @Override public boolean handle(PrismObject<T> object, OperationResult parentResult) { try { if (hookRegistry != null) { for (ReadHook hook : hookRegistry.getAllReadHooks()) { hook.invoke(object, options, task, result); // TODO result or parentResult??? [med] } } // resolveNames(object, options, task, parentResult); schemaTransformer.applySchemasAndSecurity(object, rootOptions, null, task, parentResult); } catch (SchemaException | ObjectNotFoundException | SecurityViolationException | CommunicationException | ConfigurationException ex) { parentResult.recordFatalError(ex); throw new SystemException(ex.getMessage(), ex); } return handler.handle(object, parentResult); } }; SearchResultMetadata metadata; try { if (query != null){ if (query.getPaging() == null) { LOGGER.trace("Searching objects with null paging (query in TRACE)."); } else { LOGGER.trace("Searching objects from {} to {} ordered {} by {} (query in TRACE).", new Object[] { query.getPaging().getOffset(), query.getPaging().getMaxSize(), query.getPaging().getDirection(), query.getPaging().getOrderBy() }); } } try { switch (searchProvider) { case REPOSITORY: metadata = cacheRepositoryService.searchObjectsIterative(type, query, internalHandler, options, result); break; case PROVISIONING: metadata = provisioning.searchObjectsIterative(type, query, options, internalHandler, result); break; case TASK_MANAGER: throw new UnsupportedOperationException("searchIterative in task manager is currently not supported"); case WORKFLOW: throw new UnsupportedOperationException("searchIterative in task manager is currently not supported"); default: throw new AssertionError("Unexpected search provider: " + searchProvider); } result.computeStatusIfUnknown(); result.cleanupResult(); } catch (CommunicationException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (ConfigurationException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (ObjectNotFoundException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (SchemaException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (SecurityViolationException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } catch (RuntimeException e) { processSearchException(e, rootOptions, searchProvider, result); throw e; } finally { if (LOGGER.isTraceEnabled()) { LOGGER.trace(result.dump(false)); } } } finally { RepositoryCache.exit(); } return metadata; } private void processSearchException(Exception e, GetOperationOptions rootOptions, ObjectTypes.ObjectManager searchProvider, OperationResult result) { String message; switch (searchProvider) { case REPOSITORY: message = "Couldn't search objects in repository"; break; case PROVISIONING: message = "Couldn't search objects in provisioning"; break; case TASK_MANAGER: message = "Couldn't search objects in task manager"; break; case WORKFLOW: message = "Couldn't search objects in workflow module"; break; default: message = "Couldn't search objects"; break; // should not occur } LoggingUtils.logException(LOGGER, message, e); result.recordFatalError(message, e); result.cleanupResult(e); } @Override public <T extends ObjectType> Integer countObjects(Class<T> type, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ConfigurationException, SecurityViolationException, CommunicationException { RepositoryCache.enter(); OperationResult result = parentResult.createMinorSubresult(COUNT_OBJECTS); result.addParams(new String[] { "query", "paging"}, query, (query != null ? query.getPaging() : "undefined")); query = preProcessQuerySecurity(type, query); if (query != null && query.getFilter() != null && query.getFilter() instanceof NoneFilter) { LOGGER.trace("Security denied the search"); result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "Denied"); RepositoryCache.exit(); return 0; } Integer count; try { GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); ObjectTypes.ObjectManager objectManager = ObjectTypes.getObjectManagerForClass(type); if (GetOperationOptions.isRaw(rootOptions) || objectManager == null || objectManager == ObjectTypes.ObjectManager.MODEL) { objectManager = ObjectTypes.ObjectManager.REPOSITORY; } switch (objectManager) { case PROVISIONING: count = provisioning.countObjects(type, query, null, parentResult); break; case REPOSITORY: count = cacheRepositoryService.countObjects(type, query, parentResult); break; case TASK_MANAGER: count = taskManager.countObjects(type, query, parentResult); break; default: throw new AssertionError("Unexpected objectManager: " + objectManager); } } catch (ConfigurationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SecurityViolationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (SchemaException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (ObjectNotFoundException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (CommunicationException e) { ModelUtils.recordFatalError(result, e); throw e; } catch (RuntimeException e) { ModelUtils.recordFatalError(result, e); throw e; } finally { RepositoryCache.exit(); } result.computeStatus(); result.cleanupResult(); return count; } @Override public PrismObject<UserType> findShadowOwner(String accountOid, Task task, OperationResult parentResult) throws ObjectNotFoundException, SecurityViolationException, SchemaException, ConfigurationException { Validate.notEmpty(accountOid, "Account oid must not be null or empty."); Validate.notNull(parentResult, "Result type must not be null."); RepositoryCache.enter(); PrismObject<UserType> user = null; LOGGER.trace("Listing account shadow owner for account with oid {}.", new Object[]{accountOid}); OperationResult result = parentResult.createSubresult(LIST_ACCOUNT_SHADOW_OWNER); result.addParams(new String[] { "accountOid" }, accountOid); try { user = cacheRepositoryService.listAccountShadowOwner(accountOid, result); result.recordSuccess(); } catch (ObjectNotFoundException ex) { LoggingUtils.logException(LOGGER, "Account with oid {} doesn't exists", ex, accountOid); result.recordFatalError("Account with oid '" + accountOid + "' doesn't exists", ex); throw ex; } catch (RuntimeException ex) { LoggingUtils.logException(LOGGER, "Couldn't list account shadow owner from repository" + " for account with oid {}", ex, accountOid); result.recordFatalError("Couldn't list account shadow owner for account with oid '" + accountOid + "'.", ex); throw ex; } catch (Error ex) { LoggingUtils.logException(LOGGER, "Couldn't list account shadow owner from repository" + " for account with oid {}", ex, accountOid); result.recordFatalError("Couldn't list account shadow owner for account with oid '" + accountOid + "'.", ex); throw ex; } finally { if (LOGGER.isTraceEnabled()) { LOGGER.trace(result.dump(false)); } RepositoryCache.exit(); result.cleanupResult(); } if (user != null) { try { schemaTransformer.applySchemasAndSecurity(user, null, null, task, result); } catch (SchemaException | SecurityViolationException | ConfigurationException | ObjectNotFoundException ex) { LoggingUtils.logException(LOGGER, "Couldn't list account shadow owner from repository" + " for account with oid {}", ex, accountOid); result.recordFatalError("Couldn't list account shadow owner for account with oid '" + accountOid + "'.", ex); throw ex; } } return user; } @Override public List<PrismObject<? extends ShadowType>> listResourceObjects(String resourceOid, QName objectClass, ObjectPaging paging, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { Validate.notEmpty(resourceOid, "Resource oid must not be null or empty."); Validate.notNull(objectClass, "Object type must not be null."); Validate.notNull(paging, "Paging must not be null."); Validate.notNull(parentResult, "Result type must not be null."); ModelUtils.validatePaging(paging); RepositoryCache.enter(); List<PrismObject<? extends ShadowType>> list = null; try { LOGGER.trace( "Listing resource objects {} from resource, oid {}, from {} to {} ordered {} by {}.", new Object[] { objectClass, resourceOid, paging.getOffset(), paging.getMaxSize(), paging.getOrderBy(), paging.getDirection() }); OperationResult result = parentResult.createSubresult(LIST_RESOURCE_OBJECTS); result.addParams(new String[] { "resourceOid", "objectType", "paging" }, resourceOid, objectClass, paging); try { list = provisioning.listResourceObjects(resourceOid, objectClass, paging, result); } catch (SchemaException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (CommunicationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (ConfigurationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (SecurityViolationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (ObjectNotFoundException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } result.recordSuccess(); result.cleanupResult(); if (list == null) { list = new ArrayList<PrismObject<? extends ShadowType>>(); } } finally { RepositoryCache.exit(); } return list; } // This returns OperationResult instead of taking it as in/out argument. // This is different // from the other methods. The testResource method is not using // OperationResult to track its own // execution but rather to track the execution of resource tests (that in // fact happen in provisioning). @Override public OperationResult testResource(String resourceOid, Task task) throws ObjectNotFoundException { Validate.notEmpty(resourceOid, "Resource oid must not be null or empty."); RepositoryCache.enter(); LOGGER.trace("Testing resource OID: {}", new Object[]{resourceOid}); OperationResult testResult = null; try { testResult = provisioning.testResource(resourceOid); } catch (ObjectNotFoundException ex) { LOGGER.error("Error testing resource OID: {}: Object not found: {} ", new Object[] { resourceOid, ex.getMessage(), ex }); RepositoryCache.exit(); throw ex; } catch (SystemException ex) { LOGGER.error("Error testing resource OID: {}: Object not found: {} ", new Object[] { resourceOid, ex.getMessage(), ex }); RepositoryCache.exit(); throw ex; } catch (Exception ex) { LOGGER.error("Error testing resource OID: {}: {} ", new Object[] { resourceOid, ex.getMessage(), ex }); RepositoryCache.exit(); throw new SystemException(ex.getMessage(), ex); } if (testResult != null) { LOGGER.debug("Finished testing resource OID: {}, result: {} ", resourceOid, testResult.getStatus()); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Test result:\n{}", testResult.dump(false)); } } else { LOGGER.error("Test resource returned null result"); } RepositoryCache.exit(); return testResult; } // Note: The result is in the task. No need to pass it explicitly @Override public void importFromResource(String resourceOid, QName objectClass, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { Validate.notEmpty(resourceOid, "Resource oid must not be null or empty."); Validate.notNull(objectClass, "Object class must not be null."); Validate.notNull(task, "Task must not be null."); RepositoryCache.enter(); LOGGER.trace("Launching import from resource with oid {} for object class {}.", new Object[]{ resourceOid, objectClass}); OperationResult result = parentResult.createSubresult(IMPORT_ACCOUNTS_FROM_RESOURCE); result.addParam("resourceOid", resourceOid); result.addParam("objectClass", objectClass); result.addArbitraryObjectAsParam("task", task); // TODO: add context to the result // Fetch resource definition from the repo/provisioning ResourceType resource = null; try { resource = getObject(ResourceType.class, resourceOid, null, task, result).asObjectable(); if (resource.getSynchronization() == null || resource.getSynchronization().getObjectSynchronization().isEmpty()) { OperationResult subresult = result.createSubresult(IMPORT_ACCOUNTS_FROM_RESOURCE+".check"); subresult.recordWarning("No synchronization settings in "+resource+", import will probably do nothing"); LOGGER.warn("No synchronization settings in "+resource+", import will probably do nothing"); } else { ObjectSynchronizationType syncType = resource.getSynchronization().getObjectSynchronization().iterator().next(); if (syncType.isEnabled() != null && !syncType.isEnabled()) { OperationResult subresult = result.createSubresult(IMPORT_ACCOUNTS_FROM_RESOURCE+".check"); subresult.recordWarning("Synchronization is disabled for "+resource+", import will probably do nothing"); LOGGER.warn("Synchronization is disabled for "+resource+", import will probably do nothing"); } } result.recordStatus(OperationResultStatus.IN_PROGRESS, "Task running in background"); importAccountsFromResourceTaskHandler.launch(resource, objectClass, task, result); // The launch should switch task to asynchronous. It is in/out, so no // other action is needed if (!task.isAsynchronous()) { result.recordSuccess(); } result.cleanupResult(); } catch (ObjectNotFoundException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (CommunicationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (ConfigurationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (SecurityViolationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (RuntimeException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } finally { RepositoryCache.exit(); } } @Override public void importFromResource(String shadowOid, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, SecurityViolationException { Validate.notNull(shadowOid, "Shadow OID must not be null."); Validate.notNull(task, "Task must not be null."); RepositoryCache.enter(); LOGGER.trace("Launching importing shadow {} from resource.", shadowOid); OperationResult result = parentResult.createSubresult(IMPORT_ACCOUNTS_FROM_RESOURCE); result.addParam(OperationResult.PARAM_OID, shadowOid); result.addArbitraryObjectAsParam("task", task); // TODO: add context to the result try { boolean wasOk = importAccountsFromResourceTaskHandler.importSingleShadow(shadowOid, task, result); if (wasOk) { result.recordSuccess(); } else { // the error should be in the result already, compute should reveal that to the top-level result.computeStatus(); } result.cleanupResult(); } catch (ObjectNotFoundException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (CommunicationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (ConfigurationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (SecurityViolationException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } catch (RuntimeException ex) { ModelUtils.recordFatalError(result, ex); throw ex; } finally { RepositoryCache.exit(); } } @Override public void importObjectsFromFile(File input, ImportOptionsType options, Task task, OperationResult parentResult) throws FileNotFoundException { OperationResult result = parentResult.createSubresult(IMPORT_OBJECTS_FROM_FILE); FileInputStream fis; try { fis = new FileInputStream(input); } catch (FileNotFoundException e) { String msg = "Error reading from file "+input+": "+e.getMessage(); result.recordFatalError(msg, e); throw e; } try { importObjectsFromStream(fis, options, task, parentResult); } catch (RuntimeException e) { result.recordFatalError(e); throw e; } finally { try { fis.close(); } catch (IOException e) { Log.error("Error closing file "+input+": "+e.getMessage(), e); } } result.computeStatus(); } @Override public void importObjectsFromStream(InputStream input, ImportOptionsType options, Task task, OperationResult parentResult) { RepositoryCache.enter(); OperationResult result = parentResult.createSubresult(IMPORT_OBJECTS_FROM_STREAM); result.addParam("options", options); objectImporter.importObjects(input, options, task, result); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Import result:\n{}", result.debugDump()); } // No need to compute status. The validator inside will do it. // result.computeStatus("Couldn't import object from input stream."); RepositoryCache.exit(); result.cleanupResult(); } /* * (non-Javadoc) * * @see * com.evolveum.midpoint.model.api.ModelService#discoverConnectors(com.evolveum * .midpoint.xml.ns._public.common.common_1.ConnectorHostType, * com.evolveum.midpoint.common.result.OperationResult) */ @Override public Set<ConnectorType> discoverConnectors(ConnectorHostType hostType, Task task, OperationResult parentResult) throws CommunicationException, SecurityViolationException, SchemaException, ConfigurationException, ObjectNotFoundException { RepositoryCache.enter(); OperationResult result = parentResult.createSubresult(DISCOVER_CONNECTORS); Set<ConnectorType> discoverConnectors; try { discoverConnectors = provisioning.discoverConnectors(hostType, result); } catch (CommunicationException e) { result.recordFatalError(e.getMessage(), e); RepositoryCache.exit(); throw e; } schemaTransformer.applySchemasAndSecurityToObjectTypes(discoverConnectors, null, null, task, result); result.computeStatus("Connector discovery failed"); RepositoryCache.exit(); result.cleanupResult(); return discoverConnectors; } /* * (non-Javadoc) * * @see * com.evolveum.midpoint.model.api.ModelService#initialize(com.evolveum. * midpoint.common.result.OperationResult) */ @Override public void postInit(OperationResult parentResult) { Utils.clearSystemConfigurationCache(); // necessary for testing situations where we re-import different system configurations with the same version (on system init) RepositoryCache.enter(); OperationResult result = parentResult.createSubresult(POST_INIT); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ModelController.class); securityEnforcer.setUserProfileService(userProfileService); // TODO: initialize repository PrismObject<SystemConfigurationType> systemConfiguration; try { systemConfiguration = getSystemConfiguration(result); systemConfigurationHandler.postInit(systemConfiguration, result); } catch (ObjectNotFoundException e) { String message = "No system configuration found, skipping application of initial system settings"; LOGGER.error(message + ": " + e.getMessage(), e); result.recordWarning(message, e); } catch (SchemaException e) { String message = "Schema error in system configuration, skipping application of initial system settings"; LOGGER.error(message + ": " + e.getMessage(), e); result.recordWarning(message, e); } taskManager.postInit(result); // Initialize provisioning provisioning.postInit(result); if (result.isUnknown()) { result.computeStatus(); } RepositoryCache.exit(); result.cleanupResult(); } @Override public <F extends ObjectType> ModelContext<F> unwrapModelContext(LensContextType wrappedContext, OperationResult result) throws SchemaException, ConfigurationException, ObjectNotFoundException, CommunicationException { return LensContext.fromLensContextType(wrappedContext, prismContext, provisioning, result); } private <O extends ObjectType> ObjectQuery preProcessQuerySecurity(Class<O> objectType, ObjectQuery origQuery) throws SchemaException { ObjectFilter origFilter = null; if (origQuery != null) { origFilter = origQuery.getFilter(); } ObjectFilter secFilter = securityEnforcer.preProcessObjectFilter(ModelAuthorizationAction.READ.getUrl(), null, objectType, null, origFilter); if (origQuery != null) { origQuery.setFilter(secFilter); return origQuery; } else if (secFilter == null) { return null; } else { ObjectQuery objectQuery = new ObjectQuery(); objectQuery.setFilter(secFilter); return objectQuery; } } //region Task-related operations @Override public boolean suspendTasks(Collection<String> taskOids, long waitForStop, OperationResult parentResult) throws SecurityViolationException, ObjectNotFoundException, SchemaException { authorizeTaskCollectionOperation(ModelAuthorizationAction.SUSPEND_TASK, taskOids, parentResult); return taskManager.suspendTasks(taskOids, waitForStop, parentResult); } @Override public void suspendAndDeleteTasks(Collection<String> taskOids, long waitForStop, boolean alsoSubtasks, OperationResult parentResult) throws SecurityViolationException, ObjectNotFoundException, SchemaException { authorizeTaskCollectionOperation(ModelAuthorizationAction.DELETE, taskOids, parentResult); taskManager.suspendAndDeleteTasks(taskOids, waitForStop, alsoSubtasks, parentResult); } @Override public void resumeTasks(Collection<String> taskOids, OperationResult parentResult) throws SecurityViolationException, ObjectNotFoundException, SchemaException { authorizeTaskCollectionOperation(ModelAuthorizationAction.RESUME_TASK, taskOids, parentResult); taskManager.resumeTasks(taskOids, parentResult); } @Override public void scheduleTasksNow(Collection<String> taskOids, OperationResult parentResult) throws SecurityViolationException, ObjectNotFoundException, SchemaException { authorizeTaskCollectionOperation(ModelAuthorizationAction.RUN_TASK_IMMEDIATELY, taskOids, parentResult); taskManager.scheduleTasksNow(taskOids, parentResult); } @Override public PrismObject<TaskType> getTaskByIdentifier(String identifier, Collection<SelectorOptions<GetOperationOptions>> options, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ConfigurationException, SecurityViolationException { PrismObject<TaskType> task = taskManager.getTaskTypeByIdentifier(identifier, options, parentResult); GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); schemaTransformer.applySchemasAndSecurity(task, rootOptions, null, null, parentResult); return task; } @Override public boolean deactivateServiceThreads(long timeToWait, OperationResult parentResult) throws SchemaException, SecurityViolationException { securityEnforcer.authorize(ModelAuthorizationAction.STOP_SERVICE_THREADS.getUrl(), null, null, null, null, null, parentResult); return taskManager.deactivateServiceThreads(timeToWait, parentResult); } @Override public void reactivateServiceThreads(OperationResult parentResult) throws SchemaException, SecurityViolationException { securityEnforcer.authorize(ModelAuthorizationAction.START_SERVICE_THREADS.getUrl(), null, null, null, null, null, parentResult); taskManager.reactivateServiceThreads(parentResult); } @Override public boolean getServiceThreadsActivationState() { return taskManager.getServiceThreadsActivationState(); } @Override public void stopSchedulers(Collection<String> nodeIdentifiers, OperationResult parentResult) throws SecurityViolationException, ObjectNotFoundException, SchemaException { authorizeNodeCollectionOperation(ModelAuthorizationAction.STOP_TASK_SCHEDULER, nodeIdentifiers, parentResult); taskManager.stopSchedulers(nodeIdentifiers, parentResult); } @Override public boolean stopSchedulersAndTasks(Collection<String> nodeIdentifiers, long waitTime, OperationResult parentResult) throws SecurityViolationException, ObjectNotFoundException, SchemaException { authorizeNodeCollectionOperation(ModelAuthorizationAction.STOP_TASK_SCHEDULER, nodeIdentifiers, parentResult); return taskManager.stopSchedulersAndTasks(nodeIdentifiers, waitTime, parentResult); } @Override public void startSchedulers(Collection<String> nodeIdentifiers, OperationResult parentResult) throws SecurityViolationException, ObjectNotFoundException, SchemaException { authorizeNodeCollectionOperation(ModelAuthorizationAction.START_TASK_SCHEDULER, nodeIdentifiers, parentResult); taskManager.startSchedulers(nodeIdentifiers, parentResult); } @Override public void synchronizeTasks(OperationResult parentResult) throws SchemaException, SecurityViolationException { securityEnforcer.authorize(ModelAuthorizationAction.SYNCHRONIZE_TASKS.getUrl(), null, null, null, null, null, parentResult); taskManager.synchronizeTasks(parentResult); } @Override public List<String> getAllTaskCategories() { return taskManager.getAllTaskCategories(); } @Override public String getHandlerUriForCategory(String category) { return taskManager.getHandlerUriForCategory(category); } private void authorizeTaskCollectionOperation(ModelAuthorizationAction action, Collection<String> oids, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, SecurityViolationException { if (securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_ALL_URL, null, null, null, null, null)) { return; } for (String oid : oids) { PrismObject existingObject = null; try { existingObject = cacheRepositoryService.getObject(TaskType.class, oid, null, parentResult); } catch (ObjectNotFoundException|SchemaException e) { throw e; } securityEnforcer.authorize(action.getUrl(), null, existingObject, null, null, null, parentResult); } } private void authorizeNodeCollectionOperation(ModelAuthorizationAction action, Collection<String> identifiers, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, SecurityViolationException { if (securityEnforcer.isAuthorized(AuthorizationConstants.AUTZ_ALL_URL, null, null, null, null, null)) { return; } for (String identifier : identifiers) { PrismObject existingObject = null; try { ObjectQuery q = ObjectQueryUtil.createNameQuery(NodeType.class, prismContext, identifier); List<PrismObject<NodeType>> nodes = cacheRepositoryService.searchObjects(NodeType.class, q, null, parentResult); if (nodes.isEmpty()) { throw new ObjectNotFoundException("Node with identifier '" + identifier + "' couldn't be found."); } else if (nodes.size() > 1) { throw new SystemException("Multiple nodes with identifier '" + identifier + "'"); } existingObject = nodes.get(0); } catch (ObjectNotFoundException|SchemaException e) { throw e; } securityEnforcer.authorize(action.getUrl(), null, existingObject, null, null, null, parentResult); } } //endregion //region Workflow-related operations @Override public int countWorkItemsRelatedToUser(String userOid, boolean assigned, OperationResult parentResult) throws SchemaException, ObjectNotFoundException { return workflowManager.countWorkItemsRelatedToUser(userOid, assigned, parentResult); } @Override public List<WorkItemType> listWorkItemsRelatedToUser(String userOid, boolean assigned, int first, int count, OperationResult parentResult) throws SchemaException, ObjectNotFoundException { return workflowManager.listWorkItemsRelatedToUser(userOid, assigned, first, count, parentResult); } @Override public WorkItemType getWorkItemDetailsById(String workItemId, OperationResult parentResult) throws ObjectNotFoundException { return workflowManager.getWorkItemDetailsById(workItemId, parentResult); } @Override public int countProcessInstancesRelatedToUser(String userOid, boolean requestedBy, boolean requestedFor, boolean finished, OperationResult parentResult) { return workflowManager.countProcessInstancesRelatedToUser(userOid, requestedBy, requestedFor, finished, parentResult); } @Override public List<WfProcessInstanceType> listProcessInstancesRelatedToUser(String userOid, boolean requestedBy, boolean requestedFor, boolean finished, int first, int count, OperationResult parentResult) { return workflowManager.listProcessInstancesRelatedToUser(userOid, requestedBy, requestedFor, finished, first, count, parentResult); } @Override public WfProcessInstanceType getProcessInstanceByWorkItemId(String workItemId, OperationResult parentResult) throws ObjectNotFoundException { return workflowManager.getProcessInstanceByWorkItemId(workItemId, parentResult); } @Override public WfProcessInstanceType getProcessInstanceById(String instanceId, boolean historic, boolean getWorkItems, OperationResult parentResult) throws ObjectNotFoundException { return workflowManager.getProcessInstanceById(instanceId, historic, getWorkItems, parentResult); } @Override public void approveOrRejectWorkItem(String workItemId, boolean decision, OperationResult parentResult) { workflowManager.approveOrRejectWorkItem(workItemId, decision, parentResult); } @Override public void approveOrRejectWorkItemWithDetails(String workItemId, PrismObject specific, boolean decision, OperationResult result) { workflowManager.approveOrRejectWorkItemWithDetails(workItemId, specific, decision, result); } @Override public void completeWorkItemWithDetails(String workItemId, PrismObject specific, String decision, OperationResult parentResult) { workflowManager.completeWorkItemWithDetails(workItemId, specific, decision, parentResult); } @Override public void stopProcessInstance(String instanceId, String username, OperationResult parentResult) { workflowManager.stopProcessInstance(instanceId, username, parentResult); } @Override public void deleteProcessInstance(String instanceId, OperationResult parentResult) { workflowManager.deleteProcessInstance(instanceId, parentResult); } @Override public void claimWorkItem(String workItemId, OperationResult parentResult) { workflowManager.claimWorkItem(workItemId, parentResult); } @Override public void releaseWorkItem(String workItemId, OperationResult parentResult) { workflowManager.releaseWorkItem(workItemId, parentResult); } //endregion //region Scripting (bulk actions) @Override public void evaluateExpressionInBackground(QName objectType, ObjectFilter filter, String actionName, Task task, OperationResult parentResult) throws SchemaException, SecurityViolationException { checkScriptingAuthorization(parentResult); scriptingExpressionEvaluator.evaluateExpressionInBackground(objectType, filter, actionName, task, parentResult); } @Override public void evaluateExpressionInBackground(ScriptingExpressionType expression, Task task, OperationResult parentResult) throws SchemaException, SecurityViolationException { checkScriptingAuthorization(parentResult); scriptingExpressionEvaluator.evaluateExpressionInBackground(expression, task, parentResult); } @Override public ScriptExecutionResult evaluateExpression(ScriptingExpressionType expression, Task task, OperationResult result) throws ScriptExecutionException, SchemaException, SecurityViolationException { checkScriptingAuthorization(result); ExecutionContext executionContext = scriptingExpressionEvaluator.evaluateExpression(expression, task, result); return executionContext.toExecutionResult(); } private void checkScriptingAuthorization(OperationResult parentResult) throws SchemaException, SecurityViolationException { securityEnforcer.authorize(ModelAuthorizationAction.EXECUTE_SCRIPT.getUrl(), null, null, null, null, null, parentResult); } //endregion //region Certification // TODO implement these // for now, please use CertificationManager directly @Override public AccessCertificationCampaignType createCampaign(AccessCertificationDefinitionType certificationDefinition, AccessCertificationCampaignType campaign, Task task, OperationResult parentResult) throws SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException, ObjectAlreadyExistsException, PolicyViolationException { return null; } @Override public void startStage(AccessCertificationCampaignType campaign, Task task, OperationResult parentResult) throws SchemaException, SecurityViolationException, ConfigurationException, ObjectNotFoundException, CommunicationException, ExpressionEvaluationException, ObjectAlreadyExistsException, PolicyViolationException { } @Override public List<AccessCertificationCaseType> searchCases(String campaignOid, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, CommunicationException { return null; } @Override public List<AccessCertificationCaseType> searchDecisions(String campaignOid, String reviewerOid, ObjectQuery query, Collection<SelectorOptions<GetOperationOptions>> options, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, CommunicationException { return null; } @Override public void recordReviewerDecision(String campaignOid, long caseId, AccessCertificationDecisionType decision, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, CommunicationException, ObjectAlreadyExistsException { } //endregion }
apache-2.0
w2ogroup/incubator-streams
streams-runtimes/streams-runtime-threaded/src/main/java/org/apache/streams/threaded/tasks/StreamsProviderTask.java
7499
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.streams.threaded.tasks; import org.apache.streams.threaded.controller.SimpleCondition; import org.apache.streams.threaded.controller.ThreadingController; import org.apache.streams.threaded.controller.ThreadingControllerCallback; import org.apache.streams.core.StreamsDatum; import org.apache.streams.core.StreamsProvider; import org.apache.streams.core.StreamsResultSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; public class StreamsProviderTask extends BaseStreamsTask implements Runnable { private final static Logger LOGGER = LoggerFactory.getLogger(StreamsProviderTask.class); private StreamsProvider provider; private final Type type; private final AtomicInteger outStanding = new AtomicInteger(0); private final AtomicBoolean keepRunning = new AtomicBoolean(true); private final Condition lock = new SimpleCondition(); public static enum Type { PERPETUAL, READ_CURRENT, READ_NEW, READ_RANGE } private static final int TIMEOUT = 100000000; public StreamsProviderTask(ThreadingController threadingController, String id, Map<String, Object> config, StreamsProvider provider, Type type) { super(threadingController, id, config, provider); this.provider = provider; this.type = type; } public void shutDown() { this.keepRunning.set(false); } public boolean isRunning() { return this.keepRunning.get() || this.outStanding.get() > 0; } public Condition getLock() { return this.lock; } @Override public void run() { try { // TODO allow for configuration objects StreamsResultSet resultSet = null; provider.startStream(); switch (this.type) { case PERPETUAL: LOGGER.info("Provider is running: {}", provider.isRunning()); int zeros = 0; while (this.keepRunning.get()) { resultSet = provider.readCurrent(); if (resultSet.size() == 0) { zeros++; } else { zeros = 0; } flushResults(resultSet); // the way this works needs to change... if (zeros > TIMEOUT) { this.keepRunning.set(false); } safeQuickRest(10); } break; case READ_CURRENT: resultSet = this.provider.readCurrent(); break; case READ_NEW: case READ_RANGE: default: throw new RuntimeException("Type has not been added to StreamsProviderTask."); } if(resultSet != null && resultSet.getQueue() != null) { if(provider == null) { throw new RuntimeException("Unknown Error - Provider is equal to Null."); } while((provider.isRunning() && this.keepRunning.get()) || resultSet.getQueue().size() > 0) { // Is there anything to do? if (resultSet.getQueue().isEmpty()) { // Check to see if they are going to give us a new streams result-set. StreamsResultSet streamsResultSet = this.provider.readCurrent(); // They decided to give us a new result set... nifty! if(resultSet!= streamsResultSet) { resultSet = streamsResultSet; } safeQuickRest(1); } else { flushResults(resultSet); // then work } } } } catch (Throwable e) { LOGGER.error("There was an unknown error while attempting to read from the provider. This provider cannot continue with this exception."); LOGGER.error("The stream will continue running, but not with this provider."); LOGGER.error("Exception: {}", e); } finally { this.keepRunning.set(false); checkLockSignal(); } LOGGER.debug("Finished Provider: {}", this.getId()); } public void flushResults(StreamsResultSet streamsResultSet) { try { StreamsDatum datum; while (!streamsResultSet.getQueue().isEmpty() && (datum = streamsResultSet.getQueue().poll()) != null) { /** * This is meant to be a hard exit from the system. If we are running * and this flag gets set to false, we are to exit immediately and * abandon anything that is in this queue. The remaining processors * will shutdown gracefully once they have depleted their queue */ if (!this.keepRunning.get()) { break; } workMe(datum); } } catch(Throwable e) { e.printStackTrace(); LOGGER.warn("Unknown problem reading the queue, no datums affected: {}", e.getMessage()); } } private void workMe(final StreamsDatum datum) { outStanding.incrementAndGet(); getThreadingController().execute(new Runnable() { @Override public void run() { sendToChildren(datum); } }, new ThreadingControllerCallback() { @Override public void onSuccess(Object o) { outStanding.decrementAndGet(); checkLockSignal(); } @Override public void onFailure(Throwable t) { outStanding.decrementAndGet(); checkLockSignal(); } }); } private void checkLockSignal() { if(this.outStanding.get() == 0 && !this.keepRunning.get()) { this.lock.signalAll(); } } @Override protected Collection<StreamsDatum> processInternal(StreamsDatum datum) { return null; } protected void safeQuickRest(int waitTime) { // The queue is empty, we might as well sleep. Thread.yield(); try { Thread.sleep(waitTime); } catch (InterruptedException ie) { // No Operation } Thread.yield(); } }
apache-2.0
gavin2lee/incubator
docs/sourcecodes/OpenBridge-base/ob-framework/src/main/java/com/harmazing/framework/util/TemplateUtil.java
2202
package com.harmazing.framework.util; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateNotFoundException; public class TemplateUtil { private static Configuration cfg; private static StringTemplateLoader loader = new StringTemplateLoader(); public static Configuration getConfiguration() { if (cfg == null) { cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setTemplateLoader(loader); } return cfg; } public static Template getTemplate(String name) throws IOException { return getConfiguration().getTemplate(name); } public static Template buildTemplate(String templateStr) throws IOException { String name = Md5Util.getMD5String(templateStr); Template template = null; try { template = getTemplate(name); } catch (TemplateNotFoundException e) { template = null; } if (template != null) { return template; } else { return new Template(name, templateStr, cfg); } } public static String getOutputByTemplate(String templateStr, Map<String, Object> model) throws IOException { Template template = buildTemplate(templateStr); StringWriter out = new StringWriter(); try { template.process(model, out); } catch (TemplateException e) { throw new IOException(e); } return out.toString(); } public static String getOutputByName(String name, Map<String, Object> model) throws IOException { Template template = getTemplate(name); StringWriter out = new StringWriter(); try { template.process(model, out); } catch (TemplateException e) { throw new IOException(e); } return out.toString(); } public static void main(String[] srgs) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("ss", "aaaaaa"); System.out.println(getOutputByTemplate("ss${ss}ss", map)); System.out.println(getOutputByTemplate("ss${ss}ss", map)); } }
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202108/MobileApplicationActionError.java
2441
// 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 // // 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.api.ads.admanager.jaxws.v202108; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * Lists all error reasons associated with performing actions on {@link MobileApplication} objects. * * * <p>Java class for MobileApplicationActionError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="MobileApplicationActionError"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v202108}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://www.google.com/apis/ads/publisher/v202108}MobileApplicationActionError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "MobileApplicationActionError", propOrder = { "reason" }) public class MobileApplicationActionError extends ApiError { @XmlSchemaType(name = "string") protected MobileApplicationActionErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link MobileApplicationActionErrorReason } * */ public MobileApplicationActionErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link MobileApplicationActionErrorReason } * */ public void setReason(MobileApplicationActionErrorReason value) { this.reason = value; } }
apache-2.0
toff63/eip
src/main/java/net/francesbagual/github/eip/pattern/message/Message.java
254
package net.francesbagual.github.eip.pattern.message; import java.util.Map; /** * * All messages should share a common type, have a header and a body. * */ public interface Message<T> { public Map<String, Object> headers(); public T body(); }
apache-2.0
ibissource/iaf
core/src/main/java/nl/nn/adapterframework/statistics/jdbc/StatGroupTable.java
3638
/* Copyright 2013 Nationale-Nederlanden 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 nl.nn.adapterframework.statistics.jdbc; import java.sql.Connection; import nl.nn.adapterframework.jdbc.JdbcException; import nl.nn.adapterframework.util.JdbcUtil; import nl.nn.adapterframework.util.LogUtil; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; /** * Utility class to populate and reference groups used in statistics. * * @author Gerrit van Brakel * @since 4.9.8 */ public class StatGroupTable { protected Logger log = LogUtil.getLogger(this); private String selectRootByNameQuery; private String selectByNameQuery; private String selectByTypeQuery; private String selectByNameAndTypeQuery; private String selectNextValueQuery; private String insertQuery; private String insertRootQuery; public StatGroupTable(String tableName, String keyColumn, String parentKeyColumn, String instanceKeyColumn, String nameColumn, String typeColumn, String sequence) { super(); createQueries(tableName,keyColumn,parentKeyColumn,instanceKeyColumn,nameColumn,typeColumn,sequence); } private void createQueries(String tableName, String keyColumn, String parentKeyColumn, String instanceKeyColumn, String nameColumn, String typeColumn, String sequence) { selectRootByNameQuery="SELECT "+keyColumn+" FROM "+tableName+" WHERE "+parentKeyColumn+" IS NULL AND "+instanceKeyColumn+"=? AND "+nameColumn+"=?"; selectByNameQuery="SELECT "+keyColumn+" FROM "+tableName+" WHERE "+parentKeyColumn+"=? AND "+instanceKeyColumn+"=? AND "+nameColumn+"=?"; selectByTypeQuery="SELECT "+keyColumn+" FROM "+tableName+" WHERE "+parentKeyColumn+"=? AND "+instanceKeyColumn+"=? AND "+typeColumn+"=?"; selectByNameAndTypeQuery="SELECT "+keyColumn+" FROM "+tableName+" WHERE "+parentKeyColumn+"=? AND "+instanceKeyColumn+"=? AND "+nameColumn+"=? AND "+typeColumn+"=?"; selectNextValueQuery="SELECT "+sequence+".nextval FROM DUAL"; insertQuery="INSERT INTO "+tableName+"("+keyColumn+","+parentKeyColumn+","+instanceKeyColumn+","+nameColumn+","+typeColumn+") VALUES (?,?,?,?,?)"; insertRootQuery="INSERT INTO "+tableName+"("+keyColumn+","+instanceKeyColumn+","+nameColumn+","+typeColumn+") VALUES (?,?,?,?)"; } public int findOrInsert(Connection connection, int parentKey, int instanceKey, String name, String type) throws JdbcException { int result; if (parentKey<0) { result = JdbcUtil.executeIntQuery(connection,selectRootByNameQuery,instanceKey,name); } else if (StringUtils.isNotEmpty(name)) { result = JdbcUtil.executeIntQuery(connection,selectByNameAndTypeQuery,parentKey,instanceKey,name,type); } else { result = JdbcUtil.executeIntQuery(connection,selectByTypeQuery,parentKey,instanceKey,type); } if (result>=0) { return result; } result = JdbcUtil.executeIntQuery(connection,selectNextValueQuery); if (parentKey<0) { JdbcUtil.executeStatement(connection,insertRootQuery,instanceKey,name); } else { JdbcUtil.executeStatement(connection,insertQuery,result,parentKey,instanceKey,name==null?"":name,type); } return result; } }
apache-2.0
hansenji/PocketBus
sample/src/main/java/pocketbus/sample/Bar.java
226
package pocketbus.sample; public class Bar implements Foo { public Baz<Qux> getRegistrar(Qux target) { return null; } @Override public <T> Baz<T> getRegistrar(T target) { return null; } }
apache-2.0
alonerocky/PicasaPlus
app/src/main/java/com/google/api/client/googleapis/auth/oauth/GoogleOAuthGetAccessToken.java
2430
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.auth.oauth; import com.google.api.client.auth.oauth.OAuthParameters; import com.google.api.client.auth.oauth.OAuthCredentialsResponse; import com.google.api.client.auth.oauth.OAuthGetAccessToken; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpTransport; import java.io.IOException; /** * Generic Google OAuth 1.0a URL to request to exchange the temporary * credentials token (or "request token") for a long-lived credentials token (or * "access token") from the Google Authorization server. * <p> * Use {@link #execute()} to execute the request. The long-lived access token * acquired with this request is found in {@link OAuthCredentialsResponse#token} * . This token must be stored. It may then be used to authorize HTTP requests * to protected resources in Google services by setting the * {@link OAuthParameters#token}, and invoking * {@link OAuthParameters#signRequestsUsingAuthorizationHeader(HttpTransport)}. * <p> * To revoke the stored access token, use {@link #revokeAccessToken}. * * @since 2.2 * @author Yaniv Inbar */ public final class GoogleOAuthGetAccessToken extends OAuthGetAccessToken { public GoogleOAuthGetAccessToken() { super("https://www.google.com/accounts/OAuthGetAccessToken"); } /** * Revokes the long-lived access token. * * @param parameters OAuth parameters * @throws IOException I/O exception */ public static void revokeAccessToken(OAuthParameters parameters) throws IOException { HttpTransport transport = new HttpTransport(); parameters.signRequestsUsingAuthorizationHeader(transport); HttpRequest request = transport.buildGetRequest(); request.setUrl("https://www.google.com/accounts/AuthSubRevokeToken"); request.execute().ignore(); } }
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202102/MobileApplicationServiceInterfacecreateMobileApplicationsResponse.java
2646
// 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 // // 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.api.ads.admanager.jaxws.v202102; 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.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for createMobileApplicationsResponse element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="createMobileApplicationsResponse"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="rval" type="{https://www.google.com/apis/ads/publisher/v202102}MobileApplication" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "rval" }) @XmlRootElement(name = "createMobileApplicationsResponse") public class MobileApplicationServiceInterfacecreateMobileApplicationsResponse { protected List<MobileApplication> rval; /** * Gets the value of the rval 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 rval property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRval().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MobileApplication } * * */ public List<MobileApplication> getRval() { if (rval == null) { rval = new ArrayList<MobileApplication>(); } return this.rval; } }
apache-2.0
MFlisar/PagerManager
src/com/michaelflisar/pagermanager/IPagerAdapterCallback.java
469
package com.michaelflisar.pagermanager; import android.support.v4.app.Fragment; import com.astuetz.viewpager.extensions.PagerSlidingTabStrip.TabBackgroundProvider; import com.astuetz.viewpager.extensions.PagerSlidingTabStrip.TabCustomViewProvider; public interface IPagerAdapterCallback<Frag extends Fragment & IPagerFragment> extends TabCustomViewProvider, TabBackgroundProvider { public Frag createFragment(int pos); public Frag tryGetFragment(int pos); }
apache-2.0
welterde/ewok
com/planet_ink/coffee_mud/Libraries/EnglishParser.java
62275
package com.planet_ink.coffee_mud.Libraries; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.MoneyLibrary.MoneyDenomination; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.io.IOException; import java.util.*; import java.util.regex.*; /* Copyright 2000-2010 Bo Zimmerman 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. */ @SuppressWarnings("unchecked") public class EnglishParser extends StdLibrary implements EnglishParsing { public String ID(){return "EnglishParser";} private final static String[] articles={"a","an","all of","some one","a pair of","one of","all","the","some"}; public static boolean[] PUNCTUATION_TABLE=null; public final static char[] ALL_CHRS="ALL".toCharArray(); public boolean isAnArticle(String s) { for(int a=0;a<articles.length;a++) if(s.toLowerCase().equals(articles[a])) return true; return false; } public String cleanArticles(String s) { boolean didSomething=true; while(didSomething) { didSomething=false; String lowStr=s.toLowerCase(); for(int a=0;a<articles.length;a++) if(lowStr.startsWith(articles[a]+" ")) return s.substring(articles[a].length()+1); } return s; } public String startWithAorAn(String str) { if((str==null)||(str.length()==0)) return str; String uppStr=str.toUpperCase(); if((!uppStr.startsWith("A ")) &&(!uppStr.startsWith("AN ")) &&(!uppStr.startsWith("THE ")) &&(!uppStr.startsWith("SOME "))) { if("AEIOU".indexOf(uppStr.charAt(0))>=0) return "an "+str; return "a "+str; } return str; } public String insertUnColoredAdjective(String str, String adjective) { if(str.length()==0) return str; str=CMStrings.removeColors(str.trim()); String uppStr=str.toUpperCase(); if((uppStr.startsWith("A ")) ||(uppStr.startsWith("AN "))) { if("aeiouAEIOU".indexOf(adjective.charAt(0))>=0) return "an "+adjective+" "+str.substring(2).trim(); return "a "+adjective+" "+str.substring(2).trim(); } if((!uppStr.startsWith("THE ")) &&(!uppStr.startsWith("SOME "))) { if("aeiouAEIOU".indexOf(adjective.charAt(0))>=0) return "an "+adjective+" "+str.trim(); return "a "+adjective+" "+str.trim(); } int x=str.indexOf(' '); return str.substring(0,x)+" "+adjective+" "+str.substring(x+1); } public Object findCommand(MOB mob, Vector commands) { if((mob==null) ||(commands==null) ||(mob.location()==null) ||(commands.size()==0)) return null; String firstWord=((String)commands.elementAt(0)).toUpperCase(); if((firstWord.length()>1)&&(!Character.isLetterOrDigit(firstWord.charAt(0)))) { commands.insertElementAt(((String)commands.elementAt(0)).substring(1),1); commands.setElementAt(""+firstWord.charAt(0),0); firstWord=""+firstWord.charAt(0); } // first, exacting pass Command C=CMClass.findCommandByTrigger(firstWord,true); if((C!=null) &&(C.securityCheck(mob)) &&(!CMSecurity.isDisabled("COMMAND_"+CMClass.classID(C).toUpperCase()))) return C; Ability A=getToEvoke(mob,(Vector)commands.clone()); if((A!=null) &&(!CMSecurity.isDisabled("ABILITY_"+A.ID().toUpperCase()))) return A; if(getAnEvokeWord(mob,firstWord)!=null) return null; Social social=CMLib.socials().fetchSocial(commands,true,true); if(social!=null) return social; for(int c=0;c<CMLib.channels().getNumChannels();c++) { if(CMLib.channels().getChannelName(c).equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("Channel"); if((C!=null)&&(C.securityCheck(mob))) return C; } else if(("NO"+CMLib.channels().getChannelName(c)).equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("NoChannel"); if((C!=null)&&(C.securityCheck(mob))) return C; } } for(Enumeration<JournalsLibrary.CommandJournal> e=CMLib.journals().commandJournals();e.hasMoreElements();) { JournalsLibrary.CommandJournal CMJ=e.nextElement(); if(CMJ.NAME().equalsIgnoreCase(firstWord)) { C=CMClass.getCommand("CommandJournal"); if((C!=null)&&(C.securityCheck(mob))) return C; } } // second, inexacting pass for(int a=0;a<mob.numAbilities();a++) { A=mob.fetchAbility(a); HashSet tried=new HashSet(); if(A.triggerStrings()!=null) for(int t=0;t<A.triggerStrings().length;t++) if((A.triggerStrings()[t].toUpperCase().startsWith(firstWord)) &&(!tried.contains(A.triggerStrings()[t]))) { Vector commands2=(Vector)commands.clone(); commands2.setElementAt(A.triggerStrings()[t],0); Ability A2=getToEvoke(mob,commands2); if((A2!=null)&&(!CMSecurity.isDisabled("ABILITY_"+A2.ID().toUpperCase()))) { commands.setElementAt(A.triggerStrings()[t],0); return A; } } } //commands comes inexactly after ables //because of CA, PR, etc.. C=CMClass.findCommandByTrigger(firstWord,false); if((C!=null) &&(C.securityCheck(mob)) &&(!CMSecurity.isDisabled("COMMAND_"+CMClass.classID(C).toUpperCase()))) return C; social=CMLib.socials().fetchSocial(commands,false,true); if(social!=null) { commands.setElementAt(social.baseName(),0); return social; } for(int c=0;c<CMLib.channels().getNumChannels();c++) { if(CMLib.channels().getChannelName(c).startsWith(firstWord)) { commands.setElementAt(CMLib.channels().getChannelName(c),0); C=CMClass.getCommand("Channel"); if((C!=null)&&(C.securityCheck(mob))) return C; } else if(("NO"+CMLib.channels().getChannelName(c)).startsWith(firstWord)) { commands.setElementAt("NO"+CMLib.channels().getChannelName(c),0); C=CMClass.getCommand("NoChannel"); if((C!=null)&&(C.securityCheck(mob))) return C; } } for(Enumeration<JournalsLibrary.CommandJournal> e=CMLib.journals().commandJournals();e.hasMoreElements();) { JournalsLibrary.CommandJournal CMJ=e.nextElement(); if(CMJ.NAME().startsWith(firstWord)) { C=CMClass.getCommand("CommandJournal"); if((C!=null)&&(C.securityCheck(mob))) return C; } } return null; } public boolean evokedBy(Ability thisAbility, String thisWord) { for(int i=0;i<thisAbility.triggerStrings().length;i++) { if(thisAbility.triggerStrings()[i].equalsIgnoreCase(thisWord)) return true; } return false; } private String collapsedName(Ability thisAbility) { int x=thisAbility.name().indexOf(" "); if(x>=0) return CMStrings.replaceAll(thisAbility.name()," ",""); return thisAbility.Name(); } public boolean evokedBy(Ability thisAbility, String thisWord, String secondWord) { for(int i=0;i<thisAbility.triggerStrings().length;i++) { if(thisAbility.triggerStrings()[i].equalsIgnoreCase(thisWord)) { if(((thisAbility.name().toUpperCase().startsWith(secondWord))) ||(collapsedName(thisAbility).toUpperCase().startsWith(secondWord))) return true; } } return false; } public String getAnEvokeWord(MOB mob, String word) { if(mob==null) return null; Ability A=null; HashSet done=new HashSet(); for(int i=0;i<mob.numAbilities();i++) { A=mob.fetchAbility(i); if((A!=null) &&(A.triggerStrings()!=null) &&(!done.contains(A.triggerStrings()))) { done.add(A.triggerStrings()); for(int t=0;t<A.triggerStrings().length;t++) if(word.equals(A.triggerStrings()[t])) return A.triggerStrings()[t]; } } return null; } public Ability getToEvoke(MOB mob, Vector commands) { String evokeWord=((String)commands.elementAt(0)).toUpperCase(); boolean foundMoreThanOne=false; Ability evokableAbility=null; for(int a=0;a<mob.numAbilities();a++) { Ability thisAbility=mob.fetchAbility(a); if((thisAbility!=null) &&(evokedBy(thisAbility,evokeWord))) { if(evokableAbility!=null) { foundMoreThanOne=true; evokableAbility=null; break; } evokableAbility=thisAbility; } } if((evokableAbility!=null)&&(commands.size()>1)) { int classCode=evokableAbility.classificationCode()&Ability.ALL_ACODES; switch(classCode) { case Ability.ACODE_SPELL: case Ability.ACODE_SONG: case Ability.ACODE_PRAYER: case Ability.ACODE_CHANT: evokableAbility=null; foundMoreThanOne=true; break; default: break; } } if(evokableAbility!=null) commands.removeElementAt(0); else if((foundMoreThanOne)&&(commands.size()>1)) { commands.removeElementAt(0); foundMoreThanOne=false; String secondWord=((String)commands.elementAt(0)).toUpperCase(); for(int a=0;a<mob.numAbilities();a++) { Ability thisAbility=mob.fetchAbility(a); if((thisAbility!=null) &&(evokedBy(thisAbility,evokeWord,secondWord.toUpperCase()))) { if((thisAbility.name().equalsIgnoreCase(secondWord)) ||(collapsedName(thisAbility).equalsIgnoreCase(secondWord))) { evokableAbility=thisAbility; foundMoreThanOne=false; break; } else if(evokableAbility!=null) foundMoreThanOne=true; else evokableAbility=thisAbility; } } if((evokableAbility!=null)&&(!foundMoreThanOne)) commands.removeElementAt(0); else if((foundMoreThanOne)&&(commands.size()>1)) { String secondAndThirdWord=secondWord+" "+((String)commands.elementAt(1)).toUpperCase(); for(int a=0;a<mob.numAbilities();a++) { Ability thisAbility=mob.fetchAbility(a); if((thisAbility!=null) &&(evokedBy(thisAbility,evokeWord,secondAndThirdWord.toUpperCase()))) { evokableAbility=thisAbility; break; } } if(evokableAbility!=null) { commands.removeElementAt(0); commands.removeElementAt(0); } } else { for(int a=0;a<mob.numAbilities();a++) { Ability thisAbility=mob.fetchAbility(a); if((thisAbility!=null) &&(evokedBy(thisAbility,evokeWord)) &&(thisAbility.name().toUpperCase().indexOf(" "+secondWord.toUpperCase())>0)) { evokableAbility=thisAbility; commands.removeElementAt(0); break; } } } } return evokableAbility; } public boolean preEvoke(MOB mob, Vector commands, int secondsElapsed, double actionsRemaining) { commands=(Vector)commands.clone(); Ability evokableAbility=getToEvoke(mob,commands); if(evokableAbility==null) { mob.tell("You don't know how to do that."); return false; } if((CMLib.ableMapper().qualifyingLevel(mob,evokableAbility)>=0) &&(!CMLib.ableMapper().qualifiesByLevel(mob,evokableAbility)) &&(!CMSecurity.isAllowed(mob,mob.location(),"ALLSKILLS"))) { mob.tell("You are not high enough level to do that."); return false; } return evokableAbility.preInvoke(mob,commands,null,false,0,secondsElapsed,actionsRemaining); } public void evoke(MOB mob, Vector commands) { Ability evokableAbility=getToEvoke(mob,commands); if(evokableAbility==null) { mob.tell("You don't know how to do that."); return; } if((CMLib.ableMapper().qualifyingLevel(mob,evokableAbility)>=0) &&(!CMLib.ableMapper().qualifiesByLevel(mob,evokableAbility)) &&(!CMSecurity.isAllowed(mob,mob.location(),"ALLSKILLS"))) { mob.tell("You are not high enough level to do that."); return; } evokableAbility.invoke(mob,commands,null,false,0); } public boolean[] PUNCTUATION_TABLE() { if(PUNCTUATION_TABLE==null) { boolean[] PUNCTUATION_TEMP_TABLE=new boolean[255]; for(int c=0;c<255;c++) switch(c) { case '`': case '~': case '!': case '@': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')': case '_': case '-': case '+': case '=': case '[': case ']': case '{': case '}': case '\\': case '|': case ';': case ':': case '\'': case '\"': case ',': case '<': case '.': case '>': case '/': case '?': PUNCTUATION_TEMP_TABLE[c]=true; break; default: PUNCTUATION_TEMP_TABLE[c]=false; } PUNCTUATION_TABLE=PUNCTUATION_TEMP_TABLE; } return PUNCTUATION_TABLE; } public String stripPunctuation(String str) { if((str==null)||(str.length()==0)) return str; boolean puncFound=false; PUNCTUATION_TABLE(); for(int x=0;x<str.length();x++) if(isPunctuation((byte)str.charAt(x))) { puncFound=true; break; } if(!puncFound) return str; char[] strc=str.toCharArray(); char[] str2=new char[strc.length]; int s=0; for(int x=0;x<strc.length;x++) if(!isPunctuation((byte)strc[x])) { str2[s]=strc[x]; s++; } return new String(str2,0,s); } private boolean isPunctuation(byte b) { if((b<0)||(b>255)) return false; return PUNCTUATION_TABLE[b]; } public boolean equalsPunctuationless(char[] strC, char[] str2C) { if((strC.length==0)&&(str2C.length==0)) return true; PUNCTUATION_TABLE(); int s1=0; int s2=0; int s1len=strC.length; while((s1len>0)&&(Character.isWhitespace(strC[s1len-1])||isPunctuation((byte)strC[s1len-1]))) s1len--; int s2len=str2C.length; while((s2len>0)&&(Character.isWhitespace(str2C[s2len-1])||isPunctuation((byte)str2C[s2len-1]))) s2len--; while(s1<s1len) { while((s1<s1len)&&(isPunctuation((byte)strC[s1]))) s1++; while((s2<s2len)&&(isPunctuation((byte)str2C[s2]))) s2++; if(s1==s1len) { if(s2==s2len) return true; return false; } if(s2==s2len) return false; if(strC[s1]!=str2C[s2]) return false; s1++; s2++; } if(s2==s2len) return true; return false; } public boolean containsString(String toSrchStr, String srchStr) { if((toSrchStr==null)||(srchStr==null)) return false; if((toSrchStr.length()==0)&&(srchStr.length()>0)) return false; char[] srchC=srchStr.toCharArray(); char[] toSrchC=toSrchStr.toCharArray(); for(int c=0;c<srchC.length;c++) srchC[c]=Character.toUpperCase(srchC[c]); for(int c=0;c<toSrchC.length;c++) toSrchC[c]=Character.toUpperCase(toSrchC[c]); if(java.util.Arrays.equals(srchC,ALL_CHRS)) return true; if(java.util.Arrays.equals(srchC,toSrchC)) return true; if(equalsPunctuationless(srchC,toSrchC)) return true; boolean topOnly=false; if((srchC.length>1)&&(srchC[0]=='$')) { srchC=new String(srchC,1,srchC.length-1).toCharArray(); topOnly=true; } int tos=0; boolean found=false; while((!found)&&(tos<toSrchC.length)) { for(int x=0;x<srchC.length;x++) { if(tos>=toSrchC.length) { if(srchC[x]=='$') found=true; break; } switch(toSrchC[tos]) { case '^': tos=tos+2; break; case ',': case '?': case '!': case '.': case ';': tos++; break; } switch(srchC[x]) { case '^': x=x+2; break; case ',': case '?': case '!': case '.': case ';': x++; break; } if(x<srchC.length) { if(tos<toSrchC.length) { if(srchC[x]!=toSrchC[tos]) break; else if(x==(srchC.length-1)) found=true; else tos++; } else if(srchC[x]=='$') found=true; else break; } else { found=true; break; } } if((topOnly)&&(!found)) break; while((!found)&&(tos<toSrchC.length)&&(Character.isLetter(toSrchC[tos]))) tos++; tos++; } return found; } public String bumpDotNumber(String srchStr) { Object[] flags=fetchFlags(srchStr); if(flags==null) return srchStr; if(((Boolean)flags[FLAG_ALL]).booleanValue()) return srchStr; if(((Integer)flags[FLAG_DOT]).intValue()==0) return "1."+((String)flags[FLAG_STR]); return (((Integer)flags[FLAG_DOT]).intValue()+1)+"."+((String)flags[FLAG_STR]); } public Object[] fetchFlags(String srchStr) { if(srchStr.length()==0) return null; srchStr=srchStr.toUpperCase(); if((srchStr.length()<2)||(srchStr.equals("THE"))) return null; Object[] flags=new Object[3]; boolean allFlag=false; if(srchStr.startsWith("ALL ")) { srchStr=srchStr.substring(4); allFlag=true; } else if(srchStr.equals("ALL")) allFlag=true; int dot=srchStr.lastIndexOf("."); int occurrance=0; if(dot>0) { String sub=srchStr.substring(dot+1); occurrance=CMath.s_int(sub); if(occurrance>0) srchStr=srchStr.substring(0,dot); else { dot=srchStr.indexOf("."); sub=srchStr.substring(0,dot); occurrance=CMath.s_int(sub); if(occurrance>0) srchStr=srchStr.substring(dot+1); else occurrance=0; } } flags[0]=srchStr; flags[1]=Integer.valueOf(occurrance); flags[2]=Boolean.valueOf(allFlag); return flags; } public Environmental fetchEnvironmental(Vector list, String srchStr, boolean exactOnly) { Object[] flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=(String)flags[FLAG_STR]; int myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); boolean allFlag=((Boolean)flags[FLAG_ALL]).booleanValue(); Environmental thisThang=null; if(exactOnly) { if(srchStr.startsWith("$")) srchStr=srchStr.substring(1); if(srchStr.endsWith("$")) srchStr=srchStr.substring(0,srchStr.length()-1); try { for(int i=0;i<list.size();i++) { thisThang=(Environmental)list.elementAt(i); if(thisThang.ID().equalsIgnoreCase(srchStr) ||thisThang.name().equalsIgnoreCase(srchStr) ||thisThang.Name().equalsIgnoreCase(srchStr)) if((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))) if((--myOccurrance)<=0) return thisThang; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } else { myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); try { for(int i=0;i<list.size();i++) { thisThang=(Environmental)list.elementAt(i); if((containsString(thisThang.name(),srchStr)||containsString(thisThang.Name(),srchStr)) &&((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0)))) if((--myOccurrance)<=0) return thisThang; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); try { for(int i=0;i<list.size();i++) { thisThang=(Environmental)list.elementAt(i); if((!(thisThang instanceof Ability)) &&(containsString(thisThang.displayText(),srchStr) ||((thisThang instanceof MOB)&&containsString(((MOB)thisThang).genericName(),srchStr)))) if((--myOccurrance)<=0) return thisThang; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } return null; } public Vector fetchEnvironmentals(Vector list, String srchStr, boolean exactOnly) { Object[] flags=fetchFlags(srchStr); Vector matches=new Vector(1); if(flags==null) return matches; srchStr=(String)flags[FLAG_STR]; int myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); boolean allFlag=((Boolean)flags[FLAG_ALL]).booleanValue(); Environmental thisThang=null; if(exactOnly) { if(srchStr.startsWith("$")) srchStr=srchStr.substring(1); if(srchStr.endsWith("$")) srchStr=srchStr.substring(0,srchStr.length()-1); try { for(int i=0;i<list.size();i++) { thisThang=(Environmental)list.elementAt(i); if(thisThang.ID().equalsIgnoreCase(srchStr) ||thisThang.name().equalsIgnoreCase(srchStr) ||thisThang.Name().equalsIgnoreCase(srchStr)) if((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))) if((--myOccurrance)<=0) matches.addElement(thisThang); } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } else { myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); try { for(int i=0;i<list.size();i++) { thisThang=(Environmental)list.elementAt(i); if((containsString(thisThang.name(),srchStr)||containsString(thisThang.Name(),srchStr)) &&((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0)))) if((--myOccurrance)<=0) matches.addElement(thisThang); } } catch(java.lang.ArrayIndexOutOfBoundsException x){} if(matches.size()==0) { myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); try { for(int i=0;i<list.size();i++) { thisThang=(Environmental)list.elementAt(i); if((!(thisThang instanceof Ability)) &&(containsString(thisThang.displayText(),srchStr) ||((thisThang instanceof MOB)&&containsString(((MOB)thisThang).genericName(),srchStr)))) if((--myOccurrance)<=0) matches.addElement(thisThang); } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } } return matches; } public Environmental fetchEnvironmental(Hashtable list, String srchStr, boolean exactOnly) { Object[] flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=(String)flags[FLAG_STR]; int myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); boolean allFlag=((Boolean)flags[FLAG_ALL]).booleanValue(); if(list.get(srchStr)!=null) return (Environmental)list.get(srchStr); Environmental thisThang=null; if(exactOnly) { if(srchStr.startsWith("$")) srchStr=srchStr.substring(1); if(srchStr.endsWith("$")) srchStr=srchStr.substring(0,srchStr.length()-1); for(Enumeration e=list.elements();e.hasMoreElements();) { thisThang=(Environmental)e.nextElement(); if(thisThang.ID().equalsIgnoreCase(srchStr) ||thisThang.Name().equalsIgnoreCase(srchStr) ||thisThang.name().equalsIgnoreCase(srchStr)) if((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))) if((--myOccurrance)<=0) return thisThang; } } else { myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); for(Enumeration e=list.elements();e.hasMoreElements();) { thisThang=(Environmental)e.nextElement(); if((containsString(thisThang.name(),srchStr)||containsString(thisThang.Name(),srchStr)) &&((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0)))) if((--myOccurrance)<=0) return thisThang; } myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); for(Enumeration e=list.elements();e.hasMoreElements();) { thisThang=(Environmental)e.nextElement(); if((containsString(thisThang.displayText(),srchStr)) ||((thisThang instanceof MOB)&&containsString(((MOB)thisThang).genericName(),srchStr))) if((--myOccurrance)<=0) return thisThang; } } return null; } public int getContextNumber(Object[] list, Environmental E){ return getContextNumber(CMParms.makeVector(list),E);} public int getContextNumber(Vector list, Environmental E) { if(list==null) return 0; Vector V=(Vector)list.clone(); int context=1; for(int v=0;v<V.size();v++) if((((Environmental)V.elementAt(v)).Name().equalsIgnoreCase(E.Name())) ||(((Environmental)V.elementAt(v)).name().equalsIgnoreCase(E.name()))) { if(V.elementAt(v)==E) return context<2?0:context; if((!(V.elementAt(v) instanceof Item)) ||(!(E instanceof Item)) ||(((Item)E).container()==((Item)V.elementAt(v)).container())) context++; } return -1; } public int getContextSameNumber(Object[] list, Environmental E){ return getContextSameNumber(CMParms.makeVector(list),E);} public int getContextSameNumber(Vector list, Environmental E) { if(list==null) return 0; Vector V=(Vector)list.clone(); int context=1; for(int v=0;v<V.size();v++) if((((Environmental)V.elementAt(v)).Name().equalsIgnoreCase(E.Name())) ||(((Environmental)V.elementAt(v)).name().equalsIgnoreCase(E.name()))) { if(E.sameAs((Environmental)V.elementAt(v))) return context<2?0:context; if((!(V.elementAt(v) instanceof Item)) ||(!(E instanceof Item)) ||(((Item)E).container()==((Item)V.elementAt(v)).container())) context++; } return -1; } public String getContextName(Object[] list, Environmental E){ return getContextName(CMParms.makeVector(list),E);} public String getContextName(Vector list, Environmental E) { if(list==null) return E.name(); int number=getContextNumber(list,E); if(number<0) return null; if(number<2) return E.name(); return E.name()+"."+number; } public String getContextSameName(Object[] list, Environmental E){ return getContextName(CMParms.makeVector(list),E);} public String getContextSameName(Vector list, Environmental E) { if(list==null) return E.name(); int number=getContextSameNumber(list,E); if(number<0) return null; if(number<2) return E.name(); return E.name()+"."+number; } public Environmental fetchEnvironmental(Environmental[] list, String srchStr, boolean exactOnly) { Object[] flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=(String)flags[FLAG_STR]; int myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); boolean allFlag=((Boolean)flags[FLAG_ALL]).booleanValue(); Environmental thisThang=null; if(exactOnly) { if(srchStr.startsWith("$")) srchStr=srchStr.substring(1); if(srchStr.endsWith("$")) srchStr=srchStr.substring(0,srchStr.length()-1); for(int i=0;i<list.length;i++) { thisThang=list[i]; if(thisThang!=null) if(thisThang.ID().equalsIgnoreCase(srchStr) ||thisThang.Name().equalsIgnoreCase(srchStr) ||thisThang.name().equalsIgnoreCase(srchStr)) if((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))) if((--myOccurrance)<=0) return thisThang; } } else { myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); for(int i=0;i<list.length;i++) { thisThang=list[i]; if(thisThang!=null) if((containsString(thisThang.name(),srchStr)||containsString(thisThang.Name(),srchStr)) &&((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0)))) if((--myOccurrance)<=0) return thisThang; } myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); for(int i=0;i<list.length;i++) { thisThang=list[i]; if(thisThang==null) continue; if((containsString(thisThang.displayText(),srchStr)) ||((thisThang instanceof MOB)&&containsString(((MOB)thisThang).genericName(),srchStr))) if((--myOccurrance)<=0) return thisThang; } } return null; } public Item fetchAvailableItem(Vector list, String srchStr, Item goodLocation, int wornReqCode, boolean exactOnly) { Object[] flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=(String)flags[FLAG_STR]; int myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); boolean allFlag=((Boolean)flags[FLAG_ALL]).booleanValue(); if(exactOnly) { try { if(srchStr.startsWith("$")) srchStr=srchStr.substring(1); if(srchStr.endsWith("$")) srchStr=srchStr.substring(0,srchStr.length()-1); for(int i=0;i<list.size();i++) { Item thisThang=(Item)list.elementAt(i); boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornReqCode==Wearable.FILTER_ANY)||(beingWorn&&(wornReqCode==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornReqCode==Wearable.FILTER_UNWORNONLY))) &&(thisThang.ID().equalsIgnoreCase(srchStr) ||(thisThang.Name().equalsIgnoreCase(srchStr)) ||(thisThang.name().equalsIgnoreCase(srchStr)))) if((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))) if((--myOccurrance)<=0) return thisThang; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } else { try { for(int i=0;i<list.size();i++) { Item thisThang=(Item)list.elementAt(i); boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornReqCode==Wearable.FILTER_ANY)||(beingWorn&&(wornReqCode==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornReqCode==Wearable.FILTER_UNWORNONLY))) &&((containsString(thisThang.name(),srchStr)||containsString(thisThang.Name(),srchStr)) &&((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))))) if((--myOccurrance)<=0) return thisThang; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); try { Item thisThang=null; for(int i=0;i<list.size();i++) { thisThang=(Item)list.elementAt(i); boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornReqCode==Wearable.FILTER_ANY)||(beingWorn&&(wornReqCode==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornReqCode==Wearable.FILTER_UNWORNONLY))) &&(containsString(thisThang.displayText(),srchStr))) if((--myOccurrance)<=0) return thisThang; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } return null; } public Vector fetchAvailableItems(Vector list, String srchStr, Item goodLocation, int wornReqCode, boolean exactOnly) { Vector matches=new Vector(); Object[] flags=fetchFlags(srchStr); if(flags==null) return matches; srchStr=(String)flags[FLAG_STR]; int myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); boolean allFlag=((Boolean)flags[FLAG_ALL]).booleanValue(); if(exactOnly) { try { if(srchStr.startsWith("$")) srchStr=srchStr.substring(1); if(srchStr.endsWith("$")) srchStr=srchStr.substring(0,srchStr.length()-1); for(int i=0;i<list.size();i++) { Item thisThang=(Item)list.elementAt(i); boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornReqCode==Wearable.FILTER_ANY)||(beingWorn&&(wornReqCode==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornReqCode==Wearable.FILTER_UNWORNONLY))) &&(thisThang.ID().equalsIgnoreCase(srchStr) ||(thisThang.Name().equalsIgnoreCase(srchStr)) ||(thisThang.name().equalsIgnoreCase(srchStr)))) if((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))) if((--myOccurrance)<=0) matches.addElement(thisThang); } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } else { try { for(int i=0;i<list.size();i++) { Item thisThang=(Item)list.elementAt(i); boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornReqCode==Wearable.FILTER_ANY)||(beingWorn&&(wornReqCode==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornReqCode==Wearable.FILTER_UNWORNONLY))) &&((containsString(thisThang.name(),srchStr)||containsString(thisThang.Name(),srchStr)) &&((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))))) if((--myOccurrance)<=0) matches.addElement(thisThang); } } catch(java.lang.ArrayIndexOutOfBoundsException x){} if(matches.size()==0) { myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); try { Item thisThang=null; for(int i=0;i<list.size();i++) { thisThang=(Item)list.elementAt(i); boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornReqCode==Wearable.FILTER_ANY)||(beingWorn&&(wornReqCode==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornReqCode==Wearable.FILTER_UNWORNONLY))) &&(containsString(thisThang.displayText(),srchStr))) if((--myOccurrance)<=0) matches.addElement(thisThang); } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } } return matches; } public Environmental fetchAvailable(Vector list, String srchStr, Item goodLocation, int wornFilter, boolean exactOnly) { Object[] flags=fetchFlags(srchStr); if(flags==null) return null; srchStr=(String)flags[FLAG_STR]; int myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); boolean allFlag=((Boolean)flags[FLAG_ALL]).booleanValue(); Environmental E=null; Item thisThang=null; if(exactOnly) { try { if(srchStr.startsWith("$")) srchStr=srchStr.substring(1); if(srchStr.endsWith("$")) srchStr=srchStr.substring(0,srchStr.length()-1); for(int i=0;i<list.size();i++) { E=(Environmental)list.elementAt(i); if(E instanceof Item) { thisThang=(Item)E; boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornFilter==Wearable.FILTER_ANY)||(beingWorn&&(wornFilter==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornFilter==Wearable.FILTER_UNWORNONLY))) &&(thisThang.ID().equalsIgnoreCase(srchStr) ||(thisThang.Name().equalsIgnoreCase(srchStr)) ||(thisThang.name().equalsIgnoreCase(srchStr)))) if((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))) if((--myOccurrance)<=0) return thisThang; } else if(E.ID().equalsIgnoreCase(srchStr) ||E.Name().equalsIgnoreCase(srchStr) ||E.name().equalsIgnoreCase(srchStr)) if((!allFlag)||((E.displayText()!=null)&&(E.displayText().length()>0))) if((--myOccurrance)<=0) return E; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } else { try { for(int i=0;i<list.size();i++) { E=(Environmental)list.elementAt(i); if(E instanceof Item) { thisThang=(Item)E; boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornFilter==Wearable.FILTER_ANY)||(beingWorn&&(wornFilter==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornFilter==Wearable.FILTER_UNWORNONLY))) &&((containsString(thisThang.name(),srchStr)||containsString(thisThang.Name(),srchStr)) &&((!allFlag)||((thisThang.displayText()!=null)&&(thisThang.displayText().length()>0))))) if((--myOccurrance)<=0) return thisThang; } else if((containsString(E.name(),srchStr)||containsString(E.Name(),srchStr)) &&((!allFlag)||((E.displayText()!=null)&&(E.displayText().length()>0)))) if((--myOccurrance)<=0) return E; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} myOccurrance=((Integer)flags[FLAG_DOT]).intValue(); try { for(int i=0;i<list.size();i++) { E=(Environmental)list.elementAt(i); if(E instanceof Item) { thisThang=(Item)E; boolean beingWorn=!thisThang.amWearingAt(Wearable.IN_INVENTORY); if((thisThang.container()==goodLocation) &&((wornFilter==Wearable.FILTER_ANY)||(beingWorn&&(wornFilter==Wearable.FILTER_WORNONLY))||((!beingWorn)&&(wornFilter==Wearable.FILTER_UNWORNONLY))) &&(containsString(thisThang.displayText(),srchStr))) if((--myOccurrance)<=0) return thisThang; } else if((containsString(E.displayText(),srchStr)) ||((E instanceof MOB)&&containsString(((MOB)E).genericName(),srchStr))) if((--myOccurrance)<=0) return E; } } catch(java.lang.ArrayIndexOutOfBoundsException x){} } return null; } public Environmental parseShopkeeper(MOB mob, Vector commands, String error) { if(commands.size()==0) { if(error.length()>0) mob.tell(error); return null; } commands.removeElementAt(0); Vector V=CMLib.coffeeShops().getAllShopkeepers(mob.location(),mob); if(V.size()==0) { if(error.length()>0) mob.tell(error); return null; } if(V.size()>1) { if(commands.size()<2) { if(error.length()>0) mob.tell(error); return null; } String what=(String)commands.lastElement(); Environmental shopkeeper=fetchEnvironmental(V,what,false); if((shopkeeper==null)&&(what.equals("shop")||what.equals("the shop"))) for(int v=0;v<V.size();v++) if(V.elementAt(v) instanceof Area) { shopkeeper=(Environmental)V.elementAt(v); break;} if((shopkeeper!=null)&&(CMLib.coffeeShops().getShopKeeper(shopkeeper)!=null)&&(CMLib.flags().canBeSeenBy(shopkeeper,mob))) commands.removeElementAt(commands.size()-1); else { mob.tell("You don't see anyone called '"+(String)commands.lastElement()+"' here buying or selling."); return null; } return shopkeeper; } Environmental shopkeeper=(Environmental)V.firstElement(); if(commands.size()>1) { MOB M=mob.location().fetchInhabitant((String)commands.lastElement()); if((M!=null)&&(CMLib.coffeeShops().getShopKeeper(M)!=null)&&(CMLib.flags().canBeSeenBy(M,mob))) { shopkeeper=M; commands.removeElementAt(commands.size()-1); } } return shopkeeper; } public Vector fetchItemList(Environmental from, MOB mob, Item container, Vector commands, int preferredLoc, boolean visionMatters) { int addendum=1; String addendumStr=""; Vector V=new Vector(); int maxToItem=Integer.MAX_VALUE; if((commands.size()>1) &&(CMath.s_int((String)commands.firstElement())>0)) { maxToItem=CMath.s_int((String)commands.firstElement()); commands.setElementAt("all",0); } String name=CMParms.combine(commands,0); boolean allFlag=(commands.size()>0)?((String)commands.elementAt(0)).equalsIgnoreCase("all"):false; if(name.toUpperCase().startsWith("ALL.")){ allFlag=true; name="ALL "+name.substring(4);} if(name.toUpperCase().endsWith(".ALL")){ allFlag=true; name="ALL "+name.substring(0,name.length()-4);} boolean doBugFix = true; while(doBugFix || ((allFlag)&&(addendum<=maxToItem))) { doBugFix=false; Environmental item=null; if(from instanceof MOB) { if(preferredLoc==Wearable.FILTER_UNWORNONLY) item=((MOB)from).fetchCarried(container,name+addendumStr); else if(preferredLoc==Wearable.FILTER_WORNONLY) item=((MOB)from).fetchWornItem(name+addendumStr); else item=((MOB)from).fetchInventory(null,name+addendumStr); } else if(from instanceof Room) item=((Room)from).fetchFromMOBRoomFavorsItems(mob,container,name+addendumStr,preferredLoc); if((item!=null) &&(item instanceof Item) &&((!visionMatters)||(CMLib.flags().canBeSeenBy(item,mob))||(item instanceof Light)) &&(!V.contains(item))) V.addElement(item); if(item==null) break; addendumStr="."+(++addendum); } if(preferredLoc==Wearable.FILTER_WORNONLY) { Vector V2=new Vector(); short topLayer=0; short curLayer=0; int which=-1; while(V.size()>0) { Item I=(Item)V.firstElement(); topLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; which=0; for(int v=1;v<V.size();v++) { I=(Item)V.elementAt(v); curLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; if(curLayer>topLayer) { which=v; topLayer=curLayer;} } V2.addElement(V.elementAt(which)); V.removeElementAt(which); } V=V2; } else if(preferredLoc==Wearable.FILTER_UNWORNONLY) { Vector V2=new Vector(); short topLayer=0; short curLayer=0; int which=-1; while(V.size()>0) { Item I=(Item)V.firstElement(); topLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; which=0; for(int v=1;v<V.size();v++) { I=(Item)V.elementAt(v); curLayer=(I instanceof Armor)?((Armor)I).getClothingLayer():0; if(curLayer<topLayer) { which=v; topLayer=curLayer;} } V2.addElement(V.elementAt(which)); V.removeElementAt(which); } V=V2; } return V; } public long numPossibleGold(Environmental mine, String itemID) { if(itemID.toUpperCase().trim().startsWith("A PILE OF ")) itemID=itemID.substring(10); if(CMath.isInteger(itemID)) { long num=CMath.s_long(itemID); if(mine instanceof MOB) { Vector V=CMLib.beanCounter().getStandardCurrency((MOB)mine,CMLib.beanCounter().getCurrency(mine)); for(int v=0;v<V.size();v++) if(((Coins)V.elementAt(v)).getNumberOfCoins()>=num) return num; V=CMLib.beanCounter().getStandardCurrency((MOB)mine,null); for(int v=0;v<V.size();v++) if(((Coins)V.elementAt(v)).getNumberOfCoins()>=num) return num; } return CMath.s_long(itemID); } Vector V=CMParms.parse(itemID); if((V.size()>1) &&((CMath.isInteger((String)V.firstElement())) &&(matchAnyCurrencySet(CMParms.combine(V,1))!=null))) return CMath.s_long((String)V.firstElement()); else if((V.size()>1)&&(((String)V.firstElement()).equalsIgnoreCase("all"))) { String currency=matchAnyCurrencySet(CMParms.combine(V,1)); if(currency!=null) { if(mine instanceof MOB) { Vector V2=CMLib.beanCounter().getStandardCurrency((MOB)mine,currency); double denomination=matchAnyDenomination(currency,CMParms.combine(V,1)); Coins C=null; for(int v2=0;v2<V2.size();v2++) { C=(Coins)V2.elementAt(v2); if(C.getDenomination()==denomination) return C.getNumberOfCoins(); } } return 1; } } else if((V.size()>0)&&(matchAnyCurrencySet(CMParms.combine(V,0))!=null)) return 1; return 0; } public String numPossibleGoldCurrency(Environmental mine, String itemID) { if(itemID.toUpperCase().trim().startsWith("A PILE OF ")) itemID=itemID.substring(10); if(CMath.isInteger(itemID)) { long num=CMath.s_long(itemID); if(mine instanceof MOB) { Vector V=CMLib.beanCounter().getStandardCurrency((MOB)mine,CMLib.beanCounter().getCurrency(mine)); for(int v=0;v<V.size();v++) if(((Coins)V.elementAt(v)).getNumberOfCoins()>=num) return ((Coins)V.elementAt(v)).getCurrency(); V=CMLib.beanCounter().getStandardCurrency((MOB)mine,null); for(int v=0;v<V.size();v++) if(((Coins)V.elementAt(v)).getNumberOfCoins()>=num) return ((Coins)V.elementAt(v)).getCurrency(); } return CMLib.beanCounter().getCurrency(mine); } Vector V=CMParms.parse(itemID); if((V.size()>1)&&(CMath.isInteger((String)V.firstElement()))) return matchAnyCurrencySet(CMParms.combine(V,1)); else if((V.size()>1)&&(((String)V.firstElement()).equalsIgnoreCase("all"))) return matchAnyCurrencySet(CMParms.combine(V,1)); else if(V.size()>0) return matchAnyCurrencySet(CMParms.combine(V,0)); return CMLib.beanCounter().getCurrency(mine); } public double numPossibleGoldDenomination(Environmental mine, String currency, String itemID) { if(itemID.toUpperCase().trim().startsWith("A PILE OF ")) itemID=itemID.substring(10); if(CMath.isInteger(itemID)) { long num=CMath.s_long(itemID); if(mine instanceof MOB) { Vector V=CMLib.beanCounter().getStandardCurrency((MOB)mine,currency); for(int v=0;v<V.size();v++) if(((Coins)V.elementAt(v)).getNumberOfCoins()>=num) return ((Coins)V.elementAt(v)).getDenomination(); } return CMLib.beanCounter().getLowestDenomination(currency); } Vector V=CMParms.parse(itemID); if((V.size()>1)&&(CMath.isInteger((String)V.firstElement()))) return matchAnyDenomination(currency,CMParms.combine(V,1)); else if((V.size()>1)&&(((String)V.firstElement()).equalsIgnoreCase("all"))) return matchAnyDenomination(currency,CMParms.combine(V,1)); else if(V.size()>0) return matchAnyDenomination(currency,CMParms.combine(V,0)); return 0; } public String matchAnyCurrencySet(String itemID) { Vector V=CMLib.beanCounter().getAllCurrencies(); Vector V2=null; for(int v=0;v<V.size();v++) { V2=CMLib.beanCounter().getDenominationNameSet((String)V.elementAt(v)); for(int v2=0;v2<V2.size();v2++) { String s=(String)V2.elementAt(v2); if(s.toLowerCase().endsWith("(s)")) s=s.substring(0,s.length()-3)+"s"; if(containsString(s,itemID)) return (String)V.elementAt(v); } } return null; } public double matchAnyDenomination(String currency, String itemID) { MoneyLibrary.MoneyDenomination[] DV=CMLib.beanCounter().getCurrencySet(currency); itemID=itemID.toUpperCase(); String s=null; if(DV!=null) for(int v2=0;v2<DV.length;v2++) { s=DV[v2].name.toUpperCase(); if(s.endsWith("(S)")) s=s.substring(0,s.length()-3)+"S"; if(containsString(s,itemID)) return DV[v2].value; else if((s.length()>0) &&(containsString(s,itemID))) return DV[v2].value; } return 0.0; } public Item possibleRoomGold(MOB seer, Room room, Item container, String itemID) { if(itemID.toUpperCase().trim().startsWith("A PILE OF ")) itemID=itemID.substring(10); long gold=0; if(CMath.isInteger(itemID)) { gold=CMath.s_long(itemID); itemID=""; } else { Vector V=CMParms.parse(itemID); if((V.size()>1)&&(CMath.isInteger((String)V.firstElement()))) gold=CMath.s_long((String)V.firstElement()); else return null; itemID=CMParms.combine(V,1); } if(gold>0) { for(int i=0;i<room.numItems();i++) { Item I=room.fetchItem(i); if((I.container()==container) &&(I instanceof Coins) &&(CMLib.flags().canBeSeenBy(I,seer)) &&((itemID.length()==0)||(containsString(I.name(),itemID)))) { if(((Coins)I).getNumberOfCoins()<=gold) return I; ((Coins)I).setNumberOfCoins(((Coins)I).getNumberOfCoins()-gold); Coins C=(Coins)CMClass.getItem("StdCoins"); C.setCurrency(((Coins)I).getCurrency()); C.setNumberOfCoins(gold); C.setDenomination(((Coins)I).getDenomination()); C.setContainer(container); C.recoverEnvStats(); room.addItem(C); C.setExpirationDate(I.expirationDate()); return C; } } } return null; } public Item bestPossibleGold(MOB mob, Container container, String itemID) { if(itemID.toUpperCase().trim().startsWith("A PILE OF ")) itemID=itemID.substring(10); long gold=0; double denomination=0.0; String currency=CMLib.beanCounter().getCurrency(mob); if(CMath.isInteger(itemID)) { gold=CMath.s_long(itemID); double totalAmount=CMLib.beanCounter().getTotalAbsoluteValue(mob,currency); double bestDenomination=CMLib.beanCounter().getBestDenomination(currency,(int)gold,totalAmount); if(bestDenomination==0.0) { bestDenomination=CMLib.beanCounter().getBestDenomination(null,(int)gold,totalAmount); if(bestDenomination>0.0) currency=null; } if(bestDenomination==0.0) return null; denomination=bestDenomination; } else { Vector V=CMParms.parse(itemID); if(V.size()<1) return null; if((!CMath.isInteger((String)V.firstElement())) &&(!((String)V.firstElement()).equalsIgnoreCase("all"))) V.insertElementAt("1",0); Item I=mob.fetchInventory(container,CMParms.combine(V,1)); if(I instanceof Coins) { if(((String)V.firstElement()).equalsIgnoreCase("all")) gold=((Coins)I).getNumberOfCoins(); else gold=CMath.s_long((String)V.firstElement()); currency=((Coins)I).getCurrency(); denomination=((Coins)I).getDenomination(); } else return null; } if(gold>0) { double amt = CMLib.beanCounter().getTotalAbsoluteValue(mob, currency); if(amt>=CMath.mul(denomination,gold)) { double expectedAmt = amt - CMath.mul(denomination,gold); CMLib.beanCounter().subtractMoney(mob,currency,denomination,CMath.mul(denomination,gold)); double newAmt = CMLib.beanCounter().getTotalAbsoluteValue(mob, currency); if(newAmt > expectedAmt) CMLib.beanCounter().subtractMoney(mob,currency,(newAmt - expectedAmt)); Coins C=(Coins)CMClass.getItem("StdCoins"); C.setCurrency(currency); C.setDenomination(denomination); C.setNumberOfCoins(gold); C.recoverEnvStats(); mob.addInventory(C); return C; } mob.tell("You don't have that much "+CMLib.beanCounter().getDenominationName(currency,denomination)+"."); Vector V=CMLib.beanCounter().getStandardCurrency(mob,currency); for(int v=0;v<V.size();v++) if(((Coins)V.elementAt(v)).getDenomination()==denomination) return (Item)V.elementAt(v); } return null; } public Vector possibleContainers(MOB mob, Vector commands, int wornFilter, boolean withContentOnly) { Vector V=new Vector(); if(commands.size()==1) return V; int fromDex=-1; int containerDex=commands.size()-1; for(int i=commands.size()-2;i>0;i--) if(((String)commands.elementAt(i)).equalsIgnoreCase("from")) { fromDex=i; containerDex=i+1; if(((containerDex+1)<commands.size()) &&((((String)commands.elementAt(containerDex)).equalsIgnoreCase("all")) ||(CMath.s_int((String)commands.elementAt(containerDex))>0))) containerDex++; break; } String possibleContainerID=CMParms.combine(commands,containerDex); boolean allFlag=false; String preWord=""; if(possibleContainerID.equalsIgnoreCase("all")) allFlag=true; else if(containerDex>1) preWord=(String)commands.elementAt(containerDex-1); int maxContained=Integer.MAX_VALUE; if(CMath.s_int(preWord)>0) { maxContained=CMath.s_int(preWord); commands.setElementAt("all",containerDex-1); containerDex--; preWord="all"; } if(preWord.equalsIgnoreCase("all")){ allFlag=true; possibleContainerID="ALL "+possibleContainerID;} else if(possibleContainerID.toUpperCase().startsWith("ALL.")){ allFlag=true; possibleContainerID="ALL "+possibleContainerID.substring(4);} else if(possibleContainerID.toUpperCase().endsWith(".ALL")){ allFlag=true; possibleContainerID="ALL "+possibleContainerID.substring(0,possibleContainerID.length()-4);} int addendum=1; String addendumStr=""; boolean doBugFix = true; while(doBugFix || ((allFlag)&&(addendum<=maxContained))) { doBugFix=false; Environmental thisThang=mob.location().fetchFromMOBRoomFavorsItems(mob,null,possibleContainerID+addendumStr,wornFilter); if((thisThang!=null) &&(thisThang instanceof Item) &&(((Item)thisThang) instanceof Container) &&((!withContentOnly)||(((Container)thisThang).getContents().size()>0)) &&(CMLib.flags().canBeSeenBy(thisThang,mob)||mob.isMine(thisThang))) { V.addElement(thisThang); if(V.size()==1) { while((fromDex>=0)&&(commands.size()>fromDex)) commands.removeElementAt(fromDex); while(commands.size()>containerDex) commands.removeElementAt(containerDex); preWord=""; } } if(thisThang==null) return V; addendumStr="."+(++addendum); } return V; } public Item possibleContainer(MOB mob, Vector commands, boolean withStuff, int wornFilter) { if(commands.size()==1) return null; int fromDex=-1; int containerDex=commands.size()-1; for(int i=commands.size()-2;i>=1;i--) if(((String)commands.elementAt(i)).equalsIgnoreCase("from")) { fromDex=i; containerDex=i+1; break;} String possibleContainerID=CMParms.combine(commands,containerDex); Environmental thisThang=mob.location().fetchFromMOBRoomFavorsItems(mob,null,possibleContainerID,wornFilter); if((thisThang!=null) &&(thisThang instanceof Item) &&(((Item)thisThang) instanceof Container) &&((!withStuff)||(((Container)thisThang).getContents().size()>0))) { while((fromDex>=0)&&(commands.size()>fromDex)) commands.removeElementAt(fromDex); while(commands.size()>containerDex) commands.removeElementAt(containerDex); return (Item)thisThang; } return null; } public String returnTime(long millis, long ticks) { String avg=""; if(ticks>0) avg=", Average="+(millis/ticks)+"ms"; if(millis<1000) return millis+"ms"+avg; long seconds=millis/1000; millis-=(seconds*1000); if(seconds<60) return seconds+"s "+millis+"ms"+avg; long minutes=seconds/60; seconds-=(minutes*60); if(minutes<60) return minutes+"m "+seconds+"s "+millis+"ms"+avg; long hours=minutes/60; minutes-=(hours*60); if(hours<24) return hours+"h "+minutes+"m "+seconds+"s "+millis+"ms"+avg; long days=hours/24; hours-=(days*24); return days+"d "+hours+"h "+minutes+"m "+seconds+"s "+millis+"ms"+avg; } public Object[] parseMoneyStringSDL(MOB mob, String amount, String correctCurrency) { double b=0; String myCurrency=CMLib.beanCounter().getCurrency(mob); double denomination=1.0; if(correctCurrency==null) correctCurrency=myCurrency; if(amount.length()>0) { myCurrency=CMLib.english().numPossibleGoldCurrency(mob,amount); if(myCurrency!=null) { denomination=CMLib.english().numPossibleGoldDenomination(null,correctCurrency,amount); long num=CMLib.english().numPossibleGold(null,amount); b=CMath.mul(denomination,num); } else myCurrency=CMLib.beanCounter().getCurrency(mob); } return new Object[]{myCurrency,Double.valueOf(denomination),Long.valueOf(Math.round(b/denomination))}; } public int calculateMaxToGive(MOB mob, Vector commands, boolean breakPackages, Environmental checkWhat, boolean getOnly) { int maxToGive=Integer.MAX_VALUE; if((commands.size()>1) &&(CMLib.english().numPossibleGold(mob,CMParms.combine(commands,0))==0) &&(CMath.s_int((String)commands.firstElement())>0)) { maxToGive=CMath.s_int((String)commands.firstElement()); commands.setElementAt("all",0); if(breakPackages) { boolean throwError=false; if((commands.size()>2)&&("FROM".startsWith(((String)commands.elementAt(1)).toUpperCase()))) { throwError=true; commands.removeElementAt(1); } String packCheckName=CMParms.combine(commands,1); Environmental fromWhat=null; if(checkWhat instanceof MOB) fromWhat=mob.fetchInventory(null,packCheckName); else if(checkWhat instanceof Room) fromWhat=((Room)checkWhat).fetchFromMOBRoomFavorsItems(mob,null,packCheckName,Wearable.FILTER_UNWORNONLY); if(fromWhat instanceof Item) { int max=mob.maxCarry(); if(max>3000) max=3000; if(maxToGive>max) { mob.tell("You can only handle "+max+" at a time."); return -1; } Environmental toWhat=CMLib.materials().unbundle((Item)fromWhat,maxToGive); if(toWhat==null) { if(throwError) { mob.tell("You can't get anything from "+fromWhat.name()+"."); return -1; } } else if(getOnly&&mob.isMine(fromWhat)&&mob.isMine(toWhat)) { mob.tell("Ok"); return -1; } else if(commands.size()==1) commands.addElement(toWhat.name()); else { Object o=commands.firstElement(); commands.clear(); commands.addElement(o); commands.addElement(toWhat.name()); } } else if(throwError) { mob.tell("You don't see '"+packCheckName+"' here."); return -1; } } } return maxToGive; } }
apache-2.0
davidbuhler/maven-gwt-appengine-jdo-seed-project
src/main/java/com/davidbuhler/plaidsuit/client/event/EditContactCancelledEvent.java
522
package com.davidbuhler.plaidsuit.client.event; import com.google.gwt.event.shared.GwtEvent; public class EditContactCancelledEvent extends GwtEvent<EditContactCancelledEventHandler> { public static Type<EditContactCancelledEventHandler> TYPE = new Type<EditContactCancelledEventHandler>(); @Override public Type<EditContactCancelledEventHandler> getAssociatedType() { return TYPE; } @Override protected void dispatch(EditContactCancelledEventHandler handler) { handler.onEditContactCancelled(this); } }
apache-2.0
GerardPaligot/ZMessenger
app/src/main/java/org/randoomz/zdsmessenger/auth/database/TokenDao.java
245
package org.randoomz.zdsmessenger.auth.database; import org.randoomz.zdsmessenger.auth.Token; import org.randoomz.zdsmessenger.internal.database.Dao; /** * Created by gerard on 25/09/2015. */ public interface TokenDao extends Dao<Token> { }
apache-2.0
Gaia3D/mago3d
mago3d-user/src/main/java/gaia3d/domain/user/UserGroupRole.java
1153
package gaia3d.domain.user; import lombok.*; import org.springframework.format.annotation.DateTimeFormat; import java.time.LocalDateTime; /** * 사용자 그룹별 Role * @author jeongdae * */ @ToString @Builder @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class UserGroupRole { /****** validator ********/ private String methodMode; // 사용자ID private String userId; // check role_id private String checkIds; // 고유번호 private Integer userGroupRoleId; // 사용자 그룹 고유키 private Integer userGroupId; // Role 고유키 private Integer roleId; // Role 명 private String roleName; // Role KEY private String roleKey; // Role 타켓. 0 : 사용자 페이지, 1 : 관리자 페이지, 2 : 서버 private String roleTarget; // Role 업무 유형. 0 : 사용자, 1 : 서버, 3 : api private String roleType; // 사용유무. Y : 사용, N : 사용안함 private String useYn; // 기본사용 유무. Y : 사용, N : 사용안함 private String defaultYn; // 설명 private String description; @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private LocalDateTime insertDate; }
apache-2.0
jsongraph/jgf-app
src/main/java/info/json_graph_format/jgfapp/api/util/ComparablePair.java
2801
package info.json_graph_format.jgfapp.api.util; import com.google.common.collect.ComparisonChain; /** * A pair of some types, {@code T1} and {@code T2} that implement {@link Comparable}. * <p> * For example, to represent a point: * <pre> * Pair&lt;Integer, Integer&gt; point = new Pair&lt;&gt;(0, 0); * Pair&lt;String, Integer&gt; nameAge = new Pair&lt;&gt;("Tony", 32); * // java.lang.Integer and java.lang.Double are Comparable * </pre> * but not: * <pre> * Pair&lt;Object, Object&gt; point = new Pair&lt;&gt;(new Object(), new Object()); * // java.lang.Object is not Comparable * </pre> * </p> */ public final class ComparablePair<T1 extends Comparable<T1>, T2 extends Comparable<T2>> implements Comparable<ComparablePair<T1, T2>> { private final T1 first; private final T2 second; private final int hash; /** * Creates a pair. * * @param t1 {@code T1} * @param t2 {@code T2} */ public ComparablePair(T1 t1, T2 t2) { this.first = t1; this.second = t2; this.hash = hash(); } /** * Returns the pair's first ({@code T1}). */ public T1 first() { return first; } /** * Returns the pair's second ({@code T2}). */ public T2 second() { return second; } /** * {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof ComparablePair)) return false; final ComparablePair<?,?> other = (ComparablePair<?,?>) o; if (first == null) { if (other.first != null) return false; } else if (!first.equals(other.first)) { return false; } if (second == null) { if (other.second != null) return false; } else if (!second.equals(other.second)) { return false; } return true; } /** * {@inheritDoc} */ @Override public int hashCode() { return hash; } private int hash() { final int prime = 31; int result = 1; if (first != null) { result *= prime; result += first.hashCode(); } if (second != null) { result *= prime; result += second.hashCode(); } return result; } /** * {@inheritDoc} */ @Override public int compareTo(ComparablePair<T1, T2> other) { return ComparisonChain.start(). compare(first(), other.first()). compare(second(), other.second()). result(); } /** * {@inheritDoc} */ @Override public String toString() { return "Pair [ " + first + ", " + second + " ]"; } }
apache-2.0
sonalgoyal/hiho
src/main/java/co/nubetech/hiho/mapreduce/lib/db/apache/DateSplitter.java
6334
/** * 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 co.nubetech.hiho.mapreduce.lib.db.apache; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.InputSplit; /** * Implement DBSplitter over date/time values. * Make use of logic from IntegerSplitter, since date/time are just longs * in Java. */ @InterfaceAudience.Public @InterfaceStability.Evolving public class DateSplitter extends IntegerSplitter { private static final Log LOG = LogFactory.getLog(DateSplitter.class); public List<InputSplit> split(Configuration conf, ResultSet results, String colName) throws SQLException { long minVal; long maxVal; int sqlDataType = results.getMetaData().getColumnType(1); minVal = resultSetColToLong(results, 1, sqlDataType); maxVal = resultSetColToLong(results, 2, sqlDataType); String lowClausePrefix = colName + " >= "; String highClausePrefix = colName + " < "; int numSplits = conf.getInt(MRJobConfig.NUM_MAPS, 1); if (numSplits < 1) { numSplits = 1; } if (minVal == Long.MIN_VALUE && maxVal == Long.MIN_VALUE) { // The range of acceptable dates is NULL to NULL. Just create a single split. List<InputSplit> splits = new ArrayList<InputSplit>(); splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit( colName + " IS NULL", colName + " IS NULL")); return splits; } // Gather the split point integers List<Long> splitPoints = split(numSplits, minVal, maxVal); List<InputSplit> splits = new ArrayList<InputSplit>(); // Turn the split points into a set of intervals. long start = splitPoints.get(0); Date startDate = longToDate(start, sqlDataType); if (sqlDataType == Types.TIMESTAMP) { // The lower bound's nanos value needs to match the actual lower-bound nanos. try { ((java.sql.Timestamp) startDate).setNanos(results.getTimestamp(1).getNanos()); } catch (NullPointerException npe) { // If the lower bound was NULL, we'll get an NPE; just ignore it and don't set nanos. } } for (int i = 1; i < splitPoints.size(); i++) { long end = splitPoints.get(i); Date endDate = longToDate(end, sqlDataType); if (i == splitPoints.size() - 1) { if (sqlDataType == Types.TIMESTAMP) { // The upper bound's nanos value needs to match the actual upper-bound nanos. try { ((java.sql.Timestamp) endDate).setNanos(results.getTimestamp(2).getNanos()); } catch (NullPointerException npe) { // If the upper bound was NULL, we'll get an NPE; just ignore it and don't set nanos. } } // This is the last one; use a closed interval. splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit( lowClausePrefix + dateToString(startDate), colName + " <= " + dateToString(endDate))); } else { // Normal open-interval case. splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit( lowClausePrefix + dateToString(startDate), highClausePrefix + dateToString(endDate))); } start = end; startDate = endDate; } if (minVal == Long.MIN_VALUE || maxVal == Long.MIN_VALUE) { // Add an extra split to handle the null case that we saw. splits.add(new DataDrivenDBInputFormat.DataDrivenDBInputSplit( colName + " IS NULL", colName + " IS NULL")); } return splits; } /** Retrieve the value from the column in a type-appropriate manner and return its timestamp since the epoch. If the column is null, then return Long.MIN_VALUE. This will cause a special split to be generated for the NULL case, but may also cause poorly-balanced splits if most of the actual dates are positive time since the epoch, etc. */ private long resultSetColToLong(ResultSet rs, int colNum, int sqlDataType) throws SQLException { try { switch (sqlDataType) { case Types.DATE: return rs.getDate(colNum).getTime(); case Types.TIME: return rs.getTime(colNum).getTime(); case Types.TIMESTAMP: return rs.getTimestamp(colNum).getTime(); default: throw new SQLException("Not a date-type field"); } } catch (NullPointerException npe) { // null column. return minimum long value. LOG.warn("Encountered a NULL date in the split column. Splits may be poorly balanced."); return Long.MIN_VALUE; } } /** Parse the long-valued timestamp into the appropriate SQL date type. */ private Date longToDate(long val, int sqlDataType) { switch (sqlDataType) { case Types.DATE: return new java.sql.Date(val); case Types.TIME: return new java.sql.Time(val); case Types.TIMESTAMP: return new java.sql.Timestamp(val); default: // Shouldn't ever hit this case. return null; } } /** * Given a Date 'd', format it as a string for use in a SQL date * comparison operation. * @param d the date to format. * @return the string representing this date in SQL with any appropriate * quotation characters, etc. */ protected String dateToString(Date d) { return "'" + d.toString() + "'"; } }
apache-2.0
smeverts/Threads-Demo
src/com/greyskysoftware/demo/apps/ThreadDemo.java
1890
/* * Copyright (C) 2012 Scott M. Everts Greysky Software. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.greyskysoftware.demo.apps; import java.util.concurrent.atomic.AtomicBoolean; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ProgressBar; public class ThreadDemo extends Activity { ProgressBar bar; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { bar.incrementProgressBy(5); } }; AtomicBoolean isRunning = new AtomicBoolean(false); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.threaddemo); bar = (ProgressBar)findViewById(R.id.progress); } public void onStart() { super.onStart(); bar.setProgress(0); Thread background = new Thread(new Runnable() { public void run() { try { for (int i=0;i<20 && isRunning.get(); i++) { Thread.sleep(1000); handler.sendMessage(handler.obtainMessage()); } } catch (Throwable t) { } } }); isRunning.set(true); background.start(); } public void onStop() { super.onStop(); isRunning.set(false); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-frauddetector/src/main/java/com/amazonaws/services/frauddetector/model/transform/UpdateEventLabelRequestProtocolMarshaller.java
2737
/* * 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.frauddetector.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.frauddetector.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateEventLabelRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateEventLabelRequestProtocolMarshaller implements Marshaller<Request<UpdateEventLabelRequest>, UpdateEventLabelRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AWSHawksNestServiceFacade.UpdateEventLabel").serviceName("AmazonFraudDetector").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public UpdateEventLabelRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<UpdateEventLabelRequest> marshall(UpdateEventLabelRequest updateEventLabelRequest) { if (updateEventLabelRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<UpdateEventLabelRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, updateEventLabelRequest); protocolMarshaller.startMarshalling(); UpdateEventLabelRequestMarshaller.getInstance().marshall(updateEventLabelRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
spinnaker/halyard
halyard-web/src/main/java/com/netflix/spinnaker/halyard/controllers/v1/DeploymentEnvironmentController.java
3147
/* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.spinnaker.halyard.controllers.v1; import com.netflix.spinnaker.halyard.config.config.v1.HalconfigDirectoryStructure; import com.netflix.spinnaker.halyard.config.config.v1.HalconfigParser; import com.netflix.spinnaker.halyard.config.model.v1.node.DeploymentEnvironment; import com.netflix.spinnaker.halyard.config.model.v1.node.Halconfig; import com.netflix.spinnaker.halyard.config.services.v1.DeploymentEnvironmentService; import com.netflix.spinnaker.halyard.core.tasks.v1.DaemonTask; import com.netflix.spinnaker.halyard.models.v1.ValidationSettings; import com.netflix.spinnaker.halyard.util.v1.GenericGetRequest; import com.netflix.spinnaker.halyard.util.v1.GenericUpdateRequest; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @RestController @RequiredArgsConstructor @RequestMapping("/v1/config/deployments/{deploymentName:.+}/deploymentEnvironment") public class DeploymentEnvironmentController { private final HalconfigParser halconfigParser; private final DeploymentEnvironmentService deploymentEnvironmentService; private final HalconfigDirectoryStructure halconfigDirectoryStructure; @RequestMapping(value = "/", method = RequestMethod.GET) DaemonTask<Halconfig, DeploymentEnvironment> getDeploymentEnvironment( @PathVariable String deploymentName, @ModelAttribute ValidationSettings validationSettings) { return GenericGetRequest.<DeploymentEnvironment>builder() .getter(() -> deploymentEnvironmentService.getDeploymentEnvironment(deploymentName)) .validator(() -> deploymentEnvironmentService.validateDeploymentEnvironment(deploymentName)) .description("Get the deployment environment") .build() .execute(validationSettings); } @RequestMapping(value = "/", method = RequestMethod.PUT) DaemonTask<Halconfig, Void> setDeploymentEnvironment( @PathVariable String deploymentName, @ModelAttribute ValidationSettings validationSettings, @RequestBody DeploymentEnvironment deploymentEnvironment) { return GenericUpdateRequest.<DeploymentEnvironment>builder(halconfigParser) .stagePath(halconfigDirectoryStructure.getStagingPath(deploymentName)) .updater(d -> deploymentEnvironmentService.setDeploymentEnvironment(deploymentName, d)) .validator(() -> deploymentEnvironmentService.validateDeploymentEnvironment(deploymentName)) .description("Edit the deployment environment") .build() .execute(validationSettings, deploymentEnvironment); } }
apache-2.0
b-slim/hive
ql/src/java/org/apache/hadoop/hive/ql/metadata/PartitionTree.java
10177
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.metadata; import org.apache.hadoop.hive.metastore.api.AlreadyExistsException; import org.apache.hadoop.hive.metastore.api.InvalidOperationException; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; import org.apache.hadoop.hive.metastore.api.Partition; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static org.apache.hadoop.hive.metastore.Warehouse.makePartName; import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.makePartNameMatcher; /** * Always clone objects before adding or returning them so that callers don't modify them * via references. */ final class PartitionTree { private Map<String, org.apache.hadoop.hive.metastore.api.Partition> parts = new LinkedHashMap<>(); private final org.apache.hadoop.hive.metastore.api.Table tTable; PartitionTree(org.apache.hadoop.hive.metastore.api.Table t) { this.tTable = t; } Partition addPartition(Partition partition, String partName, boolean ifNotExists) throws AlreadyExistsException { partition.setDbName(partition.getDbName().toLowerCase()); partition.setTableName(partition.getTableName().toLowerCase()); if (!ifNotExists && parts.containsKey(partName)) { throw new AlreadyExistsException("Partition " + partName + " already exists"); } return parts.putIfAbsent(partName, partition); } /** * @param partName - "p=1/q=2" full partition name {@link Warehouse#makePartName(List, List)} * @return null if doesn't exist */ Partition getPartition(String partName) { return parts.get(partName); } /** * Get a partition matching the partition values. * * @param partVals partition values for this partition, must be in the same order as the * partition keys of the table. * @return the partition object, or if not found null. * @throws MetaException partition values are incorrect. */ Partition getPartition(List<String> partVals) throws MetaException { String partName = makePartName(tTable.getPartitionKeys(), partVals); return getPartition(partName); } /** * Add partitions to the partition tree. * * @param partitions The partitions to add * @param ifNotExists only add partitions if they don't exist * @return the partitions that were added * @throws MetaException partition metadata is incorrect * @throws AlreadyExistsException if the partition with the same name already exists. */ List<Partition> addPartitions(List<Partition> partitions, boolean ifNotExists) throws MetaException, AlreadyExistsException { List<Partition> partitionsAdded = new ArrayList<>(); Map<String, Partition> partNameToPartition = new HashMap<>(); // validate that the new partition values is not already added to the table for (Partition partition : partitions) { String partName = makePartName(tTable.getPartitionKeys(), partition.getValues()); if (!ifNotExists && parts.containsKey(partName)) { throw new AlreadyExistsException("Partition " + partName + " already exists"); } partNameToPartition.put(partName, partition); } for (Map.Entry<String, Partition> entry : partNameToPartition.entrySet()) { if (addPartition(entry.getValue(), entry.getKey(), ifNotExists) == null) { partitionsAdded.add(entry.getValue()); } } return partitionsAdded; } /** * Provided values for the 1st N partition columns, will return all matching PartitionS * The list is a partial list of partition values in the same order as partition columns. * Missing values should be represented as "" (empty strings). May provide fewer values. * So if part cols are a,b,c, {"",2} is a valid list * {@link MetaStoreUtils#getPvals(List, Map)} */ List<Partition> getPartitionsByPartitionVals(List<String> partialPartVals) throws MetaException { if (partialPartVals == null || partialPartVals.isEmpty()) { throw new MetaException("Partition partial vals cannot be null or empty"); } String partNameMatcher = makePartNameMatcher(tTable, partialPartVals, ".*"); List<Partition> matchedPartitions = new ArrayList<>(); for (Map.Entry<String, Partition> entry : parts.entrySet()) { if (entry.getKey().matches(partNameMatcher)) { matchedPartitions.add(entry.getValue()); } } return matchedPartitions; } /** * Get all the partitions. * * @return partitions list */ List<Partition> listPartitions() { return new ArrayList<>(parts.values()); } /** * Remove a partition from the table. * @param partVals partition values, must be not null * @return the instance of the dropped partition, if the remove was successful, otherwise false * @throws MetaException partition with the provided partition values cannot be found. */ Partition dropPartition(List<String> partVals) throws MetaException, NoSuchObjectException { String partName = makePartName(tTable.getPartitionKeys(), partVals); if (!parts.containsKey(partName)) { throw new NoSuchObjectException( "Partition with partition values " + Arrays.toString(partVals.toArray()) + " is not found."); } return parts.remove(partName); } /** * Alter an existing partition. The flow is following: * <p> * 1) search for existing partition * 2) if found delete it * 3) insert new partition * </p> * @param oldPartitionVals the values of existing partition, which is altered, must be not null. * @param newPartition the new partition, must be not null. * @param isRename true, if rename is requested, meaning that all properties of partition can be changed, except * of its location. * @throws MetaException table or db name is altered. * @throws InvalidOperationException the new partition values are null, or the old partition cannot be found. */ void alterPartition(List<String> oldPartitionVals, Partition newPartition, boolean isRename) throws MetaException, InvalidOperationException, NoSuchObjectException { if (oldPartitionVals == null || oldPartitionVals.isEmpty()) { throw new InvalidOperationException("Old partition values cannot be null or empty."); } if (newPartition == null) { throw new InvalidOperationException("New partition cannot be null."); } Partition oldPartition = getPartition(oldPartitionVals); if (oldPartition == null) { throw new InvalidOperationException( "Partition with partition values " + Arrays.toString(oldPartitionVals.toArray()) + " is not found."); } if (!oldPartition.getDbName().equals(newPartition.getDbName())) { throw new MetaException("Db name cannot be altered."); } if (!oldPartition.getTableName().equals(newPartition.getTableName())) { throw new MetaException("Table name cannot be altered."); } if (isRename) { newPartition.getSd().setLocation(oldPartition.getSd().getLocation()); } dropPartition(oldPartitionVals); String partName = makePartName(tTable.getPartitionKeys(), newPartition.getValues()); if (parts.containsKey(partName)) { throw new InvalidOperationException("Partition " + partName + " already exists"); } parts.put(partName, newPartition); } /** * Alter multiple partitions. This operation is transactional. * @param newParts list of new partitions, must be not null. * @throws MetaException table or db name is altered. * @throws InvalidOperationException the new partition values are null, or the old partition cannot be found. * @throws NoSuchObjectException the old partition cannot be found. */ void alterPartitions(List<Partition> newParts) throws MetaException, InvalidOperationException, NoSuchObjectException { //altering partitions in a batch must be transactional, therefore bofore starting the altering, clone the original //partitions map. If something fails, revert it back. Map<String, Partition> clonedPartitions = new LinkedHashMap<>(); parts.forEach((key, value) -> clonedPartitions.put(key, new Partition(value))); for (Partition partition : newParts) { try { if (partition == null) { throw new InvalidOperationException("New partition cannot be null."); } alterPartition(partition.getValues(), partition, false); } catch (MetaException | InvalidOperationException | NoSuchObjectException e) { parts = clonedPartitions; throw e; } } } /** * Rename an existing partition. * @param oldPartitionVals the values of existing partition, which is renamed, must be not null. * @param newPart the new partition, must be not null. * @throws MetaException table or db name is altered. * @throws InvalidOperationException the new partition values are null, or the old partition cannot be altered. * @throws NoSuchObjectException the old partition cannot be found. */ void renamePartition(List<String> oldPartitionVals, Partition newPart) throws MetaException, InvalidOperationException, NoSuchObjectException { alterPartition(oldPartitionVals, newPart, true); } }
apache-2.0
tomasonjo/neo4j-graph-algorithms
algo/src/main/java/algo/algo/algorithms/AlgoUtils.java
4640
package algo.algo.algorithms; import org.neo4j.cypher.EntityNotFoundException; import org.neo4j.graphdb.Transaction; import org.neo4j.kernel.api.DataWriteOperations; import org.neo4j.kernel.api.exceptions.InvalidTransactionTypeKernelException; import org.neo4j.kernel.api.exceptions.legacyindex.AutoIndexingKernelException; import org.neo4j.kernel.api.exceptions.schema.ConstraintValidationKernelException; import org.neo4j.kernel.api.exceptions.schema.IllegalTokenNameException; import org.neo4j.kernel.api.properties.DefinedProperty; import org.neo4j.kernel.impl.core.ThreadToStatementContextBridge; import org.neo4j.kernel.internal.GraphDatabaseAPI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public class AlgoUtils { public static final String SETTING_CYPHER_NODE = "node_cypher"; public static final String SETTING_CYPHER_REL = "rel_cypher"; public static final String SETTING_WRITE = "write"; public static final String SETTING_WEIGHTED = "weight"; public static final String SETTING_BATCH_SIZE = "batchSize"; public static final String DEFAULT_CYPHER_REL = "MATCH (s)-[r]->(t) RETURN id(s) as source, id(t) as target, 1 as weight"; public static final String DEFAULT_CYPHER_NODE = "MATCH (s) RETURN id(s) as id"; public static final boolean DEFAULT_PAGE_RANK_WRITE = false; public static String getCypher(Map<String, Object> config, String setting, String defaultString) { String cypher = (String)config.getOrDefault(setting, defaultString); if ("none".equals(cypher)) return null; if (cypher == null || cypher.isEmpty()) { return defaultString; } return cypher; } public static int waitForTasks( List<Future> futures ) { int total = 0; for ( Future future : futures ) { try { future.get(); total++; } catch ( InterruptedException | ExecutionException e ) { e.printStackTrace(); } } futures.clear(); return total; } public static void writeBackResults(ExecutorService pool, GraphDatabaseAPI db, AlgorithmInterface algorithm, int batchSize) { ThreadToStatementContextBridge ctx = db.getDependencyResolver().resolveDependency(ThreadToStatementContextBridge.class); int propertyNameId; try (Transaction tx = db.beginTx()) { propertyNameId = ctx.get().tokenWriteOperations().propertyKeyGetOrCreateForName(algorithm.getPropertyName()); tx.success(); } catch (IllegalTokenNameException e) { throw new RuntimeException(e); } final long totalNodes = algorithm.numberOfNodes(); int batches = (int) totalNodes / batchSize; List<Future> futures = new ArrayList<>(batches); for (int i = 0; i < totalNodes; i += batchSize) { int nodeIndex = i; final int start = nodeIndex; Future future = pool.submit(new Runnable() { public void run() { try (Transaction tx = db.beginTx()) { DataWriteOperations ops = ctx.get().dataWriteOperations(); for (int i = 0; i < batchSize; i++) { int nodeIndex = i + start; if (nodeIndex >= totalNodes) break; long graphNode = algorithm.getMappedNode(nodeIndex); double value = algorithm.getResult(graphNode); if (graphNode == -1) { System.out.println("Node node found for " + graphNode + " mapped node " + nodeIndex); } else ops.nodeSetProperty(graphNode, DefinedProperty.doubleProperty(propertyNameId, value)); } tx.success(); } catch (ConstraintValidationKernelException | InvalidTransactionTypeKernelException | EntityNotFoundException | AutoIndexingKernelException | org.neo4j.kernel.api.exceptions.EntityNotFoundException e) { e.printStackTrace(); } } }); futures.add(future); } AlgoUtils.waitForTasks(futures); } }
apache-2.0
clonetwin26/buck
src/com/facebook/buck/python/PythonBinaryDescription.java
15828
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.python; import com.facebook.buck.cxx.toolchain.CxxBuckConfig; import com.facebook.buck.cxx.toolchain.CxxPlatform; import com.facebook.buck.cxx.toolchain.CxxPlatformsProvider; import com.facebook.buck.cxx.toolchain.linker.WindowsLinker; import com.facebook.buck.file.WriteFile; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.log.Logger; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargets; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.FlavorDomain; import com.facebook.buck.model.InternalFlavor; import com.facebook.buck.python.toolchain.PexToolProvider; import com.facebook.buck.python.toolchain.PythonPlatform; import com.facebook.buck.python.toolchain.PythonPlatformsProvider; import com.facebook.buck.rules.BuildRuleCreationContext; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.CommonDescriptionArg; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.Description; import com.facebook.buck.rules.HasDeclaredDeps; import com.facebook.buck.rules.HasTests; import com.facebook.buck.rules.ImplicitDepsInferringDescription; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.SymlinkTree; import com.facebook.buck.rules.coercer.PatternMatchedCollection; import com.facebook.buck.rules.macros.StringWithMacros; import com.facebook.buck.rules.macros.StringWithMacrosConverter; import com.facebook.buck.toolchain.ToolchainProvider; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.Optionals; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.facebook.buck.versions.HasVersionUniverse; import com.facebook.buck.versions.VersionRoot; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import java.nio.file.Path; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import org.immutables.value.Value; public class PythonBinaryDescription implements Description<PythonBinaryDescriptionArg>, ImplicitDepsInferringDescription< PythonBinaryDescription.AbstractPythonBinaryDescriptionArg>, VersionRoot<PythonBinaryDescriptionArg> { private static final Logger LOG = Logger.get(PythonBinaryDescription.class); private final ToolchainProvider toolchainProvider; private final PythonBuckConfig pythonBuckConfig; private final CxxBuckConfig cxxBuckConfig; public PythonBinaryDescription( ToolchainProvider toolchainProvider, PythonBuckConfig pythonBuckConfig, CxxBuckConfig cxxBuckConfig) { this.toolchainProvider = toolchainProvider; this.pythonBuckConfig = pythonBuckConfig; this.cxxBuckConfig = cxxBuckConfig; } @Override public Class<PythonBinaryDescriptionArg> getConstructorArgType() { return PythonBinaryDescriptionArg.class; } public static BuildTarget getEmptyInitTarget(BuildTarget baseTarget) { return baseTarget.withAppendedFlavors(InternalFlavor.of("__init__")); } public static SourcePath createEmptyInitModule( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleResolver resolver) { BuildTarget emptyInitTarget = getEmptyInitTarget(buildTarget); Path emptyInitPath = BuildTargets.getGenPath(projectFilesystem, buildTarget, "%s/__init__.py"); WriteFile rule = resolver.addToIndex( new WriteFile( emptyInitTarget, projectFilesystem, "", emptyInitPath, /* executable */ false)); return rule.getSourcePathToOutput(); } public static ImmutableMap<Path, SourcePath> addMissingInitModules( ImmutableMap<Path, SourcePath> modules, SourcePath emptyInit) { Map<Path, SourcePath> initModules = new LinkedHashMap<>(); // Insert missing `__init__.py` modules. Set<Path> packages = new HashSet<>(); for (Path module : modules.keySet()) { Path pkg = module; while ((pkg = pkg.getParent()) != null && !packages.contains(pkg)) { Path init = pkg.resolve("__init__.py"); if (!modules.containsKey(init)) { initModules.put(init, emptyInit); } packages.add(pkg); } } return ImmutableMap.<Path, SourcePath>builder().putAll(modules).putAll(initModules).build(); } private PythonInPlaceBinary createInPlaceBinaryRule( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildRuleResolver resolver, SourcePathRuleFinder ruleFinder, PythonPlatform pythonPlatform, CxxPlatform cxxPlatform, String mainModule, Optional<String> extension, PythonPackageComponents components, ImmutableSet<String> preloadLibraries) { // We don't currently support targeting Windows. if (cxxPlatform.getLd().resolve(resolver) instanceof WindowsLinker) { throw new HumanReadableException( "%s: cannot build in-place python binaries for Windows (%s)", buildTarget, cxxPlatform.getFlavor()); } // Add in any missing init modules into the python components. SourcePath emptyInit = createEmptyInitModule(buildTarget, projectFilesystem, resolver); components = components.withModules(addMissingInitModules(components.getModules(), emptyInit)); BuildTarget linkTreeTarget = buildTarget.withAppendedFlavors(InternalFlavor.of("link-tree")); Path linkTreeRoot = BuildTargets.getGenPath(projectFilesystem, linkTreeTarget, "%s"); SymlinkTree linkTree = resolver.addToIndex( new SymlinkTree( "python_in_place_binary", linkTreeTarget, projectFilesystem, linkTreeRoot, ImmutableMap.<Path, SourcePath>builder() .putAll(components.getModules()) .putAll(components.getResources()) .putAll(components.getNativeLibraries()) .build(), components.getModuleDirs(), ruleFinder)); return new PythonInPlaceBinary( buildTarget, projectFilesystem, resolver, params.getDeclaredDeps(), cxxPlatform, pythonPlatform, mainModule, components, extension.orElse(pythonBuckConfig.getPexExtension()), preloadLibraries, pythonBuckConfig.legacyOutputPath(), linkTree, pythonPlatform.getEnvironment()); } PythonBinary createPackageRule( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildRuleResolver resolver, SourcePathRuleFinder ruleFinder, PythonPlatform pythonPlatform, CxxPlatform cxxPlatform, String mainModule, Optional<String> extension, PythonPackageComponents components, ImmutableList<String> buildArgs, PythonBuckConfig.PackageStyle packageStyle, ImmutableSet<String> preloadLibraries) { switch (packageStyle) { case INPLACE: return createInPlaceBinaryRule( buildTarget, projectFilesystem, params, resolver, ruleFinder, pythonPlatform, cxxPlatform, mainModule, extension, components, preloadLibraries); case STANDALONE: return new PythonPackagedBinary( buildTarget, projectFilesystem, ruleFinder, params.getDeclaredDeps(), pythonPlatform, toolchainProvider .getByName(PexToolProvider.DEFAULT_NAME, PexToolProvider.class) .getPexTool(resolver), buildArgs, pythonBuckConfig.getPexExecutor(resolver).orElse(pythonPlatform.getEnvironment()), extension.orElse(pythonBuckConfig.getPexExtension()), pythonPlatform.getEnvironment(), mainModule, components, preloadLibraries, pythonBuckConfig.shouldCacheBinaries(), pythonBuckConfig.legacyOutputPath()); default: throw new IllegalStateException(); } } private CxxPlatform getCxxPlatform(BuildTarget target, AbstractPythonBinaryDescriptionArg args) { CxxPlatformsProvider cxxPlatformsProvider = toolchainProvider.getByName(CxxPlatformsProvider.DEFAULT_NAME, CxxPlatformsProvider.class); FlavorDomain<CxxPlatform> cxxPlatforms = cxxPlatformsProvider.getCxxPlatforms(); return cxxPlatforms .getValue(target) .orElse( args.getCxxPlatform() .map(cxxPlatforms::getValue) .orElse(cxxPlatformsProvider.getDefaultCxxPlatform())); } @Override public PythonBinary createBuildRule( BuildRuleCreationContext context, BuildTarget buildTarget, BuildRuleParams params, PythonBinaryDescriptionArg args) { if (args.getMain().isPresent() == args.getMainModule().isPresent()) { throw new HumanReadableException( "%s: must set exactly one of `main_module` and `main`", buildTarget); } Path baseModule = PythonUtil.getBasePath(buildTarget, args.getBaseModule()); String mainModule; ImmutableMap.Builder<Path, SourcePath> modules = ImmutableMap.builder(); BuildRuleResolver resolver = context.getBuildRuleResolver(); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); // If `main` is set, add it to the map of modules for this binary and also set it as the // `mainModule`, otherwise, use the explicitly set main module. if (args.getMain().isPresent()) { LOG.warn( "%s: parameter `main` is deprecated, please use `main_module` instead.", buildTarget); String mainName = pathResolver.getSourcePathName(buildTarget, args.getMain().get()); Path main = baseModule.resolve(mainName); modules.put(baseModule.resolve(mainName), args.getMain().get()); mainModule = PythonUtil.toModuleName(buildTarget, main.toString()); } else { mainModule = args.getMainModule().get(); } // Build up the list of all components going into the python binary. PythonPackageComponents binaryPackageComponents = PythonPackageComponents.of( modules.build(), /* resources */ ImmutableMap.of(), /* nativeLibraries */ ImmutableMap.of(), /* moduleDirs */ ImmutableMultimap.of(), /* zipSafe */ args.getZipSafe()); FlavorDomain<PythonPlatform> pythonPlatforms = toolchainProvider .getByName(PythonPlatformsProvider.DEFAULT_NAME, PythonPlatformsProvider.class) .getPythonPlatforms(); // Extract the platforms from the flavor, falling back to the default platforms if none are // found. PythonPlatform pythonPlatform = pythonPlatforms .getValue(buildTarget) .orElse( pythonPlatforms.getValue( args.getPlatform() .<Flavor>map(InternalFlavor::of) .orElse(pythonPlatforms.getFlavors().iterator().next()))); CxxPlatform cxxPlatform = getCxxPlatform(buildTarget, args); CellPathResolver cellRoots = context.getCellPathResolver(); ProjectFilesystem projectFilesystem = context.getProjectFilesystem(); StringWithMacrosConverter macrosConverter = StringWithMacrosConverter.builder() .setBuildTarget(buildTarget) .setCellPathResolver(cellRoots) .setResolver(resolver) .setExpanders(PythonUtil.MACRO_EXPANDERS) .build(); PythonPackageComponents allPackageComponents = PythonUtil.getAllComponents( cellRoots, buildTarget, projectFilesystem, params, resolver, ruleFinder, PythonUtil.getDeps(pythonPlatform, cxxPlatform, args.getDeps(), args.getPlatformDeps()) .stream() .map(resolver::getRule) .collect(ImmutableList.toImmutableList()), binaryPackageComponents, pythonPlatform, cxxBuckConfig, cxxPlatform, args.getLinkerFlags() .stream() .map(macrosConverter::convert) .collect(ImmutableList.toImmutableList()), pythonBuckConfig.getNativeLinkStrategy(), args.getPreloadDeps()); return createPackageRule( buildTarget, projectFilesystem, params, resolver, ruleFinder, pythonPlatform, cxxPlatform, mainModule, args.getExtension(), allPackageComponents, args.getBuildArgs(), args.getPackageStyle().orElse(pythonBuckConfig.getPackageStyle()), PythonUtil.getPreloadNames(resolver, cxxPlatform, args.getPreloadDeps())); } @Override public void findDepsForTargetFromConstructorArgs( BuildTarget buildTarget, CellPathResolver cellRoots, AbstractPythonBinaryDescriptionArg constructorArg, ImmutableCollection.Builder<BuildTarget> extraDepsBuilder, ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) { // We need to use the C/C++ linker for native libs handling, so add in the C/C++ linker to // parse time deps. extraDepsBuilder.addAll(getCxxPlatform(buildTarget, constructorArg).getLd().getParseTimeDeps()); if (constructorArg.getPackageStyle().orElse(pythonBuckConfig.getPackageStyle()) == PythonBuckConfig.PackageStyle.STANDALONE) { Optionals.addIfPresent(pythonBuckConfig.getPexTarget(), extraDepsBuilder); Optionals.addIfPresent(pythonBuckConfig.getPexExecutorTarget(), extraDepsBuilder); } } @BuckStyleImmutable @Value.Immutable interface AbstractPythonBinaryDescriptionArg extends CommonDescriptionArg, HasDeclaredDeps, HasTests, HasVersionUniverse { Optional<SourcePath> getMain(); Optional<String> getMainModule(); @Value.Default default PatternMatchedCollection<ImmutableSortedSet<BuildTarget>> getPlatformDeps() { return PatternMatchedCollection.of(); } Optional<String> getBaseModule(); Optional<Boolean> getZipSafe(); ImmutableList<String> getBuildArgs(); Optional<String> getPlatform(); Optional<Flavor> getCxxPlatform(); Optional<PythonBuckConfig.PackageStyle> getPackageStyle(); ImmutableSet<BuildTarget> getPreloadDeps(); ImmutableList<StringWithMacros> getLinkerFlags(); Optional<String> getExtension(); } }
apache-2.0
PUREMoneySystems/firstlight
src/main/java/com/firstlight/wallet/WalletBase.java
2231
/** * */ package com.firstlight.wallet; import java.util.ArrayList; import java.util.List; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import org.jrebirth.core.ui.fxml.DefaultFXMLModel; /** * @author MrMoneyChanger * */ @SuppressWarnings("rawtypes") public abstract class WalletBase<W extends WalletBase> extends DefaultFXMLModel<W> implements IWallet { /** The wallet name. */ private String name = ""; /** The wallet hash code. */ private String hashCode = ""; //TODO: Refactor this using IWalletStorageLocation /** The wallet file location. */ private String location = ""; /** The wallet state. */ private WalletState walletState = WalletState.closed; private BooleanProperty walletStateChanged = new SimpleBooleanProperty(false); /** The wallet asset accounts */ private List<IAssetAccount> assetAccounts = new ArrayList<IAssetAccount>(); @Override public String getName() { return this.name; } @Override public void setName(String newName) { this.name = newName; } @Override public String getHashCode() { return this.hashCode; } @Override public void setHashCode(String newHashCode) { this.hashCode = newHashCode; } @Override public String getLocation() { return this.location; } @Override public void setLocation(String newLocation) { this.location = newLocation; } @Override public WalletState getWalletState() { return this.walletState; } @Override public void setWalletState(WalletState state) { this.walletState = state; } @Override public List<IAssetAccount> getAssetAccounts(){ return this.assetAccounts; } @Override public void setAssetAccounts(List<IAssetAccount> assetAccounts){ this.assetAccounts = assetAccounts; } public Boolean getWalletStateChanged(){ return this.walletStateChanged.get(); } public ReadOnlyBooleanProperty walletStateChangedProperty(){ return this.walletStateChanged; } public void indicateWalletStateChangeStarted(){ this.walletStateChanged.set(true); } public void indicateWalletStateChangeCompleted(){ this.walletStateChanged.set(false); } }
apache-2.0
nopbyte/compose-idm
src/main/java/de/passau/uni/sec/compose/id/core/event/UpdateUserEvent.java
2063
package de.passau.uni.sec.compose.id.core.event; import java.util.Collection; import java.util.List; import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.passau.uni.sec.compose.id.core.domain.IPrincipal; import de.passau.uni.sec.compose.id.core.service.security.RestAuthentication; import de.passau.uni.sec.compose.id.rest.messages.ExtraAttributeMessage; import de.passau.uni.sec.compose.id.rest.messages.MembershipResponseMessage; import de.passau.uni.sec.compose.id.rest.messages.UserCreateMessage; import de.passau.uni.sec.compose.id.rest.messages.UserUpdateMessage; public class UpdateUserEvent extends AbstractUpdateEvent implements Event { private UserCreateMessage message; /** * Latest modification as epoch */ private static Logger LOG = LoggerFactory.getLogger(UpdateUserEvent.class); public UserCreateMessage getMessage() { return message; } public void setMessage(UserCreateMessage message) { this.message = message; } public UpdateUserEvent(String id, UserCreateMessage messate, Collection<IPrincipal> principals, long lastKnownUpdate) { super.entityId = id; super.setLastModifiedKnown(lastKnownUpdate); this.message = messate; this.principals = principals; } @Override public String getLoggingDetails() { /*String updateData = "extra_attributes = ["; List<ExtraAttributeMessage> as= this.message.getExtraAttributes(); for (ExtraAttributeMessage at: as) updateData += at.getName()+","+at.getValue(); updateData+= "]"; updateData+= ",memberships = ["; List<MembershipResponseMessage> me = this.message.getMemberships(); for(MembershipResponseMessage memb: me) updateData += "(group:"+memb.getGroup()+", role:"+memb.getRole()+")"; updateData+= "]"; //TODO update attributes defined for update return "Updating single user : "+updateData+ " principals: "+RestAuthentication.getBasicInfoPrincipals(principals); */ return "Updating user with id "+entityId+". New values: "+message.getUsername(); } }
apache-2.0
85977328/logcenter
src/main/java/com/panguso/lc/analysis/format/dao/impl/LogFormatDaoImpl.java
750
/** * Copyright (c) 2011-2020 Panguso, Inc. * All rights reserved. * * This software is the confidential and proprietary information of Panguso, * Inc. ("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 Panguso. */ package com.panguso.lc.analysis.format.dao.impl; import org.springframework.stereotype.Repository; import com.panguso.lc.analysis.format.dao.ILogFormatDao; import com.panguso.lc.analysis.format.entity.LogFormat; /** * @author piaohailin * @date 2012-8-24 */ @Repository public class LogFormatDaoImpl extends DaoImpl<LogFormat> implements ILogFormatDao { }
apache-2.0