repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
mscg82/Slide | app/src/main/java/me/ccrama/redditslide/Adapters/ImageGridAdapterTumblr.java | 2343 | package me.ccrama.redditslide.Adapters;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import java.util.List;
import me.ccrama.redditslide.ImgurAlbum.Image;
import me.ccrama.redditslide.Reddit;
import me.ccrama.redditslide.Tumblr.Photo;
/**
* Created by carlo_000 on 3/20/2016.
*/
public class ImageGridAdapterTumblr extends android.widget.BaseAdapter {
private Context mContext;
private List<Photo> jsons;
public static final DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisk(true)
.resetViewBeforeLoading(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.EXACTLY)
.cacheInMemory(false)
.displayer(new FadeInBitmapDisplayer(250))
.build();
public ImageGridAdapterTumblr(Context c, List<Photo> jsons) {
mContext = c;
this.jsons = jsons;
}
public int getCount() {
return jsons.size();
}
public String getItem(int position) {
return jsons.get(position).getAltSizes().get(jsons.get(position).getAltSizes().size() - 1).getUrl();
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
GridView grid = (GridView) parent;
int size = grid.getColumnWidth();
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
imageView.setLayoutParams(new GridView.LayoutParams(size, size));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
((Reddit) mContext.getApplicationContext()).getImageLoader().displayImage(getItem(position), imageView, options);
return imageView;
}
} | gpl-3.0 |
srnsw/xena | xena/ext/src/xalan-j_2_7_1/src/org/apache/xalan/res/XSLTErrorResources_zh_TW.java | 74033 | /*
* 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.
*/
/*
* $Id$
*/
package org.apache.xalan.res;
import java.util.ListResourceBundle;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Set up error messages.
* We build a two dimensional array of message keys and
* message strings. In order to add a new message here,
* you need to first add a String constant. And
* you need to enter key , value pair as part of contents
* Array. You also need to update MAX_CODE for error strings
* and MAX_WARNING for warnings ( Needed for only information
* purpose )
*/
public class XSLTErrorResources_zh_TW extends ListResourceBundle
{
/*
* This file contains error and warning messages related to Xalan Error
* Handling.
*
* General notes to translators:
*
* 1) Xalan (or more properly, Xalan-interpretive) and XSLTC are names of
* components.
* XSLT is an acronym for "XML Stylesheet Language: Transformations".
* XSLTC is an acronym for XSLT Compiler.
*
* 2) A stylesheet is a description of how to transform an input XML document
* into a resultant XML document (or HTML document or text). The
* stylesheet itself is described in the form of an XML document.
*
* 3) A template is a component of a stylesheet that is used to match a
* particular portion of an input document and specifies the form of the
* corresponding portion of the output document.
*
* 4) An element is a mark-up tag in an XML document; an attribute is a
* modifier on the tag. For example, in <elem attr='val' attr2='val2'>
* "elem" is an element name, "attr" and "attr2" are attribute names with
* the values "val" and "val2", respectively.
*
* 5) A namespace declaration is a special attribute that is used to associate
* a prefix with a URI (the namespace). The meanings of element names and
* attribute names that use that prefix are defined with respect to that
* namespace.
*
* 6) "Translet" is an invented term that describes the class file that
* results from compiling an XML stylesheet into a Java class.
*
* 7) XPath is a specification that describes a notation for identifying
* nodes in a tree-structured representation of an XML document. An
* instance of that notation is referred to as an XPath expression.
*
*/
/** Maximum error messages, this is needed to keep track of the number of messages. */
public static final int MAX_CODE = 201;
/** Maximum warnings, this is needed to keep track of the number of warnings. */
public static final int MAX_WARNING = 29;
/** Maximum misc strings. */
public static final int MAX_OTHERS = 55;
/** Maximum total warnings and error messages. */
public static final int MAX_MESSAGES = MAX_CODE + MAX_WARNING + 1;
/*
* Static variables
*/
public static final String ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX =
"ER_INVALID_SET_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX";
public static final String ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT =
"ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT";
public static final String ER_NO_CURLYBRACE = "ER_NO_CURLYBRACE";
public static final String ER_FUNCTION_NOT_SUPPORTED = "ER_FUNCTION_NOT_SUPPORTED";
public static final String ER_ILLEGAL_ATTRIBUTE = "ER_ILLEGAL_ATTRIBUTE";
public static final String ER_NULL_SOURCENODE_APPLYIMPORTS = "ER_NULL_SOURCENODE_APPLYIMPORTS";
public static final String ER_CANNOT_ADD = "ER_CANNOT_ADD";
public static final String ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES="ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES";
public static final String ER_NO_NAME_ATTRIB = "ER_NO_NAME_ATTRIB";
public static final String ER_TEMPLATE_NOT_FOUND = "ER_TEMPLATE_NOT_FOUND";
public static final String ER_CANT_RESOLVE_NAME_AVT = "ER_CANT_RESOLVE_NAME_AVT";
public static final String ER_REQUIRES_ATTRIB = "ER_REQUIRES_ATTRIB";
public static final String ER_MUST_HAVE_TEST_ATTRIB = "ER_MUST_HAVE_TEST_ATTRIB";
public static final String ER_BAD_VAL_ON_LEVEL_ATTRIB =
"ER_BAD_VAL_ON_LEVEL_ATTRIB";
public static final String ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML =
"ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML";
public static final String ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME =
"ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME";
public static final String ER_NEED_MATCH_ATTRIB = "ER_NEED_MATCH_ATTRIB";
public static final String ER_NEED_NAME_OR_MATCH_ATTRIB =
"ER_NEED_NAME_OR_MATCH_ATTRIB";
public static final String ER_CANT_RESOLVE_NSPREFIX =
"ER_CANT_RESOLVE_NSPREFIX";
public static final String ER_ILLEGAL_VALUE = "ER_ILLEGAL_VALUE";
public static final String ER_NO_OWNERDOC = "ER_NO_OWNERDOC";
public static final String ER_ELEMTEMPLATEELEM_ERR ="ER_ELEMTEMPLATEELEM_ERR";
public static final String ER_NULL_CHILD = "ER_NULL_CHILD";
public static final String ER_NEED_SELECT_ATTRIB = "ER_NEED_SELECT_ATTRIB";
public static final String ER_NEED_TEST_ATTRIB = "ER_NEED_TEST_ATTRIB";
public static final String ER_NEED_NAME_ATTRIB = "ER_NEED_NAME_ATTRIB";
public static final String ER_NO_CONTEXT_OWNERDOC = "ER_NO_CONTEXT_OWNERDOC";
public static final String ER_COULD_NOT_CREATE_XML_PROC_LIAISON =
"ER_COULD_NOT_CREATE_XML_PROC_LIAISON";
public static final String ER_PROCESS_NOT_SUCCESSFUL =
"ER_PROCESS_NOT_SUCCESSFUL";
public static final String ER_NOT_SUCCESSFUL = "ER_NOT_SUCCESSFUL";
public static final String ER_ENCODING_NOT_SUPPORTED =
"ER_ENCODING_NOT_SUPPORTED";
public static final String ER_COULD_NOT_CREATE_TRACELISTENER =
"ER_COULD_NOT_CREATE_TRACELISTENER";
public static final String ER_KEY_REQUIRES_NAME_ATTRIB =
"ER_KEY_REQUIRES_NAME_ATTRIB";
public static final String ER_KEY_REQUIRES_MATCH_ATTRIB =
"ER_KEY_REQUIRES_MATCH_ATTRIB";
public static final String ER_KEY_REQUIRES_USE_ATTRIB =
"ER_KEY_REQUIRES_USE_ATTRIB";
public static final String ER_REQUIRES_ELEMENTS_ATTRIB =
"ER_REQUIRES_ELEMENTS_ATTRIB";
public static final String ER_MISSING_PREFIX_ATTRIB =
"ER_MISSING_PREFIX_ATTRIB";
public static final String ER_BAD_STYLESHEET_URL = "ER_BAD_STYLESHEET_URL";
public static final String ER_FILE_NOT_FOUND = "ER_FILE_NOT_FOUND";
public static final String ER_IOEXCEPTION = "ER_IOEXCEPTION";
public static final String ER_NO_HREF_ATTRIB = "ER_NO_HREF_ATTRIB";
public static final String ER_STYLESHEET_INCLUDES_ITSELF =
"ER_STYLESHEET_INCLUDES_ITSELF";
public static final String ER_PROCESSINCLUDE_ERROR ="ER_PROCESSINCLUDE_ERROR";
public static final String ER_MISSING_LANG_ATTRIB = "ER_MISSING_LANG_ATTRIB";
public static final String ER_MISSING_CONTAINER_ELEMENT_COMPONENT =
"ER_MISSING_CONTAINER_ELEMENT_COMPONENT";
public static final String ER_CAN_ONLY_OUTPUT_TO_ELEMENT =
"ER_CAN_ONLY_OUTPUT_TO_ELEMENT";
public static final String ER_PROCESS_ERROR = "ER_PROCESS_ERROR";
public static final String ER_UNIMPLNODE_ERROR = "ER_UNIMPLNODE_ERROR";
public static final String ER_NO_SELECT_EXPRESSION ="ER_NO_SELECT_EXPRESSION";
public static final String ER_CANNOT_SERIALIZE_XSLPROCESSOR =
"ER_CANNOT_SERIALIZE_XSLPROCESSOR";
public static final String ER_NO_INPUT_STYLESHEET = "ER_NO_INPUT_STYLESHEET";
public static final String ER_FAILED_PROCESS_STYLESHEET =
"ER_FAILED_PROCESS_STYLESHEET";
public static final String ER_COULDNT_PARSE_DOC = "ER_COULDNT_PARSE_DOC";
public static final String ER_COULDNT_FIND_FRAGMENT =
"ER_COULDNT_FIND_FRAGMENT";
public static final String ER_NODE_NOT_ELEMENT = "ER_NODE_NOT_ELEMENT";
public static final String ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB =
"ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB";
public static final String ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB =
"ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB";
public static final String ER_NO_CLONE_OF_DOCUMENT_FRAG =
"ER_NO_CLONE_OF_DOCUMENT_FRAG";
public static final String ER_CANT_CREATE_ITEM = "ER_CANT_CREATE_ITEM";
public static final String ER_XMLSPACE_ILLEGAL_VALUE =
"ER_XMLSPACE_ILLEGAL_VALUE";
public static final String ER_NO_XSLKEY_DECLARATION =
"ER_NO_XSLKEY_DECLARATION";
public static final String ER_CANT_CREATE_URL = "ER_CANT_CREATE_URL";
public static final String ER_XSLFUNCTIONS_UNSUPPORTED =
"ER_XSLFUNCTIONS_UNSUPPORTED";
public static final String ER_PROCESSOR_ERROR = "ER_PROCESSOR_ERROR";
public static final String ER_NOT_ALLOWED_INSIDE_STYLESHEET =
"ER_NOT_ALLOWED_INSIDE_STYLESHEET";
public static final String ER_RESULTNS_NOT_SUPPORTED =
"ER_RESULTNS_NOT_SUPPORTED";
public static final String ER_DEFAULTSPACE_NOT_SUPPORTED =
"ER_DEFAULTSPACE_NOT_SUPPORTED";
public static final String ER_INDENTRESULT_NOT_SUPPORTED =
"ER_INDENTRESULT_NOT_SUPPORTED";
public static final String ER_ILLEGAL_ATTRIB = "ER_ILLEGAL_ATTRIB";
public static final String ER_UNKNOWN_XSL_ELEM = "ER_UNKNOWN_XSL_ELEM";
public static final String ER_BAD_XSLSORT_USE = "ER_BAD_XSLSORT_USE";
public static final String ER_MISPLACED_XSLWHEN = "ER_MISPLACED_XSLWHEN";
public static final String ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE =
"ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE";
public static final String ER_MISPLACED_XSLOTHERWISE =
"ER_MISPLACED_XSLOTHERWISE";
public static final String ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE =
"ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE";
public static final String ER_NOT_ALLOWED_INSIDE_TEMPLATE =
"ER_NOT_ALLOWED_INSIDE_TEMPLATE";
public static final String ER_UNKNOWN_EXT_NS_PREFIX =
"ER_UNKNOWN_EXT_NS_PREFIX";
public static final String ER_IMPORTS_AS_FIRST_ELEM =
"ER_IMPORTS_AS_FIRST_ELEM";
public static final String ER_IMPORTING_ITSELF = "ER_IMPORTING_ITSELF";
public static final String ER_XMLSPACE_ILLEGAL_VAL ="ER_XMLSPACE_ILLEGAL_VAL";
public static final String ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL =
"ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL";
public static final String ER_SAX_EXCEPTION = "ER_SAX_EXCEPTION";
public static final String ER_XSLT_ERROR = "ER_XSLT_ERROR";
public static final String ER_CURRENCY_SIGN_ILLEGAL=
"ER_CURRENCY_SIGN_ILLEGAL";
public static final String ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM =
"ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM";
public static final String ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER =
"ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER";
public static final String ER_REDIRECT_COULDNT_GET_FILENAME =
"ER_REDIRECT_COULDNT_GET_FILENAME";
public static final String ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT =
"ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT";
public static final String ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX =
"ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX";
public static final String ER_MISSING_NS_URI = "ER_MISSING_NS_URI";
public static final String ER_MISSING_ARG_FOR_OPTION =
"ER_MISSING_ARG_FOR_OPTION";
public static final String ER_INVALID_OPTION = "ER_INVALID_OPTION";
public static final String ER_MALFORMED_FORMAT_STRING =
"ER_MALFORMED_FORMAT_STRING";
public static final String ER_STYLESHEET_REQUIRES_VERSION_ATTRIB =
"ER_STYLESHEET_REQUIRES_VERSION_ATTRIB";
public static final String ER_ILLEGAL_ATTRIBUTE_VALUE =
"ER_ILLEGAL_ATTRIBUTE_VALUE";
public static final String ER_CHOOSE_REQUIRES_WHEN ="ER_CHOOSE_REQUIRES_WHEN";
public static final String ER_NO_APPLY_IMPORT_IN_FOR_EACH =
"ER_NO_APPLY_IMPORT_IN_FOR_EACH";
public static final String ER_CANT_USE_DTM_FOR_OUTPUT =
"ER_CANT_USE_DTM_FOR_OUTPUT";
public static final String ER_CANT_USE_DTM_FOR_INPUT =
"ER_CANT_USE_DTM_FOR_INPUT";
public static final String ER_CALL_TO_EXT_FAILED = "ER_CALL_TO_EXT_FAILED";
public static final String ER_PREFIX_MUST_RESOLVE = "ER_PREFIX_MUST_RESOLVE";
public static final String ER_INVALID_UTF16_SURROGATE =
"ER_INVALID_UTF16_SURROGATE";
public static final String ER_XSLATTRSET_USED_ITSELF =
"ER_XSLATTRSET_USED_ITSELF";
public static final String ER_CANNOT_MIX_XERCESDOM ="ER_CANNOT_MIX_XERCESDOM";
public static final String ER_TOO_MANY_LISTENERS = "ER_TOO_MANY_LISTENERS";
public static final String ER_IN_ELEMTEMPLATEELEM_READOBJECT =
"ER_IN_ELEMTEMPLATEELEM_READOBJECT";
public static final String ER_DUPLICATE_NAMED_TEMPLATE =
"ER_DUPLICATE_NAMED_TEMPLATE";
public static final String ER_INVALID_KEY_CALL = "ER_INVALID_KEY_CALL";
public static final String ER_REFERENCING_ITSELF = "ER_REFERENCING_ITSELF";
public static final String ER_ILLEGAL_DOMSOURCE_INPUT =
"ER_ILLEGAL_DOMSOURCE_INPUT";
public static final String ER_CLASS_NOT_FOUND_FOR_OPTION =
"ER_CLASS_NOT_FOUND_FOR_OPTION";
public static final String ER_REQUIRED_ELEM_NOT_FOUND =
"ER_REQUIRED_ELEM_NOT_FOUND";
public static final String ER_INPUT_CANNOT_BE_NULL ="ER_INPUT_CANNOT_BE_NULL";
public static final String ER_URI_CANNOT_BE_NULL = "ER_URI_CANNOT_BE_NULL";
public static final String ER_FILE_CANNOT_BE_NULL = "ER_FILE_CANNOT_BE_NULL";
public static final String ER_SOURCE_CANNOT_BE_NULL =
"ER_SOURCE_CANNOT_BE_NULL";
public static final String ER_CANNOT_INIT_BSFMGR = "ER_CANNOT_INIT_BSFMGR";
public static final String ER_CANNOT_CMPL_EXTENSN = "ER_CANNOT_CMPL_EXTENSN";
public static final String ER_CANNOT_CREATE_EXTENSN =
"ER_CANNOT_CREATE_EXTENSN";
public static final String ER_INSTANCE_MTHD_CALL_REQUIRES =
"ER_INSTANCE_MTHD_CALL_REQUIRES";
public static final String ER_INVALID_ELEMENT_NAME ="ER_INVALID_ELEMENT_NAME";
public static final String ER_ELEMENT_NAME_METHOD_STATIC =
"ER_ELEMENT_NAME_METHOD_STATIC";
public static final String ER_EXTENSION_FUNC_UNKNOWN =
"ER_EXTENSION_FUNC_UNKNOWN";
public static final String ER_MORE_MATCH_CONSTRUCTOR =
"ER_MORE_MATCH_CONSTRUCTOR";
public static final String ER_MORE_MATCH_METHOD = "ER_MORE_MATCH_METHOD";
public static final String ER_MORE_MATCH_ELEMENT = "ER_MORE_MATCH_ELEMENT";
public static final String ER_INVALID_CONTEXT_PASSED =
"ER_INVALID_CONTEXT_PASSED";
public static final String ER_POOL_EXISTS = "ER_POOL_EXISTS";
public static final String ER_NO_DRIVER_NAME = "ER_NO_DRIVER_NAME";
public static final String ER_NO_URL = "ER_NO_URL";
public static final String ER_POOL_SIZE_LESSTHAN_ONE =
"ER_POOL_SIZE_LESSTHAN_ONE";
public static final String ER_INVALID_DRIVER = "ER_INVALID_DRIVER";
public static final String ER_NO_STYLESHEETROOT = "ER_NO_STYLESHEETROOT";
public static final String ER_ILLEGAL_XMLSPACE_VALUE =
"ER_ILLEGAL_XMLSPACE_VALUE";
public static final String ER_PROCESSFROMNODE_FAILED =
"ER_PROCESSFROMNODE_FAILED";
public static final String ER_RESOURCE_COULD_NOT_LOAD =
"ER_RESOURCE_COULD_NOT_LOAD";
public static final String ER_BUFFER_SIZE_LESSTHAN_ZERO =
"ER_BUFFER_SIZE_LESSTHAN_ZERO";
public static final String ER_UNKNOWN_ERROR_CALLING_EXTENSION =
"ER_UNKNOWN_ERROR_CALLING_EXTENSION";
public static final String ER_NO_NAMESPACE_DECL = "ER_NO_NAMESPACE_DECL";
public static final String ER_ELEM_CONTENT_NOT_ALLOWED =
"ER_ELEM_CONTENT_NOT_ALLOWED";
public static final String ER_STYLESHEET_DIRECTED_TERMINATION =
"ER_STYLESHEET_DIRECTED_TERMINATION";
public static final String ER_ONE_OR_TWO = "ER_ONE_OR_TWO";
public static final String ER_TWO_OR_THREE = "ER_TWO_OR_THREE";
public static final String ER_COULD_NOT_LOAD_RESOURCE =
"ER_COULD_NOT_LOAD_RESOURCE";
public static final String ER_CANNOT_INIT_DEFAULT_TEMPLATES =
"ER_CANNOT_INIT_DEFAULT_TEMPLATES";
public static final String ER_RESULT_NULL = "ER_RESULT_NULL";
public static final String ER_RESULT_COULD_NOT_BE_SET =
"ER_RESULT_COULD_NOT_BE_SET";
public static final String ER_NO_OUTPUT_SPECIFIED = "ER_NO_OUTPUT_SPECIFIED";
public static final String ER_CANNOT_TRANSFORM_TO_RESULT_TYPE =
"ER_CANNOT_TRANSFORM_TO_RESULT_TYPE";
public static final String ER_CANNOT_TRANSFORM_SOURCE_TYPE =
"ER_CANNOT_TRANSFORM_SOURCE_TYPE";
public static final String ER_NULL_CONTENT_HANDLER ="ER_NULL_CONTENT_HANDLER";
public static final String ER_NULL_ERROR_HANDLER = "ER_NULL_ERROR_HANDLER";
public static final String ER_CANNOT_CALL_PARSE = "ER_CANNOT_CALL_PARSE";
public static final String ER_NO_PARENT_FOR_FILTER ="ER_NO_PARENT_FOR_FILTER";
public static final String ER_NO_STYLESHEET_IN_MEDIA =
"ER_NO_STYLESHEET_IN_MEDIA";
public static final String ER_NO_STYLESHEET_PI = "ER_NO_STYLESHEET_PI";
public static final String ER_NOT_SUPPORTED = "ER_NOT_SUPPORTED";
public static final String ER_PROPERTY_VALUE_BOOLEAN =
"ER_PROPERTY_VALUE_BOOLEAN";
public static final String ER_COULD_NOT_FIND_EXTERN_SCRIPT =
"ER_COULD_NOT_FIND_EXTERN_SCRIPT";
public static final String ER_RESOURCE_COULD_NOT_FIND =
"ER_RESOURCE_COULD_NOT_FIND";
public static final String ER_OUTPUT_PROPERTY_NOT_RECOGNIZED =
"ER_OUTPUT_PROPERTY_NOT_RECOGNIZED";
public static final String ER_FAILED_CREATING_ELEMLITRSLT =
"ER_FAILED_CREATING_ELEMLITRSLT";
public static final String ER_VALUE_SHOULD_BE_NUMBER =
"ER_VALUE_SHOULD_BE_NUMBER";
public static final String ER_VALUE_SHOULD_EQUAL = "ER_VALUE_SHOULD_EQUAL";
public static final String ER_FAILED_CALLING_METHOD =
"ER_FAILED_CALLING_METHOD";
public static final String ER_FAILED_CREATING_ELEMTMPL =
"ER_FAILED_CREATING_ELEMTMPL";
public static final String ER_CHARS_NOT_ALLOWED = "ER_CHARS_NOT_ALLOWED";
public static final String ER_ATTR_NOT_ALLOWED = "ER_ATTR_NOT_ALLOWED";
public static final String ER_BAD_VALUE = "ER_BAD_VALUE";
public static final String ER_ATTRIB_VALUE_NOT_FOUND =
"ER_ATTRIB_VALUE_NOT_FOUND";
public static final String ER_ATTRIB_VALUE_NOT_RECOGNIZED =
"ER_ATTRIB_VALUE_NOT_RECOGNIZED";
public static final String ER_NULL_URI_NAMESPACE = "ER_NULL_URI_NAMESPACE";
public static final String ER_NUMBER_TOO_BIG = "ER_NUMBER_TOO_BIG";
public static final String ER_CANNOT_FIND_SAX1_DRIVER =
"ER_CANNOT_FIND_SAX1_DRIVER";
public static final String ER_SAX1_DRIVER_NOT_LOADED =
"ER_SAX1_DRIVER_NOT_LOADED";
public static final String ER_SAX1_DRIVER_NOT_INSTANTIATED =
"ER_SAX1_DRIVER_NOT_INSTANTIATED" ;
public static final String ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER =
"ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER";
public static final String ER_PARSER_PROPERTY_NOT_SPECIFIED =
"ER_PARSER_PROPERTY_NOT_SPECIFIED";
public static final String ER_PARSER_ARG_CANNOT_BE_NULL =
"ER_PARSER_ARG_CANNOT_BE_NULL" ;
public static final String ER_FEATURE = "ER_FEATURE";
public static final String ER_PROPERTY = "ER_PROPERTY" ;
public static final String ER_NULL_ENTITY_RESOLVER ="ER_NULL_ENTITY_RESOLVER";
public static final String ER_NULL_DTD_HANDLER = "ER_NULL_DTD_HANDLER" ;
public static final String ER_NO_DRIVER_NAME_SPECIFIED =
"ER_NO_DRIVER_NAME_SPECIFIED";
public static final String ER_NO_URL_SPECIFIED = "ER_NO_URL_SPECIFIED";
public static final String ER_POOLSIZE_LESS_THAN_ONE =
"ER_POOLSIZE_LESS_THAN_ONE";
public static final String ER_INVALID_DRIVER_NAME = "ER_INVALID_DRIVER_NAME";
public static final String ER_ERRORLISTENER = "ER_ERRORLISTENER";
public static final String ER_ASSERT_NO_TEMPLATE_PARENT =
"ER_ASSERT_NO_TEMPLATE_PARENT";
public static final String ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR =
"ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR";
public static final String ER_NOT_ALLOWED_IN_POSITION =
"ER_NOT_ALLOWED_IN_POSITION";
public static final String ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION =
"ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION";
public static final String ER_NAMESPACE_CONTEXT_NULL_NAMESPACE =
"ER_NAMESPACE_CONTEXT_NULL_NAMESPACE";
public static final String ER_NAMESPACE_CONTEXT_NULL_PREFIX =
"ER_NAMESPACE_CONTEXT_NULL_PREFIX";
public static final String ER_XPATH_RESOLVER_NULL_QNAME =
"ER_XPATH_RESOLVER_NULL_QNAME";
public static final String ER_XPATH_RESOLVER_NEGATIVE_ARITY =
"ER_XPATH_RESOLVER_NEGATIVE_ARITY";
public static final String INVALID_TCHAR = "INVALID_TCHAR";
public static final String INVALID_QNAME = "INVALID_QNAME";
public static final String INVALID_ENUM = "INVALID_ENUM";
public static final String INVALID_NMTOKEN = "INVALID_NMTOKEN";
public static final String INVALID_NCNAME = "INVALID_NCNAME";
public static final String INVALID_BOOLEAN = "INVALID_BOOLEAN";
public static final String INVALID_NUMBER = "INVALID_NUMBER";
public static final String ER_ARG_LITERAL = "ER_ARG_LITERAL";
public static final String ER_DUPLICATE_GLOBAL_VAR ="ER_DUPLICATE_GLOBAL_VAR";
public static final String ER_DUPLICATE_VAR = "ER_DUPLICATE_VAR";
public static final String ER_TEMPLATE_NAME_MATCH = "ER_TEMPLATE_NAME_MATCH";
public static final String ER_INVALID_PREFIX = "ER_INVALID_PREFIX";
public static final String ER_NO_ATTRIB_SET = "ER_NO_ATTRIB_SET";
public static final String ER_FUNCTION_NOT_FOUND =
"ER_FUNCTION_NOT_FOUND";
public static final String ER_CANT_HAVE_CONTENT_AND_SELECT =
"ER_CANT_HAVE_CONTENT_AND_SELECT";
public static final String ER_INVALID_SET_PARAM_VALUE = "ER_INVALID_SET_PARAM_VALUE";
public static final String ER_SET_FEATURE_NULL_NAME =
"ER_SET_FEATURE_NULL_NAME";
public static final String ER_GET_FEATURE_NULL_NAME =
"ER_GET_FEATURE_NULL_NAME";
public static final String ER_UNSUPPORTED_FEATURE =
"ER_UNSUPPORTED_FEATURE";
public static final String ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING =
"ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING";
public static final String WG_FOUND_CURLYBRACE = "WG_FOUND_CURLYBRACE";
public static final String WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR =
"WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR";
public static final String WG_EXPR_ATTRIB_CHANGED_TO_SELECT =
"WG_EXPR_ATTRIB_CHANGED_TO_SELECT";
public static final String WG_NO_LOCALE_IN_FORMATNUMBER =
"WG_NO_LOCALE_IN_FORMATNUMBER";
public static final String WG_LOCALE_NOT_FOUND = "WG_LOCALE_NOT_FOUND";
public static final String WG_CANNOT_MAKE_URL_FROM ="WG_CANNOT_MAKE_URL_FROM";
public static final String WG_CANNOT_LOAD_REQUESTED_DOC =
"WG_CANNOT_LOAD_REQUESTED_DOC";
public static final String WG_CANNOT_FIND_COLLATOR ="WG_CANNOT_FIND_COLLATOR";
public static final String WG_FUNCTIONS_SHOULD_USE_URL =
"WG_FUNCTIONS_SHOULD_USE_URL";
public static final String WG_ENCODING_NOT_SUPPORTED_USING_UTF8 =
"WG_ENCODING_NOT_SUPPORTED_USING_UTF8";
public static final String WG_ENCODING_NOT_SUPPORTED_USING_JAVA =
"WG_ENCODING_NOT_SUPPORTED_USING_JAVA";
public static final String WG_SPECIFICITY_CONFLICTS =
"WG_SPECIFICITY_CONFLICTS";
public static final String WG_PARSING_AND_PREPARING =
"WG_PARSING_AND_PREPARING";
public static final String WG_ATTR_TEMPLATE = "WG_ATTR_TEMPLATE";
public static final String WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESPACE = "WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESP";
public static final String WG_ATTRIB_NOT_HANDLED = "WG_ATTRIB_NOT_HANDLED";
public static final String WG_NO_DECIMALFORMAT_DECLARATION =
"WG_NO_DECIMALFORMAT_DECLARATION";
public static final String WG_OLD_XSLT_NS = "WG_OLD_XSLT_NS";
public static final String WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED =
"WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED";
public static final String WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE =
"WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE";
public static final String WG_ILLEGAL_ATTRIBUTE = "WG_ILLEGAL_ATTRIBUTE";
public static final String WG_COULD_NOT_RESOLVE_PREFIX =
"WG_COULD_NOT_RESOLVE_PREFIX";
public static final String WG_STYLESHEET_REQUIRES_VERSION_ATTRIB =
"WG_STYLESHEET_REQUIRES_VERSION_ATTRIB";
public static final String WG_ILLEGAL_ATTRIBUTE_NAME =
"WG_ILLEGAL_ATTRIBUTE_NAME";
public static final String WG_ILLEGAL_ATTRIBUTE_VALUE =
"WG_ILLEGAL_ATTRIBUTE_VALUE";
public static final String WG_EMPTY_SECOND_ARG = "WG_EMPTY_SECOND_ARG";
public static final String WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML =
"WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML";
public static final String WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME =
"WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME";
public static final String WG_ILLEGAL_ATTRIBUTE_POSITION =
"WG_ILLEGAL_ATTRIBUTE_POSITION";
public static final String NO_MODIFICATION_ALLOWED_ERR =
"NO_MODIFICATION_ALLOWED_ERR";
/*
* Now fill in the message text.
* Then fill in the message text for that message code in the
* array. Use the new error code as the index into the array.
*/
// Error messages...
/** Get the lookup table for error messages.
*
* @return The message lookup table.
*/
public Object[][] getContents()
{
return new Object[][] {
/** Error message ID that has a null message, but takes in a single object. */
{"ER0000" , "{0}" },
{ ER_NO_CURLYBRACE,
"\u932f\u8aa4\uff1a\u8868\u793a\u5f0f\u5167\u4e0d\u80fd\u6709 '{'"},
{ ER_ILLEGAL_ATTRIBUTE ,
"{0} \u542b\u6709\u4e0d\u5408\u6cd5\u7684\u5c6c\u6027\uff1a{1}"},
{ER_NULL_SOURCENODE_APPLYIMPORTS ,
"\u5728 xsl:apply-imports \u4e2d\uff0csourceNode \u662f\u7a7a\u503c\uff01"},
{ER_CANNOT_ADD,
"\u4e0d\u80fd\u65b0\u589e {0} \u5230 {1}"},
{ ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES,
"\u5728 handleApplyTemplatesInstruction \u4e2d\uff0csourceNode \u662f\u7a7a\u503c\uff01"},
{ ER_NO_NAME_ATTRIB,
"{0} \u5fc5\u9808\u6709\u540d\u7a31\u5c6c\u6027\u3002"},
{ER_TEMPLATE_NOT_FOUND,
"\u627e\u4e0d\u5230\u6307\u540d\u70ba\uff1a{0} \u7684\u7bc4\u672c"},
{ER_CANT_RESOLVE_NAME_AVT,
"\u7121\u6cd5\u89e3\u6790 xsl:call-template \u4e2d\u7684\u540d\u7a31 AVT\u3002"},
{ER_REQUIRES_ATTRIB,
"{0} \u9700\u8981\u5c6c\u6027\uff1a{1}"},
{ ER_MUST_HAVE_TEST_ATTRIB,
"{0} \u5fc5\u9808\u6709 ''test'' \u5c6c\u6027\u3002"},
{ER_BAD_VAL_ON_LEVEL_ATTRIB,
"\u5c64\u6b21\u5c6c\u6027\uff1a{0} \u5305\u542b\u4e0d\u6b63\u78ba\u7684\u503c"},
{ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML,
"processing-instruction \u540d\u7a31\u4e0d\u80fd\u662f 'xml'"},
{ ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME,
"processing-instruction \u540d\u7a31\u5fc5\u9808\u662f\u6709\u6548\u7684 NCName\uff1a{0}"},
{ ER_NEED_MATCH_ATTRIB,
"{0} \u5982\u679c\u6709\u6a21\u5f0f\uff0c\u5fc5\u9808\u6709\u7b26\u5408\u5c6c\u6027\u3002"},
{ ER_NEED_NAME_OR_MATCH_ATTRIB,
"{0} \u9700\u8981\u540d\u7a31\u6216\u7b26\u5408\u5c6c\u6027\u3002"},
{ER_CANT_RESOLVE_NSPREFIX,
"\u7121\u6cd5\u89e3\u6790\u540d\u7a31\u7a7a\u9593\u5b57\u9996\uff1a{0}"},
{ ER_ILLEGAL_VALUE,
"xml:space \u542b\u6709\u4e0d\u5408\u6cd5\u7684\u503c\uff1a{0}"},
{ ER_NO_OWNERDOC,
"\u5b50\u7bc0\u9ede\u6c92\u6709\u64c1\u6709\u8005\u6587\u4ef6\uff01"},
{ ER_ELEMTEMPLATEELEM_ERR,
"ElemTemplateElement \u932f\u8aa4\uff1a{0}"},
{ ER_NULL_CHILD,
"\u5617\u8a66\u65b0\u589e\u7a7a\u503c\u5b50\u9805\u5143\u4ef6\uff01"},
{ ER_NEED_SELECT_ATTRIB,
"{0} \u9700\u8981\u9078\u53d6\u5c6c\u6027\u3002"},
{ ER_NEED_TEST_ATTRIB ,
"xsl:when \u5fc5\u9808\u6709 'test' \u5c6c\u6027\u3002"},
{ ER_NEED_NAME_ATTRIB,
"xsl:with-param \u5fc5\u9808\u6709 'name' \u5c6c\u6027\u3002"},
{ ER_NO_CONTEXT_OWNERDOC,
"\u74b0\u5883\u5b9a\u7fa9\u6c92\u6709\u64c1\u6709\u8005\u6587\u4ef6\uff01"},
{ER_COULD_NOT_CREATE_XML_PROC_LIAISON,
"\u7121\u6cd5\u5efa\u7acb XML TransformerFactory Liaison\uff1a{0}"},
{ER_PROCESS_NOT_SUCCESSFUL,
"Xalan: \u7a0b\u5e8f\u6c92\u6709\u9806\u5229\u5b8c\u6210\u3002"},
{ ER_NOT_SUCCESSFUL,
"Xalan: \u4e0d\u6210\u529f\u3002"},
{ ER_ENCODING_NOT_SUPPORTED,
"\u4e0d\u652f\u63f4\u7de8\u78bc\uff1a{0}"},
{ER_COULD_NOT_CREATE_TRACELISTENER,
"\u7121\u6cd5\u5efa\u7acb TraceListener\uff1a{0}"},
{ER_KEY_REQUIRES_NAME_ATTRIB,
"xsl:key \u9700\u8981 'name' \u5c6c\u6027\uff01"},
{ ER_KEY_REQUIRES_MATCH_ATTRIB,
"xsl:key \u9700\u8981 'match' \u5c6c\u6027\uff01"},
{ ER_KEY_REQUIRES_USE_ATTRIB,
"xsl:key \u9700\u8981 'use' \u5c6c\u6027\uff01"},
{ ER_REQUIRES_ELEMENTS_ATTRIB,
"(StylesheetHandler) {0} \u9700\u8981 ''elements'' \u5c6c\u6027\uff01"},
{ ER_MISSING_PREFIX_ATTRIB,
"(StylesheetHandler) {0} \u5c6c\u6027 ''prefix'' \u907a\u6f0f"},
{ ER_BAD_STYLESHEET_URL,
"\u6a23\u5f0f\u8868 URL \u4e0d\u6b63\u78ba\uff1a{0}"},
{ ER_FILE_NOT_FOUND,
"\u627e\u4e0d\u5230\u6a23\u5f0f\u8868\u6a94\u6848\uff1a{0}"},
{ ER_IOEXCEPTION,
"\u6a23\u5f0f\u8868\u6a94\u6848\uff1a{0} \u767c\u751f IO \u7570\u5e38"},
{ ER_NO_HREF_ATTRIB,
"(StylesheetHandler) \u627e\u4e0d\u5230 {0} \u7684 href \u5c6c\u6027"},
{ ER_STYLESHEET_INCLUDES_ITSELF,
"(StylesheetHandler) {0} \u76f4\u63a5\u6216\u9593\u63a5\u5305\u542b\u81ea\u5df1\uff01"},
{ ER_PROCESSINCLUDE_ERROR,
"StylesheetHandler.processInclude \u932f\u8aa4\uff0c{0}"},
{ ER_MISSING_LANG_ATTRIB,
"(StylesheetHandler) {0} \u5c6c\u6027 ''lang'' \u907a\u6f0f"},
{ ER_MISSING_CONTAINER_ELEMENT_COMPONENT,
"(StylesheetHandler) \u653e\u7f6e\u932f\u8aa4\u7684 {0} \u5143\u7d20\uff1f\uff1f\u907a\u6f0f\u5132\u5b58\u5668\u5143\u7d20 ''component''"},
{ ER_CAN_ONLY_OUTPUT_TO_ELEMENT,
"\u53ea\u80fd\u8f38\u51fa\u81f3 Element\u3001DocumentFragment\u3001Document \u6216 PrintWriter\u3002"},
{ ER_PROCESS_ERROR,
"StylesheetRoot.process \u932f\u8aa4"},
{ ER_UNIMPLNODE_ERROR,
"UnImplNode \u932f\u8aa4\uff1a{0}"},
{ ER_NO_SELECT_EXPRESSION,
"\u932f\u8aa4\uff01\u6c92\u6709\u627e\u5230 xpath select \u8868\u793a\u5f0f (-select)\u3002"},
{ ER_CANNOT_SERIALIZE_XSLPROCESSOR,
"\u7121\u6cd5\u5e8f\u5217\u5316 XSLProcessor\uff01"},
{ ER_NO_INPUT_STYLESHEET,
"\u6c92\u6709\u6307\u5b9a\u6a23\u5f0f\u8868\u8f38\u5165\uff01"},
{ ER_FAILED_PROCESS_STYLESHEET,
"\u7121\u6cd5\u8655\u7406\u6a23\u5f0f\u8868\uff01"},
{ ER_COULDNT_PARSE_DOC,
"\u7121\u6cd5\u5256\u6790 {0} \u6587\u4ef6\uff01"},
{ ER_COULDNT_FIND_FRAGMENT,
"\u627e\u4e0d\u5230\u7247\u6bb5\uff1a{0}"},
{ ER_NODE_NOT_ELEMENT,
"\u7247\u6bb5 ID \u6240\u6307\u5411\u7684\u7bc0\u9ede\u4e0d\u662f\u5143\u7d20\uff1a{0}"},
{ ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB,
"for-each \u5fc5\u9808\u6709 match \u6216 name \u5c6c\u6027"},
{ ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB,
"templates \u5fc5\u9808\u6709 match \u6216 name \u5c6c\u6027"},
{ ER_NO_CLONE_OF_DOCUMENT_FRAG,
"\u6587\u4ef6\u7247\u6bb5\u6c92\u6709\u8907\u88fd\uff01"},
{ ER_CANT_CREATE_ITEM,
"\u7121\u6cd5\u5728\u7d50\u679c\u6a39\uff1a{0} \u4e2d\u5efa\u7acb\u9805\u76ee"},
{ ER_XMLSPACE_ILLEGAL_VALUE,
"\u539f\u59cb\u6a94 XML \u4e2d\u7684 xml:space \u542b\u6709\u4e0d\u5408\u6cd5\u7684\u503c\uff1a{0}"},
{ ER_NO_XSLKEY_DECLARATION,
"{0} \u6c92\u6709 xsl:key \u5ba3\u544a\uff01"},
{ ER_CANT_CREATE_URL,
"\u932f\u8aa4\uff01\u7121\u6cd5\u91dd\u5c0d\uff1a{0} \u5efa\u7acb URL"},
{ ER_XSLFUNCTIONS_UNSUPPORTED,
"xsl:functions \u4e0d\u53d7\u652f\u63f4"},
{ ER_PROCESSOR_ERROR,
"XSLT TransformerFactory \u932f\u8aa4"},
{ ER_NOT_ALLOWED_INSIDE_STYLESHEET,
"(StylesheetHandler) {0} \u4e0d\u5141\u8a31\u5728\u6a23\u5f0f\u8868\u5167\uff01"},
{ ER_RESULTNS_NOT_SUPPORTED,
"result-ns \u4e0d\u518d\u53d7\u652f\u63f4\uff01\u8acb\u6539\u7528 xsl:output\u3002"},
{ ER_DEFAULTSPACE_NOT_SUPPORTED,
"default-space \u4e0d\u518d\u53d7\u652f\u63f4\uff01\u8acb\u6539\u7528 xsl:strip-space \u6216 xsl:preserve-space\u3002"},
{ ER_INDENTRESULT_NOT_SUPPORTED,
"indent-result \u4e0d\u518d\u53d7\u652f\u63f4\uff01\u8acb\u6539\u7528 xsl:output\u3002"},
{ ER_ILLEGAL_ATTRIB,
"(StylesheetHandler) {0} \u542b\u6709\u4e0d\u5408\u6cd5\u7684\u5c6c\u6027\uff1a{1}"},
{ ER_UNKNOWN_XSL_ELEM,
"\u4e0d\u660e XSL \u5143\u7d20\uff1a{0}"},
{ ER_BAD_XSLSORT_USE,
"(StylesheetHandler) xsl:sort \u53ea\u80fd\u548c xsl:apply-templates \u6216 xsl:for-each \u4e00\u8d77\u4f7f\u7528\u3002"},
{ ER_MISPLACED_XSLWHEN,
"(StylesheetHandler) \u653e\u7f6e\u932f\u8aa4\u7684 xsl:when\uff01"},
{ ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE,
"(StylesheetHandler) xsl:when \u7684\u6bcd\u9805\u4e0d\u662f xsl:choose\uff01"},
{ ER_MISPLACED_XSLOTHERWISE,
"(StylesheetHandler) \u653e\u7f6e\u932f\u8aa4\u7684 xsl:otherwise\uff01"},
{ ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE,
"(StylesheetHandler) xsl:otherwise \u7684\u6bcd\u9805\u4e0d\u662f xsl:choose\uff01"},
{ ER_NOT_ALLOWED_INSIDE_TEMPLATE,
"\u5728\u7bc4\u672c\u5167\u4e0d\u5141\u8a31 (StylesheetHandler) {0}\uff01"},
{ ER_UNKNOWN_EXT_NS_PREFIX,
"(StylesheetHandler) {0} \u5ef6\u4f38\u9805\u76ee\u540d\u7a31\u7a7a\u9593\u5b57\u9996 {1} \u4e0d\u660e"},
{ ER_IMPORTS_AS_FIRST_ELEM,
"(StylesheetHandler) Imports \u53ea\u80fd\u51fa\u73fe\u5728\u6a23\u5f0f\u8868\u4e2d\u4f5c\u70ba\u7b2c\u4e00\u500b\u5143\u7d20\uff01"},
{ ER_IMPORTING_ITSELF,
"(StylesheetHandler) {0} \u6b63\u5728\u76f4\u63a5\u6216\u9593\u63a5\u532f\u5165\u81ea\u5df1\uff01"},
{ ER_XMLSPACE_ILLEGAL_VAL,
"(StylesheetHandler) xml:space \u6709\u4e0d\u5408\u6cd5\u7684\u503c\uff1a{0}"},
{ ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL,
"processStylesheet \u4e0d\u6210\u529f\uff01"},
{ ER_SAX_EXCEPTION,
"SAX \u7570\u5e38"},
// add this message to fix bug 21478
{ ER_FUNCTION_NOT_SUPPORTED,
"\u51fd\u6578\u4e0d\u53d7\u652f\u63f4\uff01"},
{ ER_XSLT_ERROR,
"XSLT \u932f\u8aa4"},
{ ER_CURRENCY_SIGN_ILLEGAL,
"\u5728\u683c\u5f0f\u578b\u6a23\u5b57\u4e32\u4e2d\u4e0d\u5141\u8a31\u8ca8\u5e63\u7b26\u865f"},
{ ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM,
"\u5728\u6a23\u5f0f\u8868 DOM \u4e2d\u4e0d\u652f\u63f4\u6587\u4ef6\u51fd\u6578\uff01"},
{ ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER,
"\u7121\u6cd5\u89e3\u6790\u975e\u5b57\u9996\u89e3\u6790\u5668\u7684\u5b57\u9996\uff01"},
{ ER_REDIRECT_COULDNT_GET_FILENAME,
"\u91cd\u65b0\u5c0e\u5411\u5ef6\u4f38\u9805\u76ee\uff1a\u7121\u6cd5\u53d6\u5f97\u6a94\u6848\u540d\u7a31 - file \u6216 select \u5c6c\u6027\u5fc5\u9808\u50b3\u56de\u6709\u6548\u5b57\u4e32\u3002"},
{ ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT,
"\u7121\u6cd5\u5728\u91cd\u65b0\u5c0e\u5411\u5ef6\u4f38\u9805\u76ee\u4e2d\u5efa\u7acb FormatterListener\uff01"},
{ ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX,
"exclude-result-prefixes \u4e2d\u7684\u5b57\u9996\u7121\u6548\uff1a{0}"},
{ ER_MISSING_NS_URI,
"\u907a\u6f0f\u6307\u5b9a\u7684\u5b57\u9996\u7684\u540d\u7a31\u7a7a\u9593 URI"},
{ ER_MISSING_ARG_FOR_OPTION,
"\u907a\u6f0f\u9078\u9805\uff1a{0} \u7684\u5f15\u6578"},
{ ER_INVALID_OPTION,
"\u9078\u9805\uff1a{0} \u7121\u6548"},
{ ER_MALFORMED_FORMAT_STRING,
"\u4e0d\u6b63\u78ba\u7684\u683c\u5f0f\u5b57\u4e32\uff1a{0}"},
{ ER_STYLESHEET_REQUIRES_VERSION_ATTRIB,
"xsl:stylesheet \u9700\u8981 'version' \u5c6c\u6027\uff01"},
{ ER_ILLEGAL_ATTRIBUTE_VALUE,
"\u5c6c\u6027\uff1a{0} \u542b\u6709\u4e0d\u5408\u6cd5\u7684\u503c\uff1a{1}"},
{ ER_CHOOSE_REQUIRES_WHEN,
"xsl:choose \u9700\u8981\u6709 xsl:when"},
{ ER_NO_APPLY_IMPORT_IN_FOR_EACH,
"xsl:apply-imports \u4e0d\u5bb9\u8a31\u51fa\u73fe\u5728 xsl:for-each \u4e2d"},
{ ER_CANT_USE_DTM_FOR_OUTPUT,
"\u7121\u6cd5\u4f7f\u7528\u8f38\u51fa DOM \u7bc0\u9ede\u7684 DTMLiaison ... \u6539\u50b3\u905e org.apache.xpath.DOM2Helper\uff01"},
{ ER_CANT_USE_DTM_FOR_INPUT,
"\u7121\u6cd5\u4f7f\u7528\u8f38\u5165 DOM \u7bc0\u9ede\u7684 DTMLiaison ... \u6539\u50b3\u905e org.apache.xpath.DOM2Helper\uff01"},
{ ER_CALL_TO_EXT_FAILED,
"\u547c\u53eb\u5ef6\u4f38\u9805\u76ee\u5143\u7d20\u5931\u6557\uff1a{0}"},
{ ER_PREFIX_MUST_RESOLVE,
"\u5b57\u9996\u5fc5\u9808\u89e3\u6790\u70ba\u540d\u7a31\u7a7a\u9593\uff1a{0}"},
{ ER_INVALID_UTF16_SURROGATE,
"\u5075\u6e2c\u5230\u7121\u6548\u7684 UTF-16 \u4ee3\u7406\uff1a{0}?"},
{ ER_XSLATTRSET_USED_ITSELF,
"xsl:attribute-set {0} \u81ea\u6211\u4f7f\u7528\uff0c\u5c07\u9020\u6210\u7121\u9650\u8ff4\u5708\u3002"},
{ ER_CANNOT_MIX_XERCESDOM,
"\u7121\u6cd5\u6df7\u5408\u975e Xerces-DOM \u8f38\u5165\u8207 Xerces-DOM \u8f38\u51fa\uff01"},
{ ER_TOO_MANY_LISTENERS,
"addTraceListenersToStylesheet - TooManyListenersException"},
{ ER_IN_ELEMTEMPLATEELEM_READOBJECT,
"\u4f4d\u65bc ElemTemplateElement.readObject\uff1a{0}"},
{ ER_DUPLICATE_NAMED_TEMPLATE,
"\u627e\u5230\u4e0d\u6b62\u4e00\u500b\u540d\u7a31\u70ba\uff1a{0} \u7684\u7bc4\u672c"},
{ ER_INVALID_KEY_CALL,
"\u7121\u6548\u7684\u51fd\u6578\u547c\u53eb\uff1a\u4e0d\u5141\u8a31 recursive key() \u547c\u53eb"},
{ ER_REFERENCING_ITSELF,
"\u8b8a\u6578 {0} \u76f4\u63a5\u6216\u9593\u63a5\u53c3\u7167\u81ea\u5df1\uff01"},
{ ER_ILLEGAL_DOMSOURCE_INPUT,
"\u5c0d newTemplates \u7684 DOMSource \u800c\u8a00\uff0c\u8f38\u5165\u7bc0\u9ede\u4e0d\u53ef\u70ba\u7a7a\u503c\uff01"},
{ ER_CLASS_NOT_FOUND_FOR_OPTION,
"\u627e\u4e0d\u5230\u9078\u9805 {0} \u7684\u985e\u5225\u6a94\u6848"},
{ ER_REQUIRED_ELEM_NOT_FOUND,
"\u627e\u4e0d\u5230\u5fc5\u8981\u7684\u5143\u7d20\uff1a{0}"},
{ ER_INPUT_CANNOT_BE_NULL,
"InputStream \u4e0d\u53ef\u70ba\u7a7a\u503c"},
{ ER_URI_CANNOT_BE_NULL,
"URI \u4e0d\u53ef\u70ba\u7a7a\u503c"},
{ ER_FILE_CANNOT_BE_NULL,
"\u6a94\u6848\u4e0d\u53ef\u70ba\u7a7a\u503c"},
{ ER_SOURCE_CANNOT_BE_NULL,
"InputSource \u4e0d\u53ef\u70ba\u7a7a\u503c"},
{ ER_CANNOT_INIT_BSFMGR,
"\u7121\u6cd5\u8d77\u59cb\u8a2d\u5b9a BSF \u7ba1\u7406\u7a0b\u5f0f"},
{ ER_CANNOT_CMPL_EXTENSN,
"\u7121\u6cd5\u7de8\u8b6f\u5ef6\u4f38\u9805\u76ee"},
{ ER_CANNOT_CREATE_EXTENSN,
"\u7121\u6cd5\u5efa\u7acb\u5ef6\u4f38\u9805\u76ee\uff1a{0} \u56e0\u70ba\uff1a{1}"},
{ ER_INSTANCE_MTHD_CALL_REQUIRES,
"\u547c\u53eb\u65b9\u6cd5 {0} \u7684\u5be6\u4f8b\u65b9\u6cd5\u9700\u8981\u7269\u4ef6\u5be6\u4f8b\u4f5c\u70ba\u7b2c\u4e00\u500b\u5f15\u6578"},
{ ER_INVALID_ELEMENT_NAME,
"\u6307\u5b9a\u7121\u6548\u7684\u5143\u7d20\u540d\u7a31 {0}"},
{ ER_ELEMENT_NAME_METHOD_STATIC,
"\u5143\u7d20\u540d\u7a31\u65b9\u6cd5\u5fc5\u9808\u662f\u975c\u614b {0}"},
{ ER_EXTENSION_FUNC_UNKNOWN,
"\u5ef6\u4f38\u9805\u76ee\u51fd\u6578 {0} \uff1a {1} \u4e0d\u660e"},
{ ER_MORE_MATCH_CONSTRUCTOR,
"{0} \u7684\u6700\u7b26\u5408\u5efa\u69cb\u5143\u4e0d\u6b62\u4e00\u500b"},
{ ER_MORE_MATCH_METHOD,
"\u65b9\u6cd5 {0} \u7684\u6700\u7b26\u5408\u5efa\u69cb\u5143\u4e0d\u6b62\u4e00\u500b"},
{ ER_MORE_MATCH_ELEMENT,
"\u5143\u7d20\u65b9\u6cd5 {0} \u7684\u6700\u7b26\u5408\u5efa\u69cb\u5143\u4e0d\u6b62\u4e00\u500b"},
{ ER_INVALID_CONTEXT_PASSED,
"\u50b3\u905e\u5230\u8a55\u4f30 {0} \u7684\u74b0\u5883\u5b9a\u7fa9\u7121\u6548"},
{ ER_POOL_EXISTS,
"\u5132\u5b58\u6c60\u5df2\u5b58\u5728"},
{ ER_NO_DRIVER_NAME,
"\u672a\u6307\u5b9a\u9a45\u52d5\u7a0b\u5f0f\u540d\u7a31"},
{ ER_NO_URL,
"\u672a\u6307\u5b9a URL"},
{ ER_POOL_SIZE_LESSTHAN_ONE,
"\u5132\u5b58\u6c60\u5927\u5c0f\u5c0f\u65bc 1\uff01"},
{ ER_INVALID_DRIVER,
"\u6307\u5b9a\u7684\u9a45\u52d5\u7a0b\u5f0f\u540d\u7a31\u7121\u6548\uff01"},
{ ER_NO_STYLESHEETROOT,
"\u627e\u4e0d\u5230\u6a23\u5f0f\u8868\u6839\u76ee\u9304\uff01"},
{ ER_ILLEGAL_XMLSPACE_VALUE,
"xml:space \u7684\u503c\u4e0d\u5408\u6cd5"},
{ ER_PROCESSFROMNODE_FAILED,
"processFromNode \u5931\u6557"},
{ ER_RESOURCE_COULD_NOT_LOAD,
"\u7121\u6cd5\u8f09\u5165\u8cc7\u6e90 [ {0} ]\uff1a{1} \n {2} \t {3}"},
{ ER_BUFFER_SIZE_LESSTHAN_ZERO,
"\u7de9\u885d\u5340\u5927\u5c0f <=0"},
{ ER_UNKNOWN_ERROR_CALLING_EXTENSION,
"\u547c\u53eb\u5ef6\u4f38\u9805\u76ee\u6642\u767c\u751f\u4e0d\u660e\u932f\u8aa4"},
{ ER_NO_NAMESPACE_DECL,
"\u5b57\u9996 {0} \u6c92\u6709\u5c0d\u61c9\u7684\u540d\u7a31\u7a7a\u9593\u5ba3\u544a"},
{ ER_ELEM_CONTENT_NOT_ALLOWED,
"lang=javaclass {0} \u4e0d\u5141\u8a31\u5143\u7d20\u5167\u5bb9"},
{ ER_STYLESHEET_DIRECTED_TERMINATION,
"\u6a23\u5f0f\u8868\u5c0e\u5411\u7d42\u6b62"},
{ ER_ONE_OR_TWO,
"1 \u6216 2"},
{ ER_TWO_OR_THREE,
"2 \u6216 3"},
{ ER_COULD_NOT_LOAD_RESOURCE,
"\u7121\u6cd5\u8f09\u5165 {0}\uff08\u6aa2\u67e5 CLASSPATH\uff09\uff0c\u73fe\u5728\u53ea\u4f7f\u7528\u9810\u8a2d\u503c"},
{ ER_CANNOT_INIT_DEFAULT_TEMPLATES,
"\u7121\u6cd5\u8d77\u59cb\u8a2d\u5b9a\u9810\u8a2d\u7bc4\u672c"},
{ ER_RESULT_NULL,
"\u7d50\u679c\u4e0d\u61c9\u70ba\u7a7a\u503c"},
{ ER_RESULT_COULD_NOT_BE_SET,
"\u7121\u6cd5\u8a2d\u5b9a\u7d50\u679c"},
{ ER_NO_OUTPUT_SPECIFIED,
"\u6c92\u6709\u6307\u5b9a\u8f38\u51fa"},
{ ER_CANNOT_TRANSFORM_TO_RESULT_TYPE,
"\u7121\u6cd5\u8f49\u63db\u6210\u985e\u578b {0} \u7684\u7d50\u679c"},
{ ER_CANNOT_TRANSFORM_SOURCE_TYPE,
"\u7121\u6cd5\u8f49\u63db\u985e\u578b {0} \u7684\u539f\u59cb\u6a94"},
{ ER_NULL_CONTENT_HANDLER,
"\u7a7a\u503c\u5167\u5bb9\u8655\u7406\u7a0b\u5f0f"},
{ ER_NULL_ERROR_HANDLER,
"\u7a7a\u503c\u932f\u8aa4\u8655\u7406\u7a0b\u5f0f"},
{ ER_CANNOT_CALL_PARSE,
"\u5982\u679c\u672a\u8a2d\u5b9a ContentHandler \u5247\u7121\u6cd5\u547c\u53eb parse"},
{ ER_NO_PARENT_FOR_FILTER,
"\u904e\u6ffe\u5668\u6c92\u6709\u6bcd\u9805"},
{ ER_NO_STYLESHEET_IN_MEDIA,
"\u5728\uff1a{0}\uff0cmedia= {1} \u4e2d\u6c92\u6709\u6a23\u5f0f\u8868"},
{ ER_NO_STYLESHEET_PI,
"\u5728\uff1a{0} \u4e2d\u627e\u4e0d\u5230 xml-stylesheet PI"},
{ ER_NOT_SUPPORTED,
"\u4e0d\u652f\u63f4\uff1a{0}"},
{ ER_PROPERTY_VALUE_BOOLEAN,
"\u5167\u5bb9 {0} \u7684\u503c\u61c9\u70ba Boolean \u5be6\u4f8b"},
{ ER_COULD_NOT_FIND_EXTERN_SCRIPT,
"\u7121\u6cd5\u5728 {0} \u53d6\u5f97\u5916\u90e8 Script"},
{ ER_RESOURCE_COULD_NOT_FIND,
"\u627e\u4e0d\u5230\u8cc7\u6e90 [ {0} ]\u3002\n {1}"},
{ ER_OUTPUT_PROPERTY_NOT_RECOGNIZED,
"\u672a\u80fd\u8fa8\u8b58\u8f38\u51fa\u5167\u5bb9\uff1a{0}"},
{ ER_FAILED_CREATING_ELEMLITRSLT,
"\u5efa\u7acb ElemLiteralResult \u5be6\u4f8b\u5931\u6557"},
//Earlier (JDK 1.4 XALAN 2.2-D11) at key code '204' the key name was ER_PRIORITY_NOT_PARSABLE
// In latest Xalan code base key name is ER_VALUE_SHOULD_BE_NUMBER. This should also be taken care
//in locale specific files like XSLTErrorResources_de.java, XSLTErrorResources_fr.java etc.
//NOTE: Not only the key name but message has also been changed.
{ ER_VALUE_SHOULD_BE_NUMBER,
"{0} \u7684\u503c\u61c9\u8a72\u5305\u542b\u53ef\u5256\u6790\u7684\u6578\u5b57"},
{ ER_VALUE_SHOULD_EQUAL,
"{0} \u7684\u503c\u61c9\u7b49\u65bc yes \u6216 no"},
{ ER_FAILED_CALLING_METHOD,
"\u547c\u53eb {0} \u65b9\u6cd5\u5931\u6557"},
{ ER_FAILED_CREATING_ELEMTMPL,
"\u5efa\u7acb ElemTemplateElement \u5be6\u4f8b\u5931\u6557"},
{ ER_CHARS_NOT_ALLOWED,
"\u6587\u4ef6\u6b64\u9ede\u4e0d\u5141\u8a31\u5b57\u5143"},
{ ER_ATTR_NOT_ALLOWED,
"\"{0}\" \u5c6c\u6027\u5728 {1} \u5143\u7d20\u4e0a\u4e0d\u5141\u8a31\uff01"},
{ ER_BAD_VALUE,
"{0} \u4e0d\u6b63\u78ba\u7684\u503c {1}"},
{ ER_ATTRIB_VALUE_NOT_FOUND,
"\u627e\u4e0d\u5230 {0} \u5c6c\u6027\u503c"},
{ ER_ATTRIB_VALUE_NOT_RECOGNIZED,
"\u4e0d\u80fd\u8fa8\u8b58 {0} \u5c6c\u6027\u503c"},
{ ER_NULL_URI_NAMESPACE,
"\u5617\u8a66\u7528\u7a7a\u503c URI \u7522\u751f\u540d\u7a31\u7a7a\u9593\u5b57\u9996"},
//New ERROR keys added in XALAN code base after Jdk 1.4 (Xalan 2.2-D11)
{ ER_NUMBER_TOO_BIG,
"\u5617\u8a66\u683c\u5f0f\u5316\u5927\u65bc\u6700\u5927\u9577\u6574\u6578 (Long integer) \u7684\u6578\u5b57"},
{ ER_CANNOT_FIND_SAX1_DRIVER,
"\u627e\u4e0d\u5230 SAX1 \u9a45\u52d5\u7a0b\u5f0f\u985e\u5225 {0}"},
{ ER_SAX1_DRIVER_NOT_LOADED,
"\u627e\u5230 SAX1 \u9a45\u52d5\u7a0b\u5f0f\u985e\u5225 {0}\uff0c\u4f46\u7121\u6cd5\u8f09\u5165"},
{ ER_SAX1_DRIVER_NOT_INSTANTIATED,
"\u5df2\u8f09\u5165 SAX1 \u9a45\u52d5\u7a0b\u5f0f\u985e\u5225 {0}\uff0c\u4f46\u7121\u6cd5\u5be6\u4f8b\u5316"},
{ ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER,
"SAX1 \u9a45\u52d5\u7a0b\u5f0f\u985e\u5225 {0} \u4e0d\u80fd\u5728 org.xml.sax.Parser \u5be6\u4f5c"},
{ ER_PARSER_PROPERTY_NOT_SPECIFIED,
"\u7121\u6cd5\u6307\u5b9a\u7cfb\u7d71\u5167\u5bb9 org.xml.sax.parser"},
{ ER_PARSER_ARG_CANNOT_BE_NULL,
"\u5256\u6790\u5668\u5f15\u6578\u4e0d\u53ef\u70ba\u7a7a\u503c"},
{ ER_FEATURE,
"\u529f\u80fd\uff1a{0}"},
{ ER_PROPERTY,
"\u5167\u5bb9\uff1a{0}"},
{ ER_NULL_ENTITY_RESOLVER,
"\u7a7a\u503c\u5be6\u9ad4\u89e3\u6790\u5668"},
{ ER_NULL_DTD_HANDLER,
"\u7a7a\u503c DTD \u8655\u7406\u7a0b\u5f0f"},
{ ER_NO_DRIVER_NAME_SPECIFIED,
"\u672a\u6307\u5b9a\u9a45\u52d5\u7a0b\u5f0f\u540d\u7a31\uff01"},
{ ER_NO_URL_SPECIFIED,
"\u672a\u6307\u5b9a URL\uff01"},
{ ER_POOLSIZE_LESS_THAN_ONE,
"\u5132\u5b58\u6c60\u5c0f\u65bc 1\uff01"},
{ ER_INVALID_DRIVER_NAME,
"\u6307\u5b9a\u7684\u9a45\u52d5\u7a0b\u5f0f\u540d\u7a31\u7121\u6548\uff01"},
{ ER_ERRORLISTENER,
"ErrorListener"},
// Note to translators: The following message should not normally be displayed
// to users. It describes a situation in which the processor has detected
// an internal consistency problem in itself, and it provides this message
// for the developer to help diagnose the problem. The name
// 'ElemTemplateElement' is the name of a class, and should not be
// translated.
{ ER_ASSERT_NO_TEMPLATE_PARENT,
"\u7a0b\u5f0f\u8a2d\u8a08\u5e2b\u7684\u932f\u8aa4\uff01\u8868\u793a\u5f0f\u6c92\u6709 ElemTemplateElement \u6bcd\u9805\uff01"},
// Note to translators: The following message should not normally be displayed
// to users. It describes a situation in which the processor has detected
// an internal consistency problem in itself, and it provides this message
// for the developer to help diagnose the problem. The substitution text
// provides further information in order to diagnose the problem. The name
// 'RedundentExprEliminator' is the name of a class, and should not be
// translated.
{ ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR,
"\u7a0b\u5f0f\u8a2d\u8a08\u5e2b\u5728 RedundentExprEliminator \u4e2d\u7684\u78ba\u8a8d\uff1a{0}"},
{ ER_NOT_ALLOWED_IN_POSITION,
"\u5728\u6b64\u6a23\u5f0f\u8868\u4e2d\uff0c\u6b64\u4f4d\u7f6e\u4e0d\u53ef\u4ee5\u662f {0}\u3002"},
{ ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION,
"\u5728\u6b64\u6a23\u5f0f\u8868\u4e2d\uff0c\u6b64\u4f4d\u7f6e\u4e0d\u53ef\u4ee5\u662f\u975e\u7a7a\u767d\u5b57\u5143\uff01"},
// This code is shared with warning codes.
// SystemId Unknown
{ INVALID_TCHAR,
"CHAR \u5c6c\u6027\uff1a{0} \u4f7f\u7528\u7684\u503c\uff1a{1} \u4e0d\u5408\u6cd5\u3002CHAR \u985e\u578b\u7684\u5c6c\u6027\u53ea\u80fd\u6709\u4e00\u500b\u5b57\u5143\uff01"},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "QNAME" is the XML data-type of
// the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
//The following codes are shared with the warning codes...
{ INVALID_QNAME,
"QNAME \u5c6c\u6027\uff1a{0} \u4f7f\u7528\u7684\u503c\uff1a{1} \u4e0d\u5408\u6cd5"},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "ENUM" is the XML data-type of
// the attribute, and should not be translated. The substitution text {1} is
// the attribute value, {0} is the attribute name, and {2} is a list of valid
// values.
{ INVALID_ENUM,
"ENUM \u5c6c\u6027\uff1a{0} \u4f7f\u7528\u7684\u503c\uff1a{1} \u4e0d\u5408\u6cd5\u3002\u6709\u6548\u7684\u503c\u70ba\uff1a{2}\u3002"},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "NMTOKEN" is the XML data-type
// of the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
{ INVALID_NMTOKEN,
"NMTOKEN \u5c6c\u6027\uff1a{0} \u4f7f\u7528\u7684\u503c\uff1a{1} \u4e0d\u5408\u6cd5"},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "NCNAME" is the XML data-type
// of the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
{ INVALID_NCNAME,
"NCNAME \u5c6c\u6027\uff1a{0} \u4f7f\u7528\u7684\u503c\uff1a{1} \u4e0d\u5408\u6cd5"},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "boolean" is the XSLT data-type
// of the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
{ INVALID_BOOLEAN,
"Boolean \u5c6c\u6027\uff1a{0} \u4f7f\u7528\u7684\u503c\uff1a{1} \u4e0d\u5408\u6cd5"},
// Note to translators: The following message is used if the value of
// an attribute in a stylesheet is invalid. "number" is the XSLT data-type
// of the attribute, and should not be translated. The substitution text {1} is
// the attribute value and {0} is the attribute name.
{ INVALID_NUMBER,
"Number \u5c6c\u6027\uff1a{0} \u4f7f\u7528\u7684\u503c\uff1a{1} \u4e0d\u5408\u6cd5"},
// End of shared codes...
// Note to translators: A "match pattern" is a special form of XPath expression
// that is used for matching patterns. The substitution text is the name of
// a function. The message indicates that when this function is referenced in
// a match pattern, its argument must be a string literal (or constant.)
// ER_ARG_LITERAL - new error message for bugzilla //5202
{ ER_ARG_LITERAL,
"\u6bd4\u5c0d\u578b\u6a23\u4e2d\u7684 ''''{0}'''' \u7684\u5f15\u6578\u5fc5\u9808\u662f\u6587\u5b57\u3002"},
// Note to translators: The following message indicates that two definitions of
// a variable. A "global variable" is a variable that is accessible everywher
// in the stylesheet.
// ER_DUPLICATE_GLOBAL_VAR - new error message for bugzilla #790
{ ER_DUPLICATE_GLOBAL_VAR,
"\u5ee3\u57df\u8b8a\u6578\u5ba3\u544a\u91cd\u8907\u3002"},
// Note to translators: The following message indicates that two definitions of
// a variable were encountered.
// ER_DUPLICATE_VAR - new error message for bugzilla #790
{ ER_DUPLICATE_VAR,
"\u8b8a\u6578\u5ba3\u544a\u91cd\u8907\u3002"},
// Note to translators: "xsl:template, "name" and "match" are XSLT keywords
// which must not be translated.
// ER_TEMPLATE_NAME_MATCH - new error message for bugzilla #789
{ ER_TEMPLATE_NAME_MATCH,
"xsl:template \u5fc5\u9808\u6709\u540d\u7a31\u6216\u76f8\u7b26\u7684\u5c6c\u6027\uff08\u6216\u5169\u8005\uff09"},
// Note to translators: "exclude-result-prefixes" is an XSLT keyword which
// should not be translated. The message indicates that a namespace prefix
// encountered as part of the value of the exclude-result-prefixes attribute
// was in error.
// ER_INVALID_PREFIX - new error message for bugzilla #788
{ ER_INVALID_PREFIX,
"exclude-result-prefixes \u4e2d\u7684\u5b57\u9996\u7121\u6548\uff1a{0}"},
// Note to translators: An "attribute set" is a set of attributes that can
// be added to an element in the output document as a group. The message
// indicates that there was a reference to an attribute set named {0} that
// was never defined.
// ER_NO_ATTRIB_SET - new error message for bugzilla #782
{ ER_NO_ATTRIB_SET,
"attribute-set \u540d\u7a31 {0} \u4e0d\u5b58\u5728"},
// Note to translators: This message indicates that there was a reference
// to a function named {0} for which no function definition could be found.
{ ER_FUNCTION_NOT_FOUND,
"\u51fd\u6578\u540d\u70ba {0} \u4e0d\u5b58\u5728"},
// Note to translators: This message indicates that the XSLT instruction
// that is named by the substitution text {0} must not contain other XSLT
// instructions (content) or a "select" attribute. The word "select" is
// an XSLT keyword in this case and must not be translated.
{ ER_CANT_HAVE_CONTENT_AND_SELECT,
"{0} \u5143\u7d20\u4e0d\u5f97\u540c\u6642\u6709\u5167\u5bb9\u548c select \u5c6c\u6027\u3002"},
// Note to translators: This message indicates that the value argument
// of setParameter must be a valid Java Object.
{ ER_INVALID_SET_PARAM_VALUE,
"\u53c3\u6578 {0} \u7684\u503c\u5fc5\u9808\u662f\u6709\u6548\u7684 Java \u7269\u4ef6"},
{ ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT,
"\u4e00\u500b xsl:namespace-alias \u5143\u7d20\u7684 result-prefix \u5c6c\u6027\u6709\u503c '#default'\uff0c\u4f46\u5728\u8a72\u5143\u7d20\u7684\u7bc4\u570d\u4e2d\u4e26\u6c92\u6709\u9810\u8a2d\u540d\u7a31\u7a7a\u9593\u7684\u5ba3\u544a"},
{ ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX,
"\u4e00\u500b xsl:namespace-alias \u5143\u7d20\u7684 result-prefix \u5c6c\u6027\u6709\u503c ''{0}''\uff0c\u4f46\u5728\u8a72\u5143\u7d20\u7684\u7bc4\u570d\u4e2d\u4e26\u6c92\u6709\u5b57\u9996 ''{0}'' \u7684\u540d\u7a31\u7a7a\u9593\u5ba3\u544a\u3002"},
{ ER_SET_FEATURE_NULL_NAME,
"\u7279\u6027\u540d\u7a31\u5728 TransformerFactory.setFeature(\u5b57\u4e32\u540d\u7a31\u3001boolean \u503c) \u4e2d\u4e0d\u53ef\u662f\u7a7a\u503c\u3002"},
{ ER_GET_FEATURE_NULL_NAME,
"\u7279\u6027\u540d\u7a31\u5728 TransformerFactory.getFeature(\u5b57\u4e32\u540d\u7a31) \u4e2d\u4e0d\u53ef\u662f\u7a7a\u503c\u3002"},
{ ER_UNSUPPORTED_FEATURE,
"\u7121\u6cd5\u5728\u9019\u500b TransformerFactory \u8a2d\u5b9a\u7279\u6027 ''{0}''\u3002"},
{ ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING,
"\u7576\u5b89\u5168\u8655\u7406\u7279\u6027\u8a2d\u70ba true \u6642\uff0c\u4e0d\u63a5\u53d7\u4f7f\u7528\u5ef6\u4f38\u5143\u7d20 ''{0}''\u3002"},
{ ER_NAMESPACE_CONTEXT_NULL_NAMESPACE,
"\u7121\u6cd5\u53d6\u5f97\u7a7a\u503c\u540d\u7a31\u7a7a\u9593 uri \u7684\u5b57\u9996\u3002"},
{ ER_NAMESPACE_CONTEXT_NULL_PREFIX,
"\u7121\u6cd5\u53d6\u5f97\u7a7a\u503c\u5b57\u9996\u7684\u540d\u7a31\u7a7a\u9593 uri\u3002"},
{ ER_XPATH_RESOLVER_NULL_QNAME,
"\u51fd\u6578\u540d\u7a31\u4e0d\u53ef\u70ba\u7a7a\u503c\u3002"},
{ ER_XPATH_RESOLVER_NEGATIVE_ARITY,
"Arity \u4e0d\u53ef\u70ba\u8ca0\u503c\u3002"},
// Warnings...
{ WG_FOUND_CURLYBRACE,
"\u627e\u5230 '}' \u4f46\u6c92\u6709\u958b\u555f\u5c6c\u6027\u7bc4\u672c\uff01"},
{ WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR,
"\u8b66\u544a\uff1acount \u5c6c\u6027\u4e0d\u7b26\u5408 xsl:number \u4e2d\u7684\u88ab\u7e7c\u627f\u8005\uff01\u76ee\u6a19 = {0}"},
{ WG_EXPR_ATTRIB_CHANGED_TO_SELECT,
"\u820a\u8a9e\u6cd5\uff1a'expr' \u5c6c\u6027\u7684\u540d\u7a31\u5df2\u8b8a\u66f4\u70ba 'select'\u3002"},
{ WG_NO_LOCALE_IN_FORMATNUMBER,
"Xalan \u5c1a\u672a\u8655\u7406 format-number \u51fd\u6578\u4e2d\u7684\u8a9e\u8a00\u74b0\u5883\u540d\u7a31\u3002"},
{ WG_LOCALE_NOT_FOUND,
"\u8b66\u544a\uff1a\u627e\u4e0d\u5230 xml:lang={0} \u7684\u8a9e\u8a00\u74b0\u5883"},
{ WG_CANNOT_MAKE_URL_FROM,
"\u7121\u6cd5\u5f9e\uff1a{0} \u7522\u751f URL"},
{ WG_CANNOT_LOAD_REQUESTED_DOC,
"\u7121\u6cd5\u8f09\u5165\u6240\u8981\u6c42\u7684\u6587\u4ef6\uff1a{0}"},
{ WG_CANNOT_FIND_COLLATOR,
"\u627e\u4e0d\u5230 <sort xml:lang={0} \u7684\u7406\u5e8f\u5668"},
{ WG_FUNCTIONS_SHOULD_USE_URL,
"\u820a\u8a9e\u6cd5\uff1a\u51fd\u6578\u6307\u4ee4\u61c9\u4f7f\u7528 {0} \u7684 URL"},
{ WG_ENCODING_NOT_SUPPORTED_USING_UTF8,
"\u4e0d\u652f\u63f4\u7de8\u78bc\uff1a{0}\uff0c\u8acb\u4f7f\u7528 UTF-8"},
{ WG_ENCODING_NOT_SUPPORTED_USING_JAVA,
"\u4e0d\u652f\u63f4\u7de8\u78bc\uff1a{0}\uff0c\u8acb\u4f7f\u7528 Java {1}"},
{ WG_SPECIFICITY_CONFLICTS,
"\u627e\u5230\u7279\u5b9a\u885d\u7a81\uff1a{0} \u5c07\u4f7f\u7528\u5728\u6a23\u5f0f\u8868\u4e2d\u627e\u5230\u7684\u6700\u5f8c\u4e00\u500b\u3002"},
{ WG_PARSING_AND_PREPARING,
"========= \u5256\u6790\u8207\u6e96\u5099 {0} =========="},
{ WG_ATTR_TEMPLATE,
"\u5c6c\u6027\u7bc4\u672c\uff0c{0}"},
{ WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESPACE,
"\u5728 xsl:strip-space \u548c xsl:preserve-space \u4e4b\u9593\u6709\u6bd4\u5c0d\u885d\u7a81"},
{ WG_ATTRIB_NOT_HANDLED,
"Xalan \u5c1a\u672a\u8655\u7406 {0} \u5c6c\u6027\uff01"},
{ WG_NO_DECIMALFORMAT_DECLARATION,
"\u627e\u4e0d\u5230\u5341\u9032\u4f4d\u683c\u5f0f\u7684\u5ba3\u544a\uff1a{0}"},
{ WG_OLD_XSLT_NS,
"XSLT \u540d\u7a31\u7a7a\u9593\u907a\u6f0f\u6216\u4e0d\u6b63\u78ba\u3002"},
{ WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED,
"\u50c5\u5141\u8a31\u4e00\u500b\u9810\u8a2d xsl:decimal-format \u5ba3\u544a\u3002"},
{ WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE,
"xsl:decimal-format \u540d\u7a31\u5fc5\u9808\u662f\u552f\u4e00\u7684\u3002\u540d\u7a31 \"{0}\" \u5df2\u91cd\u8907\u3002"},
{ WG_ILLEGAL_ATTRIBUTE,
"{0} \u542b\u6709\u4e0d\u5408\u6cd5\u7684\u5c6c\u6027\uff1a{1}"},
{ WG_COULD_NOT_RESOLVE_PREFIX,
"\u7121\u6cd5\u89e3\u6790\u540d\u7a31\u7a7a\u9593\u5b57\u9996\uff1a{0}\u3002\u7bc0\u9ede\u5c07\u88ab\u5ffd\u7565\u3002"},
{ WG_STYLESHEET_REQUIRES_VERSION_ATTRIB,
"xsl:stylesheet \u9700\u8981 'version' \u5c6c\u6027\uff01"},
{ WG_ILLEGAL_ATTRIBUTE_NAME,
"\u4e0d\u5408\u6cd5\u5c6c\u6027\u540d\u7a31\uff1a{0}"},
{ WG_ILLEGAL_ATTRIBUTE_VALUE,
"\u5c6c\u6027 {0} \u4f7f\u7528\u4e86\u4e0d\u5408\u6cd5\u503c\uff1a{1}"},
{ WG_EMPTY_SECOND_ARG,
"\u5f9e\u6587\u4ef6\u51fd\u6578\u7b2c\u4e8c\u500b\u5f15\u6578\u7522\u751f\u7684\u7bc0\u9ede\u96c6\u662f\u7a7a\u503c\u3002\u50b3\u56de\u7a7a\u7684\u7bc0\u9ede\u96c6\u3002"},
//Following are the new WARNING keys added in XALAN code base after Jdk 1.4 (Xalan 2.2-D11)
// Note to translators: "name" and "xsl:processing-instruction" are keywords
// and must not be translated.
{ WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML,
"xsl:processing-instruction \u540d\u7a31\u7684 'name' \u5c6c\u6027\u503c\u4e0d\u53ef\u4ee5\u662f 'xml'"},
// Note to translators: "name" and "xsl:processing-instruction" are keywords
// and must not be translated. "NCName" is an XML data-type and must not be
// translated.
{ WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME,
"xsl:processing-instruction \u7684 ''name'' \u5c6c\u6027\u503c\u5fc5\u9808\u662f\u6709\u6548\u7684 NCName\uff1a{0}"},
// Note to translators: This message is reported if the stylesheet that is
// being processed attempted to construct an XML document with an attribute in a
// place other than on an element. The substitution text specifies the name of
// the attribute.
{ WG_ILLEGAL_ATTRIBUTE_POSITION,
"\u5728\u7522\u751f\u5b50\u9805\u7bc0\u9ede\u4e4b\u5f8c\uff0c\u6216\u5728\u7522\u751f\u5143\u7d20\u4e4b\u524d\uff0c\u4e0d\u53ef\u65b0\u589e\u5c6c\u6027 {0}\u3002\u5c6c\u6027\u6703\u88ab\u5ffd\u7565\u3002"},
{ NO_MODIFICATION_ALLOWED_ERR,
"\u5617\u8a66\u4fee\u6539\u4e0d\u63a5\u53d7\u4fee\u6539\u7684\u7269\u4ef6\u3002"
},
//Check: WHY THERE IS A GAP B/W NUMBERS in the XSLTErrorResources properties file?
// Other miscellaneous text used inside the code...
{ "ui_language", "zh"},
{ "help_language", "zh" },
{ "language", "zh" },
{ "BAD_CODE", "createMessage \u7684\u53c3\u6578\u8d85\u51fa\u754c\u9650"},
{ "FORMAT_FAILED", "\u5728 messageFormat \u547c\u53eb\u671f\u9593\u64f2\u51fa\u7570\u5e38"},
{ "version", ">>>>>>> Xalan \u7248\u672c"},
{ "version2", "<<<<<<<"},
{ "yes", "yes"},
{ "line", "\u884c\u865f"},
{ "column","\u6b04\u865f"},
{ "xsldone", "XSLProcessor\uff1a\u5b8c\u6210"},
// Note to translators: The following messages provide usage information
// for the Xalan Process command line. "Process" is the name of a Java class,
// and should not be translated.
{ "xslProc_option", "Xalan-J \u6307\u4ee4\u884c Process \u985e\u5225\u9078\u9805\uff1a"},
{ "xslProc_option", "Xalan-J \u6307\u4ee4\u884c Process \u985e\u5225\u9078\u9805\u003a"},
{ "xslProc_invalid_xsltc_option", "XSLTC \u6a21\u5f0f\u4e0d\u652f\u63f4\u9078\u9805 {0}\u3002"},
{ "xslProc_invalid_xalan_option", "\u9078\u9805 {0} \u53ea\u80fd\u548c -XSLTC \u4e00\u8d77\u4f7f\u7528\u3002"},
{ "xslProc_no_input", "\u932f\u8aa4\uff1a\u672a\u6307\u5b9a\u6a23\u5f0f\u8868\u6216\u8f38\u5165 xml\u3002\u57f7\u884c\u6b64\u6307\u4ee4\u6642\u4e0d\u8981\u5305\u542b\u4efb\u4f55\u9078\u9805\uff0c\u5373\u53ef\u53d6\u5f97\u7528\u6cd5\u6307\u793a\u3002"},
{ "xslProc_common_options", "-\u4e00\u822c\u9078\u9805-"},
{ "xslProc_xalan_options", "-Xalan \u7684\u9078\u9805-"},
{ "xslProc_xsltc_options", "-XSLTC \u7684\u9078\u9805-"},
{ "xslProc_return_to_continue", "(\u6309 <return> \u7e7c\u7e8c)"},
// Note to translators: The option name and the parameter name do not need to
// be translated. Only translate the messages in parentheses. Note also that
// leading whitespace in the messages is used to indent the usage information
// for each option in the English messages.
// Do not translate the keywords: XSLTC, SAX, DOM and DTM.
{ "optionXSLTC", "[-XSLTC (\u4f7f\u7528 XSLTC \u9032\u884c\u8f49\u63db)]"},
{ "optionIN", "[-IN inputXMLURL]"},
{ "optionXSL", "[-XSL XSLTransformationURL]"},
{ "optionOUT", "[-OUT outputFileName]"},
{ "optionLXCIN", "[-LXCIN compiledStylesheetFileNameIn]"},
{ "optionLXCOUT", "[-LXCOUT compiledStylesheetFileNameOutOut]"},
{ "optionPARSER", "[-PARSER fully qualified class name of parser liaison]"},
{ "optionE", " [-E\uff08\u4e0d\u5c55\u958b\u5be6\u9ad4\u53c3\u7167\uff09]"},
{ "optionV", " [-E\uff08\u4e0d\u5c55\u958b\u5be6\u9ad4\u53c3\u7167\uff09]"},
{ "optionQC", " [-QC\uff08\u7121\u8072\u578b\u6a23\u885d\u7a81\u8b66\u544a\uff09]"},
{ "optionQ", " [-Q \uff08\u7121\u8072\u6a21\u5f0f\uff09]"},
{ "optionLF", " [-LF\uff08\u53ea\u5728\u8f38\u51fa\u4e0a\u4f7f\u7528\u8f38\u51fa {\u9810\u8a2d\u662f CR/LF}\uff09]"},
{ "optionCR", " [-LF\uff08\u53ea\u5728\u8f38\u51fa\u4e0a\u4f7f\u7528\u56de\u8eca {\u9810\u8a2d\u662f CR/LF}\uff09]"},
{ "optionESCAPE", "[-ESCAPE\uff08\u8981\u8df3\u51fa\u7684\u5b57\u5143 {\u9810\u8a2d\u662f <>&\"\'\\r\\n}]"},
{ "optionINDENT", "[-INDENT\uff08\u63a7\u5236\u8981\u5167\u7e2e\u7684\u7a7a\u683c\u6578 {\u9810\u8a2d\u662f 0}\uff09]"},
{ "optionTT", " [-TT\uff08\u5728\u88ab\u547c\u53eb\u6642\u8ffd\u8e64\u7bc4\u672c\u3002\uff09]"},
{ "optionTG", " [-TG\uff08\u8ffd\u8e64\u6bcf\u4e00\u500b\u7522\u751f\u4e8b\u4ef6\u3002\uff09]"},
{ "optionTS", " [-TS\uff08\u8ffd\u8e64\u6bcf\u4e00\u500b\u9078\u53d6\u4e8b\u4ef6\u3002\uff09]"},
{ "optionTTC", " [-TTC\uff08\u5728\u88ab\u8655\u7406\u6642\u8ffd\u8e64\u7bc4\u672c\u5b50\u9805\u5143\u4ef6\u3002\uff09]"},
{ "optionTCLASS", " [-TCLASS\uff08\u8ffd\u8e64\u5ef6\u4f38\u9805\u76ee\u7684 TraceListener \u985e\u5225\u3002\uff09]"},
{ "optionVALIDATE", "[-VALIDATE\uff08\u8a2d\u5b9a\u662f\u5426\u767c\u751f\u9a57\u8b49\u3002\u4f9d\u9810\u8a2d\u9a57\u8b49\u662f\u95dc\u9589\u7684\u3002\uff09]"},
{ "optionEDUMP", "[-EDUMP {\u9078\u7528\u7684\u6a94\u6848\u540d\u7a31}\uff08\u767c\u751f\u932f\u8aa4\u6642\u57f7\u884c stackdump\uff09]"},
{ "optionXML", " [-XML\uff08\u4f7f\u7528 XML \u683c\u5f0f\u88fd\u4f5c\u5668\u53ca\u65b0\u589e XML \u6a19\u982d\u3002\uff09]"},
{ "optionTEXT", " [-TEXT\uff08\u4f7f\u7528\u7c21\u6613\u6587\u5b57\u683c\u5f0f\u5316\u7a0b\u5f0f\u3002\uff09]"},
{ "optionHTML", " [-HTML\uff08\u4f7f\u7528 HTML \u683c\u5f0f\u88fd\u4f5c\u5668\u3002\uff09]"},
{ "optionPARAM", " [-PARAM \u540d\u7a31\u8868\u793a\u5f0f\uff08\u8a2d\u5b9a\u6a23\u5f0f\u8868\u53c3\u6578\uff09]"},
{ "noParsermsg1", "XSL \u7a0b\u5e8f\u6c92\u6709\u9806\u5229\u5b8c\u6210\u3002"},
{ "noParsermsg2", "** \u627e\u4e0d\u5230\u5256\u6790\u5668 **"},
{ "noParsermsg3", "\u8acb\u6aa2\u67e5\u985e\u5225\u8def\u5f91\u3002"},
{ "noParsermsg4", "\u5982\u679c\u60a8\u6c92\u6709 IBM \u7684 XML Parser for Java\uff0c\u53ef\u81ea\u4ee5\u4e0b\u7db2\u5740\u4e0b\u8f09"},
{ "noParsermsg5", "IBM \u7684 AlphaWorks\uff1ahttp://www.alphaworks.ibm.com/formula/xml"},
{ "optionURIRESOLVER", "[-URIRESOLVER \u5b8c\u6574\u7684\u985e\u5225\u540d\u7a31\uff08URIResolver \u7528\u4f86\u89e3\u6790 URI\uff09]"},
{ "optionENTITYRESOLVER", "[-ENTITYRESOLVER \u5b8c\u6574\u7684\u985e\u5225\u540d\u7a31\uff08EntityResolver \u7528\u4f86\u89e3\u6790\u5be6\u9ad4\uff09]"},
{ "optionCONTENTHANDLER", "[-CONTENTHANDLER \u5b8c\u6574\u7684\u985e\u5225\u540d\u7a31\uff08ContentHandler \u7528\u4f86\u5e8f\u5217\u5316\u8f38\u51fa\uff09]"},
{ "optionLINENUMBERS", "[-L \u4f7f\u7528\u539f\u59cb\u6587\u4ef6\u7684\u884c\u865f]"},
{ "optionSECUREPROCESSING", " [-SECURE (\u5c07\u5b89\u5168\u8655\u7406\u7279\u6027\u8a2d\u70ba true\u3002)]"},
// Following are the new options added in XSLTErrorResources.properties files after Jdk 1.4 (Xalan 2.2-D11)
{ "optionMEDIA", " [-MEDIA mediaType\uff08\u4f7f\u7528\u5a92\u9ad4\u5c6c\u6027\u5c0b\u627e\u8207\u6587\u4ef6\u76f8\u95dc\u806f\u7684\u6a23\u5f0f\u8868\u3002\uff09]"},
{ "optionFLAVOR", " [-FLAVOR flavorName\uff08\u660e\u78ba\u4f7f\u7528 s2s=SAX \u6216 d2d=DOM \u4f86\u57f7\u884c\u8f49\u63db\u3002\uff09] "}, // Added by sboag/scurcuru; experimental
{ "optionDIAG", " [-DIAG (\u5217\u5370\u8f49\u63db\u82b1\u8cbb\u7684\u6beb\u79d2\u6578\u3002\uff09]"},
{ "optionINCREMENTAL", " [-INCREMENTAL\uff08\u8a2d\u5b9a http://xml.apache.org/xalan/features/incremental \u70ba true\uff0c\u8981\u6c42\u6f38\u9032\u5f0f DTM \u5efa\u69cb\u3002\uff09]"},
{ "optionNOOPTIMIMIZE", " [-NOOPTIMIMIZE\uff08\u8a2d\u5b9a http://xml.apache.org/xalan/features/optimize \u70ba false\uff0c\u8981\u6c42\u4e0d\u9032\u884c\u6a23\u5f0f\u8868\u6700\u4f73\u5316\u8655\u7406\u7a0b\u5e8f\u3002)]"},
{ "optionRL", " [-RL recursionlimit\uff08\u4e3b\u5f35\u5c0d\u6a23\u5f0f\u8868\u905e\u8ff4\u6df1\u5ea6\u5be6\u65bd\u6578\u503c\u9650\u5236\u3002\uff09]"},
{ "optionXO", "[-XO [transletName] (\u6307\u5b9a\u540d\u7a31\u7d66\u7522\u751f\u7684 translet)]"},
{ "optionXD", "[-XD destinationDirectory (\u6307\u5b9a translet \u7684\u76ee\u6a19\u76ee\u9304)]"},
{ "optionXJ", "[-XJ jarfile (\u5c07 translet \u985e\u5225\u5c01\u88dd\u5728\u6a94\u540d\u70ba <jarfile> \u7684 jar \u6a94\u6848\u4e2d)]"},
{ "optionXP", "[-XP package (\u6307\u5b9a\u6240\u7522\u751f\u7684\u6240\u6709 translet \u985e\u5225\u4e4b\u5957\u4ef6\u540d\u7a31\u5b57\u9996)]"},
//AddITIONAL STRINGS that need L10n
// Note to translators: The following message describes usage of a particular
// command-line option that is used to enable the "template inlining"
// optimization. The optimization involves making a copy of the code
// generated for a template in another template that refers to it.
{ "optionXN", "[-XN (\u555f\u7528\u7bc4\u672c\u5217\u5165)]" },
{ "optionXX", "[-XX (\u958b\u555f\u984d\u5916\u7684\u9664\u932f\u8a0a\u606f\u8f38\u51fa)]"},
{ "optionXT" , "[-XT (\u53ef\u80fd\u7684\u8a71\uff0c\u4f7f\u7528 translet \u9032\u884c\u8f49\u63db)]"},
{ "diagTiming","--------- \u900f\u904e {1} \u8017\u8cbb {2} \u6beb\u79d2\u8f49\u63db {0}" },
{ "recursionTooDeep","\u7bc4\u672c\u5de2\u72c0\u7d50\u69cb\u592a\u6df1\u3002\u5de2\u72c0 = {0}\uff0c\u7bc4\u672c {1} {2}" },
{ "nameIs", "\u540d\u7a31\u70ba" },
{ "matchPatternIs", "\u6bd4\u5c0d\u578b\u6a23\u70ba" }
};
}
// ================= INFRASTRUCTURE ======================
/** String for use when a bad error code was encountered. */
public static final String BAD_CODE = "BAD_CODE";
/** String for use when formatting of the error string failed. */
public static final String FORMAT_FAILED = "FORMAT_FAILED";
/** General error string. */
public static final String ERROR_STRING = "#error";
/** String to prepend to error messages. */
public static final String ERROR_HEADER = "\u932f\u8aa4\uff1a";
/** String to prepend to warning messages. */
public static final String WARNING_HEADER = "\u8b66\u544a\uff1a";
/** String to specify the XSLT module. */
public static final String XSL_HEADER = "XSLT ";
/** String to specify the XML parser module. */
public static final String XML_HEADER = "XML ";
/** I don't think this is used any more.
* @deprecated */
public static final String QUERY_HEADER = "PATTERN ";
/**
* Return a named ResourceBundle for a particular locale. This method mimics the behavior
* of ResourceBundle.getBundle().
*
* @param className the name of the class that implements the resource bundle.
* @return the ResourceBundle
* @throws MissingResourceException
*/
public static final XSLTErrorResources loadResourceBundle(String className)
throws MissingResourceException
{
Locale locale = Locale.getDefault();
String suffix = getResourceSuffix(locale);
try
{
// first try with the given locale
return (XSLTErrorResources) ResourceBundle.getBundle(className
+ suffix, locale);
}
catch (MissingResourceException e)
{
try // try to fall back to en_US if we can't load
{
// Since we can't find the localized property file,
// fall back to en_US.
return (XSLTErrorResources) ResourceBundle.getBundle(className,
new Locale("zh", "TW"));
}
catch (MissingResourceException e2)
{
// Now we are really in trouble.
// very bad, definitely very bad...not going to get very far
throw new MissingResourceException(
"Could not load any resource bundles.", className, "");
}
}
}
/**
* Return the resource file suffic for the indicated locale
* For most locales, this will be based the language code. However
* for Chinese, we do distinguish between Taiwan and PRC
*
* @param locale the locale
* @return an String suffix which canbe appended to a resource name
*/
private static final String getResourceSuffix(Locale locale)
{
String suffix = "_" + locale.getLanguage();
String country = locale.getCountry();
if (country.equals("TW"))
suffix += "_" + country;
return suffix;
}
}
| gpl-3.0 |
cwgreene/RegexGenerator | Random Regex Turtle/src/it/units/inginf/male/strategy/impl/DefaultStrategy.java | 10731 | /*
* Copyright (C) 2015 Machine Learning Lab - University of Trieste,
* Italy (http://machinelearning.inginf.units.it/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.units.inginf.male.strategy.impl;
import it.units.inginf.male.configuration.Configuration;
import it.units.inginf.male.configuration.EvolutionParameters;
import it.units.inginf.male.evaluators.TreeEvaluationException;
import it.units.inginf.male.generations.Generation;
import it.units.inginf.male.generations.InitialPopulationBuilder;
import it.units.inginf.male.generations.Ramped;
import it.units.inginf.male.inputs.Context;
import it.units.inginf.male.objective.Objective;
import it.units.inginf.male.objective.Ranking;
import it.units.inginf.male.selections.Selection;
import it.units.inginf.male.selections.Tournament;
import it.units.inginf.male.strategy.ExecutionListener;
import it.units.inginf.male.strategy.RunStrategy;
import it.units.inginf.male.tree.Node;
import it.units.inginf.male.utils.Pair;
import it.units.inginf.male.utils.Utils;
import it.units.inginf.male.variations.Variation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Implements the default evolution strategy, termination criteria can be enabled thru parameters.
* Optional accepted parameters:
* "terminationCriteria", Boolean, then True the termination criteria is enabled when false is disabled, Default value: false
* "terminationCriteriaGenerations", Integer, number of generations for the termination criteria.Default value: 200
* @author MaleLabTs
*/
public class DefaultStrategy implements RunStrategy {
protected Context context;
protected int maxDepth;
protected List<Node> population;
protected List<Ranking> rankings = new LinkedList<>();
protected Selection selection;
protected Objective objective;
protected Variation variation;
protected EvolutionParameters param;
protected ExecutionListener listener;
protected boolean terminationCriteria = false; //Termination criteria enables/disables the premature termination of thread when best regex/individual doens't change for
//a speciefied amount of generations (terminationCriteriaGenerations)
protected int terminationCriteriaGenerations = 200;
@Override
public void setup(Configuration configuration, ExecutionListener listener) throws TreeEvaluationException {
this.param = configuration.getEvolutionParameters();
this.readParameters(configuration);
this.context = new Context(Context.EvaluationPhases.TRAINING, configuration);
this.maxDepth = param.getCreationMaxDepth();
//cloning the objective
this.objective = configuration.getObjective();
this.selection = new Tournament(this.context);
this.variation = new Variation(this.context);
this.listener = listener;
this.objective.setup(context);
}
protected void readParameters(Configuration configuration){
Map<String, String> parameters = configuration.getStrategyParameters();
if (parameters != null) {
//add parameters if needed
if (parameters.containsKey("terminationCriteriaGenerations")) {
terminationCriteriaGenerations = Integer.valueOf(parameters.get("terminationCriteriaGenerations"));
}
if (parameters.containsKey("terminationCriteria")) {
terminationCriteria = Boolean.valueOf(parameters.get("terminationCriteria"));
}
}
}
@Override
public Void call() throws TreeEvaluationException {
try {
int generation;
listener.evolutionStarted(this);
InitialPopulationBuilder populationBuilder = context.getConfiguration().getPopulationBuilder();
this.population = populationBuilder.init();
Generation ramped = new Ramped(this.maxDepth, this.context);
this.population.addAll(ramped.generate(param.getPopulationSize() - population.size()));
List<Ranking> tmp = buildRankings(population, objective);
while (tmp.size() > 0) {
List<Ranking> t = Utils.getFirstParetoFront(tmp);
tmp.removeAll(t);
sortByFirst(t);
this.rankings.addAll(t);
}
//Variables for termination criteria
String oldGenerationBestValue = null;
int terminationCriteriaGenerationsCounter = 0;
int doneGenerations = 0;
for (generation = 0; generation < param.getGenerations(); generation++) {
context.setStripedPhase(context.getDataSetContainer().isDataSetStriped() && ((generation % context.getDataSetContainer().getProposedNormalDatasetInterval()) != 0));
evolve();
Ranking best = rankings.get(0);
doneGenerations = generation + 1;
if (listener != null) {
listener.logGeneration(this, doneGenerations, best.getTree(), best.getFitness(), this.rankings);
}
boolean allPerfect = true;
for (double fitness : this.rankings.get(0).getFitness()) {
if (Math.round(fitness * 10000) != 0) {
allPerfect = false;
break;
}
}
if (allPerfect) {
break;
}
if(terminationCriteria){
String newBestValue = best.getDescription();
if(newBestValue.equals(oldGenerationBestValue)){
terminationCriteriaGenerationsCounter++;
} else {
terminationCriteriaGenerationsCounter = 0;
}
if(terminationCriteriaGenerationsCounter >= this.terminationCriteriaGenerations) {
break;
}
oldGenerationBestValue = newBestValue;
}
if (Thread.interrupted()) {
break;
}
}
//now generation value is already last generation + 1, no reason to add +1
if (listener != null) {
listener.evolutionComplete(this, doneGenerations, this.rankings);
}
return null;
} catch (Throwable x) {
throw new TreeEvaluationException("Error during evaluation of a tree", x, this);
}
}
protected void evolve() {
List<Node> newPopulation = new ArrayList<>(population.size());
int popSize = population.size();
int oldPopSize = (int) (popSize * 0.9);
boolean allPerfect = true;
for (double fitness : rankings.get(0).getFitness()) {
if (Math.round(fitness * 10000) != 0) {
allPerfect = false;
break;
}
}
if (allPerfect) {
return;
}
for (int index = 0; index < param.getElitarism(); index++) {
Node elite = rankings.remove(0).getTree();
newPopulation.add(elite);
}
while (newPopulation.size() < oldPopSize) {
double random = context.getRandom().nextDouble();
if (random <= param.getCrossoverProbability() && oldPopSize - newPopulation.size() >= 2) {
Node selectedA = selection.select(rankings);
Node selectedB = selection.select(rankings);
Pair<Node, Node> newIndividuals = variation.crossover(selectedA, selectedB);
if (newIndividuals != null) {
newPopulation.add(newIndividuals.getFirst());
newPopulation.add(newIndividuals.getSecond());
}
} else if (random <= param.getCrossoverProbability() + param.getMutationPobability()) {
Node mutant = selection.select(this.rankings);
mutant = variation.mutate(mutant);
newPopulation.add(mutant);
} else {
Node duplicated = selection.select(rankings);
newPopulation.add(duplicated);
}
}
Generation ramped = new Ramped(maxDepth, context);
List<Node> generated = ramped.generate(popSize - oldPopSize);
newPopulation.addAll(generated);
population = newPopulation;
List<Ranking> tmp = buildRankings(population, objective);
rankings.clear();
while (tmp.size() > 0) {
List<Ranking> t = Utils.getFirstParetoFront(tmp);
tmp.removeAll(t);
sortByFirst(t);
rankings.addAll(t);
}
}
protected List<Ranking> buildRankings(List<Node> population, Objective objective) {
List<Ranking> result = new ArrayList<>(population.size());
for (Node tree : population) {
double fitness[] = objective.fitness(tree);
result.add(new Ranking(tree, fitness));
}
return result;
}
@Override
public Configuration getConfiguration() {
return context.getConfiguration();
}
@Override
public ExecutionListener getExecutionListener() {
return listener;
}
protected void sortByFirst(List<Ranking> front) {
Collections.sort(front, new Comparator<Ranking>() {
@Override
public int compare(Ranking o1, Ranking o2) {
Double fitness1 = o1.getFitness()[0];
Double fitness2 = o2.getFitness()[0];
int result = Double.compare(fitness1, fitness2);
if (result == 0) {
return o1.getDescription().compareTo(o2.getDescription());
}
return result;
}
});
}
@Override
public Context getContext() {
return this.context;
}
}
| gpl-3.0 |
sbesson/thunderstorm | src/main/java/cz/cuni/lf1/lge/ThunderSTORM/filters/CompoundWaveletFilter.java | 3345 | package cz.cuni.lf1.lge.ThunderSTORM.filters;
import cz.cuni.lf1.lge.ThunderSTORM.thresholding.Thresholder;
import static cz.cuni.lf1.lge.ThunderSTORM.util.ImageMath.subtract;
import static cz.cuni.lf1.lge.ThunderSTORM.util.ImageMath.crop;
import cz.cuni.lf1.lge.ThunderSTORM.util.Padding;
import ij.process.FloatProcessor;
import java.util.HashMap;
/**
* This wavelet filter is implemented as an undecimated wavelet transform using
* scaled B-spline of k-th order.
*
* This filter uses the separable kernel feature. Note that in the convolution
* with the wavelet kernels we use padding twice to simulate {@code conv2}
* function from Matlab to keep the results identical to the results we got in
* Matlab version of ThunderSTORM.
*
* @see WaveletFilter
* @see ConvolutionFilter
*/
public final class CompoundWaveletFilter implements IFilter {
private FloatProcessor input = null, result = null, result_F1 = null, result_F2 = null;
private HashMap<String, FloatProcessor> export_variables = null;
private int margin;
private int spline_order = 3, spline_n_samples = 5;
private double spline_scale = 2.0;
private WaveletFilter w1, w2;
public CompoundWaveletFilter() {
this(3, 2.0, 5); // these settings yield the identical kernel to the one proposed by Izeddin
}
/**
* Initialize the filter with all the wavelet kernels needed to create the
* wavelet transform.
*/
public CompoundWaveletFilter(int spline_order, double spline_scale, int spline_n_samples) {
w1 = new WaveletFilter(1, spline_order, spline_scale, spline_n_samples, Padding.PADDING_ZERO);
w2 = new WaveletFilter(2, spline_order, spline_scale, spline_n_samples, Padding.PADDING_ZERO);
//
this.margin = w2.getKernelX().getWidth() / 2;
this.spline_n_samples = spline_n_samples;
this.spline_order = spline_order;
this.spline_scale = spline_scale;
}
@Override
public FloatProcessor filterImage(FloatProcessor image) {
input = image;
FloatProcessor padded = Padding.addBorder(image, Padding.PADDING_DUPLICATE, margin);
FloatProcessor V1 = w1.filterImage(padded);
FloatProcessor V2 = w2.filterImage(V1);
result_F1 = subtract(input, crop(V1, margin, margin, image.getWidth(), image.getHeight()));
result_F2 = subtract(input, crop(V2, margin, margin, image.getWidth(), image.getHeight()));
result = crop(subtract(V1, V2), margin, margin, image.getWidth(), image.getHeight());
return result;
}
@Override
public String getFilterVarName() {
return "Wave";
}
@Override
public HashMap<String, FloatProcessor> exportVariables(boolean reevaluate) {
if(export_variables == null) {
export_variables = new HashMap<String, FloatProcessor>();
}
//
if(reevaluate) {
filterImage(Thresholder.getCurrentImage());
}
//
export_variables.put("I", input);
export_variables.put("F", result);
export_variables.put("F1", result_F1);
export_variables.put("F2", result_F2);
return export_variables;
}
@Override
public IFilter clone() {
return new CompoundWaveletFilter(spline_order, spline_scale, spline_n_samples);
}
}
| gpl-3.0 |
TecMunky/xDrip | app/src/main/java/com/eveningoutpost/dexdrip/utils/HeadsetStateReceiver.java | 6794 | package com.eveningoutpost.dexdrip.utils;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.eveningoutpost.dexdrip.Home;
import com.eveningoutpost.dexdrip.Models.JoH;
import com.eveningoutpost.dexdrip.Models.UserError;
import com.eveningoutpost.dexdrip.R;
import com.eveningoutpost.dexdrip.UtilityModels.Inevitable;
import com.eveningoutpost.dexdrip.UtilityModels.PersistentStore;
import com.eveningoutpost.dexdrip.UtilityModels.SpeechUtil;
import com.eveningoutpost.dexdrip.UtilityModels.VehicleMode;
import com.eveningoutpost.dexdrip.ui.activities.SelectAudioDevice;
import com.eveningoutpost.dexdrip.xdrip;
import static com.eveningoutpost.dexdrip.UtilityModels.SpeechUtil.TWICE_DELIMITER;
/**
* jamorham
*
* Track connection changes with bluetooth headsets
* Activate vehicle mode if we have been configured to do so
*/
public class HeadsetStateReceiver extends BroadcastReceiver {
private static final String TAG = "BluetoothHeadset";
private static final String PREF_LAST_CONNECTED_MAC = "bluetooth-last-audio-connected-mac";
private static final String PREF_LAST_CONNECTED_NAME = "bluetooth-last-audio-connected-name";
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device != null && device.getAddress() != null) {
final int state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, -1);
final int previousState = intent.getIntExtra(BluetoothHeadset.EXTRA_PREVIOUS_STATE, -1);
final String deviceInfo = device.getName() + "\n" + device.getAddress() + " " + (device.getBluetoothClass() != null ? device.getBluetoothClass() : "<unknown class>");
//UserError.Log.uel(TAG, "Bluetooth audio connection state change: " + state + " was " + previousState + " " + device.getAddress() + " " + device.getName());
if (state == BluetoothProfile.STATE_CONNECTED && previousState != BluetoothProfile.STATE_CONNECTED) {
PersistentStore.setString(PREF_LAST_CONNECTED_MAC, device.getAddress());
PersistentStore.setString(PREF_LAST_CONNECTED_NAME, device.getName());
UserError.Log.uel(TAG, "Bluetooth Audio connected: " + deviceInfo);
processDevice(device.getAddress(), true);
} else if (state == BluetoothProfile.STATE_DISCONNECTED && previousState == BluetoothProfile.STATE_CONNECTED) {
UserError.Log.uel(TAG, "Bluetooth Audio disconnected: " + deviceInfo);
processDevice(device.getAddress(), false);
}
} else {
UserError.Log.d(TAG, "Device was null in intent!");
}
} else if (BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED.equals(action)) {
// TODO this probably just for debugging could remove later
final int state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, -1);
UserError.Log.e(TAG, "audio state changed: " + state);
} else if (BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT.equals(action)) {
// TODO this will probably never fire due to manifest intent filter - check if there is any use for it
UserError.Log.e(TAG, "Vendor specific command event received");
}
}
private static final long NOISE_DELAY = 10000; // allow time for bt volume control
private static void processDevice(final String mac, final boolean connected) {
if (VehicleMode.isEnabled() && VehicleMode.viaCarAudio() && SelectAudioDevice.getAudioMac().equals(mac)) {
VehicleMode.setVehicleModeActive(connected);
UserError.Log.ueh(TAG, "Vehicle mode: " + (connected ? "Enabled" : "Disabled"));
if (connected) {
Inevitable.task("xdrip-vehicle-mode", NOISE_DELAY, HeadsetStateReceiver::audioNotification);
}
Home.staticRefreshBGChartsOnIdle();
}
}
private static void audioNotification() {
if (VehicleMode.isVehicleModeActive()) {
if (VehicleMode.shouldUseSpeech()) {
SpeechUtil.say(" X Drip " + TWICE_DELIMITER, 500);
} else if (VehicleMode.shouldPlaySound()) {
JoH.playResourceAudio(R.raw.labbed_musical_chime);
}
}
}
public static String getLastConnectedMac() {
return PersistentStore.getString(PREF_LAST_CONNECTED_MAC);
}
public static String getLastConnectedName() {
return PersistentStore.getString(PREF_LAST_CONNECTED_NAME);
}
public static void reprocessConnectionIfAlreadyConnected(final String mac) {
VehicleMode.setVehicleModeActive(false);
areWeConnectedToMac(mac, () -> processDevice(mac, true));
}
// if connected run the runnable, proxy service object may mean async running
private static void areWeConnectedToMac(final String mac, Runnable runnable) {
final int state = BluetoothAdapter.getDefaultAdapter().getProfileConnectionState(BluetoothProfile.HEADSET);
if (state != BluetoothProfile.STATE_CONNECTED) {
return;
}
final BluetoothProfile.ServiceListener serviceListener = new BluetoothProfile.ServiceListener() {
@Override
public void onServiceDisconnected(int profile) {
}
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
for (BluetoothDevice device : proxy.getConnectedDevices()) {
if (device.getAddress().equals(mac)) {
final boolean isConnected = proxy.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED;
UserError.Log.uel(TAG, "Found: " + device.getName() + " " + device.getAddress() + " " + (isConnected ? "Connected" : "Not connected"));
if (isConnected) {
if (runnable != null) runnable.run();
}
break;
}
}
BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy);
}
};
BluetoothAdapter.getDefaultAdapter().getProfileProxy(xdrip.getAppContext(), serviceListener, BluetoothProfile.HEADSET);
}
}
| gpl-3.0 |
dahlb/gcal-call-logger | src/com/dahl/brendan/calllog/PerferencesActivity.java | 4857 | // This file is part of GCal Call Logger.
//
// Open WordSearch is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Open WordSearch is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Open WordSearch. If not, see <http://www.gnu.org/licenses/>.
//
// Copyright 2010 Brendan Dahl <dahl.brendan@brendandahl.com>
// http://www.brendandahl.com
package com.dahl.brendan.calllog;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.admob.android.ads.AdManager;
import com.dahl.brendan.calllog.util.Logger;
public class PerferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
final static private String LOGTAG = PerferencesActivity.class.getSimpleName();
private CharSequence PREFS_CALENDAR_ID;
@Override
protected void onDestroy() {
super.onDestroy();
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AdManager.setTestDevices(new String[] { AdManager.TEST_EMULATOR });
View v = this.getLayoutInflater().inflate(R.layout.main, null, false);
v.findViewById(R.id.list).setId(android.R.id.list);
this.setContentView(v);
PREFS_CALENDAR_ID = this.getString(R.string.PREFS_CALENDAR_ID);
Log.v(LOGTAG,"init");
addPreferencesFromResource(R.xml.preferences);
setupCalendars(false);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
Log.v(LOGTAG,"added preferences listener");
}
private void setupCalendars(boolean log) {
List<CharSequence> labels = null;
List<CharSequence> values = null;
if (log) {
Log.v(LOGTAG,"setup_"+Constants.CALENDARS_URI.toString());
final Cursor cursor2 = getContentResolver().query(Constants.CALENDARS_URI, (new String[] {"_id", "displayName"}), null, null, null);
Log.v(LOGTAG, "all count:"+cursor2.getCount());
}
final Cursor cursor = getContentResolver().query(Constants.CALENDARS_URI, (new String[] {"_id", "displayName"}), "selected = 1 and access_level >= 500", null, null);
if (log) {
Log.v(LOGTAG, "usable count:"+cursor.getCount());
}
labels = new ArrayList<CharSequence>(cursor.getCount());
values = new ArrayList<CharSequence>(cursor.getCount());
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
if (log) {
Log.v(LOGTAG,"label:"+cursor.getString(1));
Log.v(LOGTAG,"value:"+String.valueOf(cursor.getLong(0)));
}
labels.add(cursor.getString(1));
values.add(String.valueOf(cursor.getLong(0)));
cursor.moveToNext();
}
if (log) {
Log.v(LOGTAG,"calendars list");
}
if (labels != null && values != null && labels.size() == values.size()) {
ListPreference p = (ListPreference)this.findPreference(PREFS_CALENDAR_ID);
p.setEntries(labels.toArray(new CharSequence[0]));
p.setEntryValues(values.toArray(new CharSequence[0]));
updateCalendar();
}
if (log) {
Log.v(LOGTAG,"updated calendar");
}
}
private void updateCalendar() {
ListPreference p = (ListPreference)this.findPreference(PREFS_CALENDAR_ID);
CharSequence calendar = p.getEntry();
if (calendar == null) {
p.setTitle(R.string.CALENDAR);
} else {
p.setTitle(calendar);
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (PREFS_CALENDAR_ID.equals(key)) {
updateCalendar();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.getMenuInflater().inflate(R.menu.options_preferences, menu);
menu.findItem(R.id.menu_log).setIcon(android.R.drawable.ic_menu_help);
menu.findItem(R.id.menu_quit).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_quit:
this.finish();
return true;
case R.id.menu_log:
setupCalendars(true);
Logger.collectAndSendLog(this, LOGTAG);
return true;
}
return super.onOptionsItemSelected(item);
}
} | gpl-3.0 |
kidaa/RealmSpeak | general/utility/general_swing/source/com/robin/general/swing/TableMap.java | 5001 | /*
* RealmSpeak is the Java application for playing the board game Magic Realm.
* Copyright (c) 2005-2015 Robin Warren
* E-mail: robin@dewkid.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
*
* http://www.gnu.org/licenses/
*/
package com.robin.general.swing;
/*
* @(#)TableMap.java 1.4 97/12/17
*
* Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, 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 Sun.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
* THIS SOFTWARE OR ITS DERIVATIVES.
*
*/
/**
* In a chain of data manipulators some behaviour is common. TableMap
* provides most of this behavour and can be subclassed by filters
* that only need to override a handful of specific methods. TableMap
* implements TableModel by routing all requests to its model, and
* TableModelListener by routing all events to its listeners. Inserting
* a TableMap which has not been subclassed into a chain of table filters
* should have no effect.
*
* @version 1.4 12/17/97
* @author Philip Milne */
import javax.swing.table.*;
import javax.swing.event.TableModelListener;
import javax.swing.event.TableModelEvent;
public class TableMap extends AbstractTableModel implements TableModelListener
{
protected TableModel model;
public TableModel getModel() {
return model;
}
public void setModel(TableModel model) {
this.model = model;
model.addTableModelListener(this);
}
// By default, Implement TableModel by forwarding all messages
// to the model.
public Object getValueAt(int aRow, int aColumn) {
return model.getValueAt(aRow, aColumn);
}
public void setValueAt(Object aValue, int aRow, int aColumn) {
model.setValueAt(aValue, aRow, aColumn);
}
public int getRowCount() {
return (model == null) ? 0 : model.getRowCount();
}
public int getColumnCount() {
return (model == null) ? 0 : model.getColumnCount();
}
public String getColumnName(int aColumn) {
return model.getColumnName(aColumn);
}
public Class getColumnClass(int aColumn) {
return model.getColumnClass(aColumn);
}
public boolean isCellEditable(int row, int column) {
return model.isCellEditable(row, column);
}
/**
* Returns the matrix of cell values at the coordinates specified by arrays of
* row and column indices. Note that while the returned matrix is contiguous,
* the rows and columns from which the values are taken do not have to be.<p>
*
* In general, if v is the returned matrix, <code>v[i][j]</code> = cell value at
* <code>(rows[i], cols[j])</code>.<p>
*
* @return Matrix of values from the specified cells.
* @param rows Array of row indices.
* @param cols Array of column indices.
*
* @exception ArrayIndexOutOfBoundsException
* If any of the array indices are out of bounds.
*
* @exception NullPointerException
* If either <code>rows</code> or <code>cols</code> is null.
*/
public Object[][] getValuesAt(int[] rows, int[] cols) {
Object[][] values = new Object[rows.length][cols.length];
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < cols.length; j++) {
values[i][j] = getValueAt(rows[i], cols[j]);
}
}
return values;
}
public void setValuesAt(Object[][] values, int[] rows, int[] cols) {
int vRows = values.length;
int vCols = values[0].length;
for (int i = 0; i < rows.length; i++) {
for (int j = 0; j < cols.length; j++) {
setValueAt(values[i%vRows][j%vCols],rows[i], cols[j]);
}
}
}
public boolean isCellValueValid(int row, int col) {
return true;
}
//
// Implementation of the TableModelListener interface,
//
// By default forward all events to all the listeners.
public void tableChanged(TableModelEvent e) {
fireTableChanged(e);
}
} | gpl-3.0 |
aria42/prototype-sequence-modeling | src/edu/berkeley/nlp/util/SubIndexer.java | 2518 | package edu.berkeley.nlp.util;
import java.util.*;
/**
* Maintains a two-way map between a set of (objects, substate) pairs and contiguous integers from 0
* to the number of objects. It also maintains a map from (object, substate) pairs
* to contiguous integers. Use get(i) to look up object i, and
* indexOf(object) to look up the index of an object.
* This class was modified to accomodate objects that can have several substates.
* It is assumed that if an object is added several times, it will be with the
* same number of substates.
*
* @author Dan Klein
* @author Romain Thibaux
*/
public class SubIndexer <E> extends AbstractList<E> {
List<E> objects;
// Index from 0 to objects.size()-1 of a given object:
Map<E, Integer> indexes;
// Sub-indexes (indexes of substates) of the object whose index is i are [ subindexes(i), subindexes(i+1) [
List<Integer> subindexes;
/**
* Return the object with the given index
*
* @param index
*/
public E get(int index) {
return objects.get(index);
}
/**
* Returns the number of objects indexed (not the total number of substates)
*/
public int size() {
return objects.size();
}
/**
* Returns the total number of substates
*/
public int totalSize() {
return subindexes.get(subindexes.size()-1);
}
/**
* Returns the index of the given object, or -1 if the object is not present
* in the indexer.
*
* @param o
* @return
*/
public int indexOf(Object o) {
Integer index = indexes.get(o);
if (index == null)
return -1;
return index;
}
public int subindexBegin(int index) {
return subindexes.get(index);
}
public int subindexEnd(int index) {
return subindexes.get(index+1);
}
/**
* Constant time override for contains.
*/
public boolean contains(Object o) {
return indexes.keySet().contains(o);
}
/**
* Add an element to the indexer. If the element is already in the indexer,
* the indexer is unchanged (and false is returned).
*
* @param e
* @return
*/
public boolean add(E e, int numSubstates) {
if (contains(e)) return false;
objects.add(e);
indexes.put(e, size() - 1);
Integer previousSubindex = subindexes.get(subindexes.size()-1);
subindexes.add(previousSubindex + numSubstates);
return true;
}
public SubIndexer() {
objects = new ArrayList<E>();
indexes = new HashMap<E, Integer>();
subindexes = new ArrayList<Integer>();
subindexes.add(0);
}
}
| gpl-3.0 |
srnsw/xena | xena/ext/src/xalan-j_2_7_1/src/org/apache/xalan/xsltc/compiler/ValueOf.java | 5699 | /*
* 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.
*/
/*
* $Id$
*/
package org.apache.xalan.xsltc.compiler;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.INVOKEINTERFACE;
import org.apache.bcel.generic.INVOKEVIRTUAL;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.PUSH;
import org.apache.xalan.xsltc.compiler.util.ClassGenerator;
import org.apache.xalan.xsltc.compiler.util.ErrorMsg;
import org.apache.xalan.xsltc.compiler.util.MethodGenerator;
import org.apache.xalan.xsltc.compiler.util.Type;
import org.apache.xalan.xsltc.compiler.util.TypeCheckError;
import org.apache.xalan.xsltc.compiler.util.Util;
/**
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
*/
final class ValueOf extends Instruction {
private Expression _select;
private boolean _escaping = true;
private boolean _isString = false;
public void display(int indent) {
indent(indent);
Util.println("ValueOf");
indent(indent + IndentIncrement);
Util.println("select " + _select.toString());
}
public void parseContents(Parser parser) {
_select = parser.parseExpression(this, "select", null);
// make sure required attribute(s) have been set
if (_select.isDummy()) {
reportError(this, parser, ErrorMsg.REQUIRED_ATTR_ERR, "select");
return;
}
final String str = getAttribute("disable-output-escaping");
if ((str != null) && (str.equals("yes"))) _escaping = false;
}
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
Type type = _select.typeCheck(stable);
// Prefer to handle the value as a node; fall back to String, otherwise
if (type != null && !type.identicalTo(Type.Node)) {
/***
*** %HZ% Would like to treat result-tree fragments in the same
*** %HZ% way as node sets for value-of, but that's running into
*** %HZ% some snags. Instead, they'll be converted to String
if (type.identicalTo(Type.ResultTree)) {
_select = new CastExpr(new CastExpr(_select, Type.NodeSet),
Type.Node);
} else
***/
if (type.identicalTo(Type.NodeSet)) {
_select = new CastExpr(_select, Type.Node);
} else {
_isString = true;
if (!type.identicalTo(Type.String)) {
_select = new CastExpr(_select, Type.String);
}
_isString = true;
}
}
return Type.Void;
}
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
final int setEscaping = cpg.addInterfaceMethodref(OUTPUT_HANDLER,
"setEscaping","(Z)Z");
// Turn off character escaping if so is wanted.
if (!_escaping) {
il.append(methodGen.loadHandler());
il.append(new PUSH(cpg,false));
il.append(new INVOKEINTERFACE(setEscaping,2));
}
// Translate the contents. If the value is a string, use the
// translet.characters(String, TranslatOutputHandler) method.
// Otherwise, the value is a node, and the
// dom.characters(int node, TransletOutputHandler) method can dispatch
// the string value of the node to the output handler more efficiently.
if (_isString) {
final int characters = cpg.addMethodref(TRANSLET_CLASS,
CHARACTERSW,
CHARACTERSW_SIG);
il.append(classGen.loadTranslet());
_select.translate(classGen, methodGen);
il.append(methodGen.loadHandler());
il.append(new INVOKEVIRTUAL(characters));
} else {
final int characters = cpg.addInterfaceMethodref(DOM_INTF,
CHARACTERS,
CHARACTERS_SIG);
il.append(methodGen.loadDOM());
_select.translate(classGen, methodGen);
il.append(methodGen.loadHandler());
il.append(new INVOKEINTERFACE(characters, 3));
}
// Restore character escaping setting to whatever it was.
if (!_escaping) {
il.append(methodGen.loadHandler());
il.append(SWAP);
il.append(new INVOKEINTERFACE(setEscaping,2));
il.append(POP);
}
}
}
| gpl-3.0 |
ceskaexpedice/kramerius | shared/common/src/test/java/cz/incad/kramerius/utils/handle/DisectHandleTest.java | 1027 | package cz.incad.kramerius.utils.handle;
import junit.framework.Assert;
import org.junit.Test;
public class DisectHandleTest {
@Test
public void testDisectHandle() {
String url="http://localhost:8080/search/handle/uuid:045b1250-7e47-11e0-add1-000d606f5dc6";
String handle = DisectHandle.disectHandle(url);
Assert.assertEquals("uuid:045b1250-7e47-11e0-add1-000d606f5dc6",handle);
}
@Test
public void testDisectHandleWithPage() {
String url="http://localhost:8080/search/handle/uuid:045b1250-7e47-11e0-add1-000d606f5dc6/@2";
String handle = DisectHandle.disectHandle(url);
Assert.assertEquals("uuid:045b1250-7e47-11e0-add1-000d606f5dc6/@2",handle);
}
@Test
public void testDisectHandleClient() {
String url="http://localhost:8080/client/handle/uuid:045b1250-7e47-11e0-add1-000d606f5dc6";
String handle = DisectHandle.disectHandle(url);
Assert.assertEquals("uuid:045b1250-7e47-11e0-add1-000d606f5dc6",handle);
}
}
| gpl-3.0 |
tempbottle/CJBE | src/org/gjt/jclasslib/structures/constants/ConstantDoubleInfo.java | 2153 | /*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the license, or (at your option) any later version.
*/
package org.gjt.jclasslib.structures.constants;
import org.gjt.jclasslib.structures.InvalidByteCodeException;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* Describes a <tt>CONSTANT_Double_info</tt> constant pool data structure.
*
* @author <a href="mailto:jclasslib@ej-technologies.com">Ingo Kegel</a>
* @version $Revision: 1.1 $ $Date: 2005/11/01 13:18:24 $
*/
public class ConstantDoubleInfo extends ConstantLargeNumeric {
public byte getTag() {
return CONSTANT_DOUBLE;
}
public String getTagVerbose() {
return CONSTANT_DOUBLE_VERBOSE;
}
public String getVerbose() throws InvalidByteCodeException {
return String.valueOf(getDouble());
}
/**
* Get the double value of this constant pool entry.
*
* @return the value
*/
public double getDouble() {
long longBits = (long) highBytes << 32 | (long) lowBytes & 0xFFFFFFFFL;
return Double.longBitsToDouble(longBits);
}
/**
* Set the double value of this constant pool entry.
*
* @param number the value
*/
public void setDouble(double number) {
long longBits = Double.doubleToLongBits(number);
highBytes = (int) (longBits >>> 32 & 0xFFFFFFFFL);
lowBytes = (int) (longBits & 0xFFFFFFFFL);
}
public void read(DataInput in)
throws InvalidByteCodeException, IOException {
super.read(in);
if (debug) debug("read ");
}
public void write(DataOutput out)
throws InvalidByteCodeException, IOException {
out.writeByte(CONSTANT_DOUBLE);
super.write(out);
if (debug) debug("wrote ");
}
protected void debug(String message) {
super.debug(message + getTagVerbose() + " with high_bytes " + highBytes +
" and low_bytes " + lowBytes);
}
}
| gpl-3.0 |
danielyc/test-1.9.4 | build/tmp/recompileMc/sources/net/minecraft/util/CombatTracker.java | 9558 | package net.minecraft.util;
import com.google.common.collect.Lists;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
public class CombatTracker
{
private final List<CombatEntry> combatEntries = Lists.<CombatEntry>newArrayList();
/** The entity tracked. */
private final EntityLivingBase fighter;
private int lastDamageTime;
private int combatStartTime;
private int combatEndTime;
private boolean inCombat;
private boolean takingDamage;
private String fallSuffix;
public CombatTracker(EntityLivingBase fighterIn)
{
this.fighter = fighterIn;
}
public void calculateFallSuffix()
{
this.resetFallSuffix();
if (this.fighter.isOnLadder())
{
Block block = this.fighter.worldObj.getBlockState(new BlockPos(this.fighter.posX, this.fighter.getEntityBoundingBox().minY, this.fighter.posZ)).getBlock();
if (block == Blocks.LADDER)
{
this.fallSuffix = "ladder";
}
else if (block == Blocks.VINE)
{
this.fallSuffix = "vines";
}
}
else if (this.fighter.isInWater())
{
this.fallSuffix = "water";
}
}
/**
* Adds an entry for the combat tracker
*/
public void trackDamage(DamageSource damageSrc, float healthIn, float damageAmount)
{
this.reset();
this.calculateFallSuffix();
CombatEntry combatentry = new CombatEntry(damageSrc, this.fighter.ticksExisted, healthIn, damageAmount, this.fallSuffix, this.fighter.fallDistance);
this.combatEntries.add(combatentry);
this.lastDamageTime = this.fighter.ticksExisted;
this.takingDamage = true;
if (combatentry.isLivingDamageSrc() && !this.inCombat && this.fighter.isEntityAlive())
{
this.inCombat = true;
this.combatStartTime = this.fighter.ticksExisted;
this.combatEndTime = this.combatStartTime;
this.fighter.sendEnterCombat();
}
}
public ITextComponent getDeathMessage()
{
if (this.combatEntries.isEmpty())
{
return new TextComponentTranslation("death.attack.generic", new Object[] {this.fighter.getDisplayName()});
}
else
{
CombatEntry combatentry = this.getBestCombatEntry();
CombatEntry combatentry1 = (CombatEntry)this.combatEntries.get(this.combatEntries.size() - 1);
ITextComponent itextcomponent1 = combatentry1.getDamageSrcDisplayName();
Entity entity = combatentry1.getDamageSrc().getEntity();
ITextComponent itextcomponent;
if (combatentry != null && combatentry1.getDamageSrc() == DamageSource.fall)
{
ITextComponent itextcomponent2 = combatentry.getDamageSrcDisplayName();
if (combatentry.getDamageSrc() != DamageSource.fall && combatentry.getDamageSrc() != DamageSource.outOfWorld)
{
if (itextcomponent2 != null && (itextcomponent1 == null || !itextcomponent2.equals(itextcomponent1)))
{
Entity entity1 = combatentry.getDamageSrc().getEntity();
ItemStack itemstack1 = entity1 instanceof EntityLivingBase ? ((EntityLivingBase)entity1).getHeldItemMainhand() : null;
if (itemstack1 != null && itemstack1.hasDisplayName())
{
itextcomponent = new TextComponentTranslation("death.fell.assist.item", new Object[] {this.fighter.getDisplayName(), itextcomponent2, itemstack1.getTextComponent()});
}
else
{
itextcomponent = new TextComponentTranslation("death.fell.assist", new Object[] {this.fighter.getDisplayName(), itextcomponent2});
}
}
else if (itextcomponent1 != null)
{
ItemStack itemstack = entity instanceof EntityLivingBase ? ((EntityLivingBase)entity).getHeldItemMainhand() : null;
if (itemstack != null && itemstack.hasDisplayName())
{
itextcomponent = new TextComponentTranslation("death.fell.finish.item", new Object[] {this.fighter.getDisplayName(), itextcomponent1, itemstack.getTextComponent()});
}
else
{
itextcomponent = new TextComponentTranslation("death.fell.finish", new Object[] {this.fighter.getDisplayName(), itextcomponent1});
}
}
else
{
itextcomponent = new TextComponentTranslation("death.fell.killer", new Object[] {this.fighter.getDisplayName()});
}
}
else
{
itextcomponent = new TextComponentTranslation("death.fell.accident." + this.getFallSuffix(combatentry), new Object[] {this.fighter.getDisplayName()});
}
}
else
{
itextcomponent = combatentry1.getDamageSrc().getDeathMessage(this.fighter);
}
return itextcomponent;
}
}
@Nullable
public EntityLivingBase getBestAttacker()
{
EntityLivingBase entitylivingbase = null;
EntityPlayer entityplayer = null;
float f = 0.0F;
float f1 = 0.0F;
for (CombatEntry combatentry : this.combatEntries)
{
if (combatentry.getDamageSrc().getEntity() instanceof EntityPlayer && (entityplayer == null || combatentry.getDamage() > f1))
{
f1 = combatentry.getDamage();
entityplayer = (EntityPlayer)combatentry.getDamageSrc().getEntity();
}
if (combatentry.getDamageSrc().getEntity() instanceof EntityLivingBase && (entitylivingbase == null || combatentry.getDamage() > f))
{
f = combatentry.getDamage();
entitylivingbase = (EntityLivingBase)combatentry.getDamageSrc().getEntity();
}
}
if (entityplayer != null && f1 >= f / 3.0F)
{
return entityplayer;
}
else
{
return entitylivingbase;
}
}
@Nullable
private CombatEntry getBestCombatEntry()
{
CombatEntry combatentry = null;
CombatEntry combatentry1 = null;
float f = 0.0F;
float f1 = 0.0F;
for (int i = 0; i < this.combatEntries.size(); ++i)
{
CombatEntry combatentry2 = (CombatEntry)this.combatEntries.get(i);
CombatEntry combatentry3 = i > 0 ? (CombatEntry)this.combatEntries.get(i - 1) : null;
if ((combatentry2.getDamageSrc() == DamageSource.fall || combatentry2.getDamageSrc() == DamageSource.outOfWorld) && combatentry2.getDamageAmount() > 0.0F && (combatentry == null || combatentry2.getDamageAmount() > f1))
{
if (i > 0)
{
combatentry = combatentry3;
}
else
{
combatentry = combatentry2;
}
f1 = combatentry2.getDamageAmount();
}
if (combatentry2.getFallSuffix() != null && (combatentry1 == null || combatentry2.getDamage() > f))
{
combatentry1 = combatentry2;
f = combatentry2.getDamage();
}
}
if (f1 > 5.0F && combatentry != null)
{
return combatentry;
}
else if (f > 5.0F && combatentry1 != null)
{
return combatentry1;
}
else
{
return null;
}
}
private String getFallSuffix(CombatEntry entry)
{
return entry.getFallSuffix() == null ? "generic" : entry.getFallSuffix();
}
public int getCombatDuration()
{
return this.inCombat ? this.fighter.ticksExisted - this.combatStartTime : this.combatEndTime - this.combatStartTime;
}
private void resetFallSuffix()
{
this.fallSuffix = null;
}
/**
* Resets this trackers list of combat entries
*/
public void reset()
{
int i = this.inCombat ? 300 : 100;
if (this.takingDamage && (!this.fighter.isEntityAlive() || this.fighter.ticksExisted - this.lastDamageTime > i))
{
boolean flag = this.inCombat;
this.takingDamage = false;
this.inCombat = false;
this.combatEndTime = this.fighter.ticksExisted;
if (flag)
{
this.fighter.sendEndCombat();
}
this.combatEntries.clear();
}
}
/**
* Returns EntityLivingBase assigned for this CombatTracker
*/
public EntityLivingBase getFighter()
{
return this.fighter;
}
} | gpl-3.0 |
GoodSign2017/mochadoom | src/s/DummySFX.java | 1108 | package s;
import data.sfxinfo_t;
public class DummySFX implements ISoundDriver {
@Override
public boolean InitSound() {
// Dummy is super-reliable ;-)
return true;
}
@Override
public void UpdateSound() {
// TODO Auto-generated method stub
}
@Override
public void SubmitSound() {
// TODO Auto-generated method stub
}
@Override
public void ShutdownSound() {
// TODO Auto-generated method stub
}
@Override
public int GetSfxLumpNum(sfxinfo_t sfxinfo) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int StartSound(int id, int vol, int sep, int pitch, int priority) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void StopSound(int handle) {
// TODO Auto-generated method stub
}
@Override
public boolean SoundIsPlaying(int handle) {
// TODO Auto-generated method stub
return false;
}
@Override
public void UpdateSoundParams(int handle, int vol, int sep, int pitch) {
// TODO Auto-generated method stub
}
@Override
public void SetChannels(int numChannels) {
// TODO Auto-generated method stub
}
}
| gpl-3.0 |
bserdar/lightblue-mongo | mongo/src/main/java/com/redhat/lightblue/mongo/config/MongoDBResolver.java | 4135 | /*
Copyright 2013 Red Hat, Inc. and/or its affiliates.
This file is part of lightblue.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.lightblue.mongo.config;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.DB;
import com.redhat.lightblue.config.DataSourceConfiguration;
import com.redhat.lightblue.config.DataSourcesConfiguration;
import com.redhat.lightblue.mongo.common.DBResolver;
import com.redhat.lightblue.mongo.common.MongoDataStore;
public class MongoDBResolver implements DBResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(MongoDBResolver.class);
private final Map<String, MongoConfiguration> datasources;
private final Map<String, DB> dbMap = new HashMap<>();
private final Map<String, DB> dsMap = new HashMap<>();
public MongoDBResolver(DataSourcesConfiguration ds) {
datasources = ds.getDataSourcesByType(MongoConfiguration.class);
}
@Override
public MongoConfiguration getConfiguration(MongoDataStore store) {
if (store.getDatasourceName() != null) {
return datasources.get(store.getDatasourceName());
} else if (store.getDatabaseName() != null) {
for (DataSourceConfiguration cfg : datasources.values()) {
if (((MongoConfiguration) cfg).getDatabase().equals(store.getDatabaseName())) {
return (MongoConfiguration) cfg;
}
}
}
return null;
}
@Override
public Collection<MongoConfiguration> getConfigurations() {
return Collections.unmodifiableCollection(datasources.values());
}
@Override
public DB get(MongoDataStore store) {
LOGGER.debug("Returning DB for {}", store);
DB db = null;
try {
if (store.getDatasourceName() != null) {
LOGGER.debug("datasource:{}", store.getDatasourceName());
db = dsMap.get(store.getDatasourceName());
if (db == null) {
MongoConfiguration cfg = getConfiguration(store);
if (cfg == null) {
throw new IllegalArgumentException("No datasources for " + store.getDatasourceName());
}
db = cfg.getDB();
dsMap.put(store.getDatasourceName(), db);
}
} else if (store.getDatabaseName() != null) {
LOGGER.debug("databaseName:{}", store.getDatabaseName());
db = dbMap.get(store.getDatabaseName());
if (db == null) {
MongoConfiguration cfg = getConfiguration(store);
if (cfg == null) {
throw new IllegalArgumentException("No datasources for " + store.getDatasourceName());
}
db = cfg.getDB();
dbMap.put(store.getDatabaseName(), db);
}
}
} catch (RuntimeException re) {
LOGGER.error("Cannot get {}:{}", store, re);
throw re;
} catch (Exception e) {
LOGGER.error("Cannot get {}:{}", store, e);
throw new IllegalArgumentException(e);
}
if (db == null) {
throw new IllegalArgumentException("Cannot find DB for " + store);
}
LOGGER.debug("Returning {} for {}", db, store);
return db;
}
}
| gpl-3.0 |
jentfoo/threadly_examples | src/main/java/org/threadly/examples/features/package-info.java | 115 | /**
* A collection of small examples using specific threadly features.
*/
package org.threadly.examples.features; | mpl-2.0 |
sensiasoft/sensorhub-core | sensorhub-core/src/main/java/org/sensorhub/impl/sensor/AbstractSensorOutput.java | 4214 | /***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved.
******************************* END LICENSE BLOCK ***************************/
package org.sensorhub.impl.sensor;
import java.util.List;
import net.opengis.swe.v20.DataBlock;
import org.sensorhub.api.common.IEventHandler;
import org.sensorhub.api.common.IEventListener;
import org.sensorhub.api.sensor.ISensorDataInterface;
import org.sensorhub.api.sensor.ISensorModule;
import org.sensorhub.api.sensor.SensorException;
import org.sensorhub.impl.common.EventBus;
import org.sensorhub.utils.MsgUtils;
/**
* <p>
* Class providing default implementation of common sensor data interface
* API methods. By default, storage is unsupported.
* </p>
*
* @author Alex Robin <alex.robin@sensiasoftware.com>
* @param <SensorType> Type of parent sensor
* @since Nov 2, 2014
*/
public abstract class AbstractSensorOutput<SensorType extends ISensorModule<?>> implements ISensorDataInterface
{
protected static String ERROR_NO_STORAGE = "Data storage is not supported by driver ";
protected SensorType parentSensor;
protected String name;
protected IEventHandler eventHandler;
protected DataBlock latestRecord;
protected long latestRecordTime = Long.MIN_VALUE;
public AbstractSensorOutput(SensorType parentSensor)
{
this(null, parentSensor);
}
public AbstractSensorOutput(String name, SensorType parentSensor)
{
this.name = name;
this.parentSensor = parentSensor;
// obtain an event handler for this output
String moduleID = parentSensor.getLocalID();
String topic = getName();
this.eventHandler = EventBus.getInstance().registerProducer(moduleID, topic);
}
protected abstract void init() throws SensorException;
protected void stop()
{
// do nothing by default
}
@Override
public SensorType getParentModule()
{
return parentSensor;
}
@Override
public String getName()
{
return name;
}
@Override
public boolean isEnabled()
{
return true;
}
@Override
public DataBlock getLatestRecord()
{
return latestRecord;
}
@Override
public long getLatestRecordTime()
{
return latestRecordTime;
}
@Override
public boolean isStorageSupported()
{
return false;
}
@Override
public int getStorageCapacity() throws SensorException
{
return 0;
}
@Override
public int getNumberOfAvailableRecords() throws SensorException
{
throw new SensorException(ERROR_NO_STORAGE + MsgUtils.moduleClassAndId(parentSensor));
}
@Override
public List<DataBlock> getLatestRecords(int maxRecords, boolean clear) throws SensorException
{
throw new SensorException(ERROR_NO_STORAGE + MsgUtils.moduleClassAndId(parentSensor));
}
@Override
public List<DataBlock> getAllRecords(boolean clear) throws SensorException
{
throw new SensorException(ERROR_NO_STORAGE + MsgUtils.moduleClassAndId(parentSensor));
}
@Override
public int clearAllRecords() throws SensorException
{
throw new SensorException(ERROR_NO_STORAGE + MsgUtils.moduleClassAndId(parentSensor));
}
@Override
public void registerListener(IEventListener listener)
{
eventHandler.registerListener(listener);
}
@Override
public void unregisterListener(IEventListener listener)
{
eventHandler.unregisterListener(listener);
}
}
| mpl-2.0 |
mkodekar/Fennece-Browser | tests/background/junit3/src/db/TestClientsDatabase.java | 6761 | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
package org.mozilla.gecko.background.db;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.mozilla.gecko.sync.Utils;
import org.mozilla.gecko.sync.repositories.NullCursorException;
import org.mozilla.gecko.sync.repositories.android.ClientsDatabase;
import org.mozilla.gecko.sync.repositories.android.RepoUtils;
import org.mozilla.gecko.sync.repositories.domain.ClientRecord;
import org.mozilla.gecko.sync.setup.Constants;
import android.database.Cursor;
import android.test.AndroidTestCase;
public class TestClientsDatabase extends AndroidTestCase {
protected ClientsDatabase db;
public void setUp() {
db = new ClientsDatabase(mContext);
db.wipeDB();
}
public void testStoreAndFetch() {
ClientRecord record = new ClientRecord();
String profileConst = Constants.DEFAULT_PROFILE;
db.store(profileConst, record);
Cursor cur = null;
try {
// Test stored item gets fetched correctly.
cur = db.fetchClientsCursor(record.guid, profileConst);
assertTrue(cur.moveToFirst());
assertEquals(1, cur.getCount());
String guid = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_ACCOUNT_GUID);
String profileId = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_PROFILE);
String clientName = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_NAME);
String clientType = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_TYPE);
assertEquals(record.guid, guid);
assertEquals(profileConst, profileId);
assertEquals(record.name, clientName);
assertEquals(record.type, clientType);
} catch (NullCursorException e) {
fail("Should not have NullCursorException");
} finally {
if (cur != null) {
cur.close();
}
}
}
public void testStoreAndFetchSpecificCommands() {
String accountGUID = Utils.generateGuid();
ArrayList<String> args = new ArrayList<String>();
args.add("URI of Page");
args.add("Sender GUID");
args.add("Title of Page");
String jsonArgs = JSONArray.toJSONString(args);
Cursor cur = null;
try {
db.store(accountGUID, "displayURI", jsonArgs);
// This row should not show up in the fetch.
args.add("Another arg.");
db.store(accountGUID, "displayURI", JSONArray.toJSONString(args));
// Test stored item gets fetched correctly.
cur = db.fetchSpecificCommand(accountGUID, "displayURI", jsonArgs);
assertTrue(cur.moveToFirst());
assertEquals(1, cur.getCount());
String guid = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_ACCOUNT_GUID);
String commandType = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_COMMAND);
String fetchedArgs = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_ARGS);
assertEquals(accountGUID, guid);
assertEquals("displayURI", commandType);
assertEquals(jsonArgs, fetchedArgs);
} catch (NullCursorException e) {
fail("Should not have NullCursorException");
} finally {
if (cur != null) {
cur.close();
}
}
}
public void testFetchCommandsForClient() {
String accountGUID = Utils.generateGuid();
ArrayList<String> args = new ArrayList<String>();
args.add("URI of Page");
args.add("Sender GUID");
args.add("Title of Page");
String jsonArgs = JSONArray.toJSONString(args);
Cursor cur = null;
try {
db.store(accountGUID, "displayURI", jsonArgs);
// This row should ALSO show up in the fetch.
args.add("Another arg.");
db.store(accountGUID, "displayURI", JSONArray.toJSONString(args));
// Test both stored items with the same GUID but different command are fetched.
cur = db.fetchCommandsForClient(accountGUID);
assertTrue(cur.moveToFirst());
assertEquals(2, cur.getCount());
} catch (NullCursorException e) {
fail("Should not have NullCursorException");
} finally {
if (cur != null) {
cur.close();
}
}
}
@SuppressWarnings("resource")
public void testDelete() {
ClientRecord record1 = new ClientRecord();
ClientRecord record2 = new ClientRecord();
String profileConst = Constants.DEFAULT_PROFILE;
db.store(profileConst, record1);
db.store(profileConst, record2);
Cursor cur = null;
try {
// Test record doesn't exist after delete.
db.deleteClient(record1.guid, profileConst);
cur = db.fetchClientsCursor(record1.guid, profileConst);
assertFalse(cur.moveToFirst());
assertEquals(0, cur.getCount());
// Test record2 still there after deleting record1.
cur = db.fetchClientsCursor(record2.guid, profileConst);
assertTrue(cur.moveToFirst());
assertEquals(1, cur.getCount());
String guid = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_ACCOUNT_GUID);
String profileId = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_PROFILE);
String clientName = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_NAME);
String clientType = RepoUtils.getStringFromCursor(cur, ClientsDatabase.COL_TYPE);
assertEquals(record2.guid, guid);
assertEquals(profileConst, profileId);
assertEquals(record2.name, clientName);
assertEquals(record2.type, clientType);
} catch (NullCursorException e) {
fail("Should not have NullCursorException");
} finally {
if (cur != null) {
cur.close();
}
}
}
@SuppressWarnings("resource")
public void testWipe() {
ClientRecord record1 = new ClientRecord();
ClientRecord record2 = new ClientRecord();
String profileConst = Constants.DEFAULT_PROFILE;
db.store(profileConst, record1);
db.store(profileConst, record2);
Cursor cur = null;
try {
// Test before wipe the records are there.
cur = db.fetchClientsCursor(record2.guid, profileConst);
assertTrue(cur.moveToFirst());
assertEquals(1, cur.getCount());
cur = db.fetchClientsCursor(record2.guid, profileConst);
assertTrue(cur.moveToFirst());
assertEquals(1, cur.getCount());
// Test after wipe neither record exists.
db.wipeClientsTable();
cur = db.fetchClientsCursor(record2.guid, profileConst);
assertFalse(cur.moveToFirst());
assertEquals(0, cur.getCount());
cur = db.fetchClientsCursor(record1.guid, profileConst);
assertFalse(cur.moveToFirst());
assertEquals(0, cur.getCount());
} catch (NullCursorException e) {
fail("Should not have NullCursorException");
} finally {
if (cur != null) {
cur.close();
}
}
}
}
| mpl-2.0 |
jerolba/torodb | engine/backend/postgresql/src/main/java/com/torodb/backend/postgresql/PostgreSqlReadInterface.java | 7845 | /*
* ToroDB
* Copyright © 2014 8Kdata Technology (www.8kdata.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.torodb.backend.postgresql;
import com.torodb.backend.AbstractReadInterface;
import com.torodb.backend.InternalField;
import com.torodb.backend.SqlHelper;
import com.torodb.backend.tables.MetaDocPartTable.DocPartTableFields;
import com.torodb.core.TableRef;
import com.torodb.core.TableRefFactory;
import com.torodb.core.transaction.metainf.MetaDatabase;
import com.torodb.core.transaction.metainf.MetaDocPart;
import org.jooq.Converter;
import org.jooq.lambda.tuple.Tuple2;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class PostgreSqlReadInterface extends AbstractReadInterface {
private final PostgreSqlMetaDataReadInterface metaDataReadInterface;
@Inject
public PostgreSqlReadInterface(PostgreSqlMetaDataReadInterface metaDataReadInterface,
PostgreSqlDataTypeProvider dataTypeProvider,
PostgreSqlErrorHandler errorhandler, SqlHelper sqlHelper, TableRefFactory tableRefFactory) {
super(metaDataReadInterface, dataTypeProvider, errorhandler, sqlHelper, tableRefFactory);
this.metaDataReadInterface = metaDataReadInterface;
}
@Override
protected String getReadCollectionDidsWithFieldEqualsToStatement(String schemaName,
String rootTableName,
String columnName) {
StringBuilder sb = new StringBuilder()
.append("SELECT \"")
.append(DocPartTableFields.DID.fieldName)
.append("\" FROM \"")
.append(schemaName)
.append("\".\"")
.append(rootTableName)
.append("\" WHERE \"")
.append(rootTableName)
.append("\".\"")
.append(columnName)
.append("\" = ? GROUP BY \"")
.append(DocPartTableFields.DID.fieldName)
.append("\" ORDER BY \"")
.append(DocPartTableFields.DID.fieldName)
.append('"');
String statement = sb.toString();
return statement;
}
@Override
protected String getReadCollectionDidsWithFieldInStatement(
String schemaName, String rootTableName, Stream<Tuple2<String, Integer>> valuesCountList) {
StringBuilder sb = new StringBuilder()
.append("SELECT \"")
.append(DocPartTableFields.DID.fieldName)
.append("\" FROM \"")
.append(schemaName)
.append("\".\"")
.append(rootTableName)
.append("\" WHERE \"");
Iterator<Tuple2<String, Integer>> valuesCountMapEntryIterator =
valuesCountList.iterator();
while (valuesCountMapEntryIterator.hasNext()) {
Tuple2<String, Integer> valuesCountMapEntry =
valuesCountMapEntryIterator.next();
String columnName = valuesCountMapEntry.v1;
Integer valuesCount = valuesCountMapEntry.v2;
sb
.append(rootTableName)
.append("\".\"")
.append(columnName)
.append("\" IN (");
for (int index = 0; index < valuesCount; index++) {
sb.append("?,");
}
sb.setCharAt(sb.length() - 1, ')');
}
sb.append(" ORDER BY \"")
.append(DocPartTableFields.DID.fieldName)
.append('"');
String statement = sb.toString();
return statement;
}
@Override
protected String getReadCollectionDidsAndProjectionWithFieldInStatement(String schemaName,
String rootTableName,
String columnName, int valuesCount) {
StringBuilder sb = new StringBuilder()
.append("SELECT \"")
.append(DocPartTableFields.DID.fieldName)
.append("\",\"")
.append(columnName)
.append("\" FROM \"")
.append(schemaName)
.append("\".\"")
.append(rootTableName)
.append("\" WHERE \"")
.append(columnName)
.append("\" IN (");
for (int index = 0; index < valuesCount; index++) {
sb.append("?,");
}
sb.setCharAt(sb.length() - 1, ')');
String statement = sb.toString();
return statement;
}
@Override
protected String getReadAllCollectionDidsStatement(String schemaName, String rootTableName) {
StringBuilder sb = new StringBuilder()
.append("SELECT \"")
.append(DocPartTableFields.DID.fieldName)
.append("\" FROM \"")
.append(schemaName)
.append("\".\"")
.append(rootTableName)
.append('"');
String statement = sb.toString();
return statement;
}
@Override
protected String getReadCountAllStatement(String schemaName, String rootTableName) {
StringBuilder sb = new StringBuilder()
.append("SELECT COUNT(1) FROM \"")
.append(schemaName)
.append("\".\"")
.append(rootTableName)
.append('"');
String statement = sb.toString();
return statement;
}
@Override
protected String getDocPartStatament(MetaDatabase metaDatabase, MetaDocPart metaDocPart,
Collection<Integer> dids) {
StringBuilder sb = new StringBuilder()
.append("SELECT ");
Collection<InternalField<?>> internalFields = metaDataReadInterface.getInternalFields(
metaDocPart);
for (InternalField<?> internalField : internalFields) {
sb.append('"')
.append(internalField.getName())
.append("\",");
}
metaDocPart.streamScalars().forEach(metaScalar -> {
sb.append('"')
.append(metaScalar.getIdentifier())
.append("\",");
});
metaDocPart.streamFields().forEach(metaField -> {
sb.append('"')
.append(metaField.getIdentifier())
.append("\",");
});
sb.setCharAt(sb.length() - 1, ' ');
sb
.append("FROM \"")
.append(metaDatabase.getIdentifier())
.append("\".\"")
.append(metaDocPart.getIdentifier())
.append("\" WHERE \"")
.append(metaDataReadInterface.getMetaDocPartTable().DID.getName())
.append("\" IN (");
Converter<?, Integer> converter =
metaDataReadInterface.getMetaDocPartTable().DID.getDataType().getConverter();
for (Integer requestedDoc : dids) {
sb.append(converter.to(requestedDoc))
.append(',');
}
sb.setCharAt(sb.length() - 1, ')');
if (!metaDocPart.getTableRef().isRoot()) {
sb.append(" ORDER BY ");
Collection<InternalField<?>> internalFieldsIt =
metaDataReadInterface.getReadInternalFields(metaDocPart);
for (InternalField<?> internalField : internalFieldsIt) {
sb
.append('"')
.append(internalField.getName())
.append("\",");
}
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
@Override
protected String getLastRowIdUsedStatement(MetaDatabase metaDatabase, MetaDocPart metaDocPart) {
TableRef tableRef = metaDocPart.getTableRef();
StringBuilder sb = new StringBuilder();
sb.append("SELECT max(\"")
.append(getPrimaryKeyColumnIdentifier(tableRef))
.append("\") FROM \"")
.append(metaDatabase.getIdentifier())
.append("\".\"")
.append(metaDocPart.getIdentifier())
.append("\"");
String statement = sb.toString();
return statement;
}
}
| agpl-3.0 |
pbouillet/inspectIT | CommonsCS/test/info/novatec/inspectit/storage/nio/ByteBufferProviderTest.java | 6214 | package info.novatec.inspectit.storage.nio;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import info.novatec.inspectit.storage.nio.bytebuffer.ByteBufferFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import nl.jqno.equalsverifier.util.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Tests the {@link ByteBufferProvider}.
*
* @author Ivan Senic
*
*/
@SuppressWarnings("PMD")
public class ByteBufferProviderTest {
/**
* To be tested.
*/
private ByteBufferProvider byteBufferProvider;
/**
* Creates new instance before each test.
*/
@BeforeMethod
public void init() {
byteBufferProvider = new ByteBufferProvider(new ByteBufferFactory(1), 1);
byteBufferProvider.setBufferPoolMaxDirectMemoryOccupancy(0.6f);
byteBufferProvider.setBufferPoolMinDirectMemoryOccupancy(0.3f);
}
/**
* Test that the created capacity of the buffer will be as wanted.
*/
@Test(invocationCount = 5)
public void capacity() throws IOException {
int maxCapacity = 1000;
Random random = new Random();
// at least 1
int wantedCapacity = 1 + random.nextInt(maxCapacity);
byteBufferProvider.setBufferSize(wantedCapacity);
byteBufferProvider.setPoolMaxCapacity(maxCapacity);
byteBufferProvider.init();
ByteBuffer buffer = byteBufferProvider.acquireByteBuffer();
assertThat(buffer, is(notNullValue()));
assertThat(buffer.capacity(), is(equalTo(wantedCapacity)));
}
/**
* Tests that no buffer will be created after max pool capacity has been reached.
*/
@Test
public void creationUntilMax() throws IOException {
int maxCapacity = 3;
byteBufferProvider.setBufferSize(1);
byteBufferProvider.setPoolMaxCapacity(maxCapacity);
byteBufferProvider.init();
for (int i = 0; i < maxCapacity; i++) {
ByteBuffer buffer = byteBufferProvider.acquireByteBuffer();
assertThat(buffer, is(notNullValue()));
}
assertThat(byteBufferProvider.getBufferPoolSize(), is(equalTo(0)));
}
/**
* Tests that a buffer will not be returned to the queue after a release when the available
* capacity is above or equal to min capacity.
*/
@Test
public void relaseAfterMin() throws IOException {
byteBufferProvider.setBufferSize(1);
byteBufferProvider.setPoolMaxCapacity(3);
byteBufferProvider.setPoolMinCapacity(1);
byteBufferProvider.init();
ByteBuffer buffer1 = byteBufferProvider.acquireByteBuffer();
ByteBuffer buffer2 = byteBufferProvider.acquireByteBuffer();
assertThat(byteBufferProvider.getCreatedCapacity(), is(equalTo(2L)));
assertThat(byteBufferProvider.getAvailableCapacity(), is(equalTo(0L)));
byteBufferProvider.releaseByteBuffer(buffer1);
byteBufferProvider.releaseByteBuffer(buffer2);
assertThat(byteBufferProvider.getCreatedCapacity(), is(equalTo(1L)));
assertThat(byteBufferProvider.getAvailableCapacity(), is(equalTo(1L)));
assertThat(byteBufferProvider.getBufferPoolSize(), is(equalTo(1)));
}
/**
* Tests that acquire and release of the buffer will have the correct side effects.
*/
@Test
public void acquireAndRelease() throws IOException {
byteBufferProvider.setBufferSize(1);
byteBufferProvider.setPoolMaxCapacity(2);
byteBufferProvider.setPoolMinCapacity(1);
byteBufferProvider.init();
assertThat(byteBufferProvider.getCreatedCapacity(), is(equalTo(0L)));
assertThat(byteBufferProvider.getAvailableCapacity(), is(equalTo(0L)));
ByteBuffer buffer = byteBufferProvider.acquireByteBuffer();
assertThat(buffer, is(notNullValue()));
assertThat(byteBufferProvider.getBufferPoolSize(), is(equalTo(0)));
assertThat(byteBufferProvider.getCreatedCapacity(), is(equalTo(1L)));
assertThat(byteBufferProvider.getAvailableCapacity(), is(equalTo(0L)));
byteBufferProvider.releaseByteBuffer(buffer);
assertThat(byteBufferProvider.getBufferPoolSize(), is(equalTo(1)));
assertThat(byteBufferProvider.getCreatedCapacity(), is(equalTo(1L)));
assertThat(byteBufferProvider.getAvailableCapacity(), is(equalTo(1L)));
}
/**
* Test that IOException will be thrown when there is no buffer available any more.
*/
@Test(expectedExceptions = IOException.class)
public void bufferNotAvailable() throws IOException {
byteBufferProvider.setBufferSize(1);
byteBufferProvider.setPoolMaxCapacity(1);
byteBufferProvider.setPoolMinCapacity(0);
byteBufferProvider.init();
// first acquire to work
ByteBuffer buffer = byteBufferProvider.acquireByteBuffer();
assertThat(buffer, is(notNullValue()));
// second to fail
buffer = byteBufferProvider.acquireByteBuffer();
}
/**
* Stress the provider with several thread proving that the byte buffer provider won't block
* under heavy load.
*/
@Test
public void providerStressed() throws Throwable {
byteBufferProvider.setBufferSize(1);
byteBufferProvider.setPoolMaxCapacity(3);
byteBufferProvider.setPoolMinCapacity(1);
byteBufferProvider.init();
int threadCount = 5;
final int iterationsPerThread = 100000;
final AtomicInteger totalCount = new AtomicInteger(threadCount * iterationsPerThread);
for (int i = 0; i < threadCount; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < iterationsPerThread; i++) {
try {
ByteBuffer buffer = byteBufferProvider.acquireByteBuffer();
assertThat(buffer, is(notNullValue()));
byteBufferProvider.releaseByteBuffer(buffer);
totalCount.decrementAndGet();
} catch (IOException ioException) {
// if IOException occurs we will repeat the try
i--;
}
}
}
}).start();
}
int sleepTime = 500;
int totalSlept = 0;
int maxSleepTime = 2 * 60 * 1000;
while (totalCount.get() > 0) {
try {
Thread.sleep(sleepTime);
totalSlept += sleepTime;
if (totalSlept > maxSleepTime) {
Assert.fail("Waiting for the byte buffer stressed test is over " + maxSleepTime + " milliseconds. Test is failed.");
}
} catch (InterruptedException e) {
Thread.interrupted();
}
}
}
}
| agpl-3.0 |
inspectIT/inspectIT | inspectit.shared.cs/src/main/java/rocks/inspectit/shared/cs/indexing/indexer/impl/SqlStringIndexer.java | 2420 | package rocks.inspectit.shared.cs.indexing.indexer.impl;
import rocks.inspectit.shared.all.communication.DefaultData;
import rocks.inspectit.shared.all.communication.data.SqlStatementData;
import rocks.inspectit.shared.all.indexing.IIndexQuery;
import rocks.inspectit.shared.cs.indexing.indexer.AbstractSharedInstanceBranchIndexer;
import rocks.inspectit.shared.cs.indexing.indexer.IBranchIndexer;
import rocks.inspectit.shared.cs.indexing.storage.impl.StorageIndexQuery;
/**
* Indexer that indexes SQLs based on the query string. All other objects types are indexed with
* same key.
*
* @author Ivan Senic
*
* @param <E>
*/
public class SqlStringIndexer<E extends DefaultData> extends AbstractSharedInstanceBranchIndexer<E> implements IBranchIndexer<E> {
/**
* Maximum amount of branches/leaf that can be created by this indexer. Negative values means no
* limit.
*/
private final int maxKeys;
/**
* Default constructor. Adds no limit on the maximum amount of keys created.
*/
public SqlStringIndexer() {
this(-1);
}
/**
* Additional constructor. Sets the amount of maximum keys that will be created. If unlimited
* keys should be used, construct object with no-arg constructor or pass the non-positive
* number.
*
* @param maxKeys
* Max keys that can be created by this indexer.
*/
public SqlStringIndexer(int maxKeys) {
this.maxKeys = maxKeys;
}
/**
* {@inheritDoc}
*/
@Override
public Object getKey(E element) {
if (element instanceof SqlStatementData) {
SqlStatementData sqlStatementData = (SqlStatementData) element;
if (null != sqlStatementData.getSql()) {
return getInternalHash(sqlStatementData.getSql().hashCode());
}
}
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public Object[] getKeys(IIndexQuery query) {
if (query instanceof StorageIndexQuery) {
if (null != ((StorageIndexQuery) query).getSql()) {
Object[] keys = new Object[1];
keys[0] = getInternalHash(((StorageIndexQuery) query).getSql().hashCode());
return keys;
}
}
return new Object[0];
}
/**
* Internal hash function depending on the {@link #maxKeys}.
*
* @param hashCode
* Hash code to transform.
* @return Key that can be used.
*/
private Integer getInternalHash(int hashCode) {
if (maxKeys > 0) {
return Integer.valueOf(Math.abs(hashCode % maxKeys));
} else {
return hashCode;
}
}
}
| agpl-3.0 |
inspectIT/inspectIT | inspectit.agent.java/src/main/java/rocks/inspectit/agent/java/sensor/method/remote/server/mq/JmsListenerRemoteServerSensor.java | 2191 | package rocks.inspectit.agent.java.sensor.method.remote.server.mq;
import io.opentracing.propagation.TextMap;
import rocks.inspectit.agent.java.config.impl.RegisteredSensorConfig;
import rocks.inspectit.agent.java.sensor.method.remote.server.RemoteServerSensor;
import rocks.inspectit.agent.java.tracing.core.adapter.ResponseAdapter;
import rocks.inspectit.agent.java.tracing.core.adapter.ServerAdapterProvider;
import rocks.inspectit.agent.java.tracing.core.adapter.ServerRequestAdapter;
import rocks.inspectit.agent.java.tracing.core.adapter.empty.EmptyResponseAdapter;
import rocks.inspectit.agent.java.tracing.core.adapter.error.ThrowableAwareResponseAdapter;
import rocks.inspectit.agent.java.tracing.core.adapter.mq.MQRequestAdapter;
import rocks.inspectit.agent.java.tracing.core.adapter.mq.data.impl.JmsMessage;
/**
* Remote server sensor for intercepting JMS message receiving. This sensor is intended to work with
* JMS listener, but in theory can be placed on any method where JMS message is first parameter.
* <p>
* Targeted instrumentation method:
* <ul>
* <li>{@code javax.jms.MessageListener#onMessage(javax.jms.Message)}
* <li>{@code javax.jms.MessageListener#onMessage(javax.jms.Message, javax.jms.Session)}
* </ul>
*
* @author Ivan Senic
*/
public class JmsListenerRemoteServerSensor extends RemoteServerSensor implements ServerAdapterProvider {
/**
* {@inheritDoc}
*/
@Override
protected ServerAdapterProvider getServerAdapterProvider() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ServerRequestAdapter<TextMap> getServerRequestAdapter(Object object, Object[] parameters, RegisteredSensorConfig rsc) {
// message is first parameter
Object message = parameters[0];
JmsMessage jmsMessage = new JmsMessage(message, CACHE);
return new MQRequestAdapter(jmsMessage, true);
}
/**
* {@inheritDoc}
*/
@Override
public ResponseAdapter getServerResponseAdapter(Object object, Object[] parameters, Object result, boolean exception, RegisteredSensorConfig rsc) {
if (exception) {
return new ThrowableAwareResponseAdapter(result.getClass().getSimpleName());
} else {
return EmptyResponseAdapter.INSTANCE;
}
}
}
| agpl-3.0 |
inspectIT/inspectIT | inspectit.server/src/test/java/rocks/inspectit/server/processor/impl/BusinessContextRecognitionProcessorTest.java | 18941 | package rocks.inspectit.server.processor.impl;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import javax.persistence.EntityManager;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import rocks.inspectit.server.ci.event.BusinessContextDefinitionUpdateEvent;
import rocks.inspectit.server.dao.impl.BufferInvocationDataDaoImpl;
import rocks.inspectit.server.service.BusinessContextManagementService;
import rocks.inspectit.server.service.ConfigurationInterfaceService;
import rocks.inspectit.shared.all.communication.data.InvocationSequenceData;
import rocks.inspectit.shared.all.communication.data.TimerData;
import rocks.inspectit.shared.all.communication.data.cmr.ApplicationData;
import rocks.inspectit.shared.all.communication.data.cmr.BusinessTransactionData;
import rocks.inspectit.shared.all.exception.BusinessException;
import rocks.inspectit.shared.all.testbase.TestBase;
import rocks.inspectit.shared.cs.ci.business.expression.impl.StringMatchingExpression;
import rocks.inspectit.shared.cs.ci.business.impl.ApplicationDefinition;
import rocks.inspectit.shared.cs.ci.business.impl.BusinessTransactionDefinition;
import rocks.inspectit.shared.cs.ci.business.valuesource.PatternMatchingType;
import rocks.inspectit.shared.cs.ci.business.valuesource.StringValueSource;
import rocks.inspectit.shared.cs.cmr.service.cache.CachedDataService;
/**
* @author Alexander Wert
*
*/
@SuppressWarnings("PMD")
public class BusinessContextRecognitionProcessorTest extends TestBase {
@InjectMocks
BusinessContextRecognitionProcessor processor;
/**
* Tests
* {@link BusinessContextRecognitionProcessor#assignBusinessContext(InvocationSequenceData)}
* method.
*
*/
public static class Process extends BusinessContextRecognitionProcessorTest {
private static AtomicInteger idGenerator = new AtomicInteger(100);
@Mock
CachedDataService cachedDataService;
@Mock
BusinessContextManagementService businessContextManagementService;
@Mock
BufferInvocationDataDaoImpl invocationDataDao;
@Mock
ConfigurationInterfaceService ciService;
@Mock
EntityManager entityManager;
InvocationSequenceData root;
InvocationSequenceData level_1_1;
InvocationSequenceData level_1_2;
InvocationSequenceData level_2_1;
ApplicationDefinition applicationDefinition;
ApplicationDefinition applicationDefinition_empty;
BusinessTransactionDefinition businessTxDefinition_1;
BusinessTransactionDefinition businessTxDefinition_2;
StringValueSource stringValueSource;
ApplicationData application;
ApplicationData application_unknown;
ApplicationData application_empty;
BusinessTransactionData businessTx_1;
BusinessTransactionData businessTx_2;
BusinessTransactionData businessTx_unknown;
@BeforeMethod
public void init() throws BusinessException {
root = new InvocationSequenceData();
root.setId(1);
level_1_1 = new InvocationSequenceData();
level_1_1.setId(2);
level_1_2 = new InvocationSequenceData();
level_1_2.setId(3);
level_2_1 = new InvocationSequenceData();
level_2_1.setId(4);
root.getNestedSequences().add(level_1_1);
root.getNestedSequences().add(level_1_2);
level_1_2.getNestedSequences().add(level_2_1);
when(cachedDataService.getApplicationForId(anyInt())).thenReturn(null);
when(cachedDataService.getBusinessTransactionForId(anyInt(), anyInt())).thenReturn(null);
applicationDefinition = new ApplicationDefinition(idGenerator.getAndIncrement(), "SomeApplication", null);
application = new ApplicationData(idGenerator.getAndIncrement(), applicationDefinition.getId(), applicationDefinition.getApplicationName());
applicationDefinition_empty = new ApplicationDefinition(idGenerator.getAndIncrement(), "EmptyApplication", null);
application_empty = new ApplicationData(idGenerator.getAndIncrement(), applicationDefinition_empty.getId(), applicationDefinition_empty.getApplicationName());
application_unknown = new ApplicationData(idGenerator.getAndIncrement(), ApplicationDefinition.DEFAULT_ID, "Unknown Application");
businessTxDefinition_1 = new BusinessTransactionDefinition(idGenerator.getAndIncrement(), "businessTxDefinition_1", null);
businessTx_1 = new BusinessTransactionData(idGenerator.getAndIncrement(), businessTxDefinition_1.getId(), application, businessTxDefinition_1.getBusinessTransactionDefinitionName());
businessTxDefinition_2 = new BusinessTransactionDefinition(idGenerator.getAndIncrement(), "businessTxDefinition_2", null);
businessTx_2 = new BusinessTransactionData(idGenerator.getAndIncrement(), businessTxDefinition_2.getId(), application, businessTxDefinition_2.getBusinessTransactionDefinitionName());
businessTx_unknown = new BusinessTransactionData(idGenerator.getAndIncrement(), BusinessTransactionDefinition.DEFAULT_ID, application, "Unknown Transaction");
applicationDefinition.addBusinessTransactionDefinition(businessTxDefinition_1);
applicationDefinition.addBusinessTransactionDefinition(businessTxDefinition_2);
List<ApplicationDefinition> applicationDefinitions = new ArrayList<>();
applicationDefinitions.add(applicationDefinition);
applicationDefinitions.add(applicationDefinition_empty);
when(ciService.getApplicationDefinitions()).thenReturn(applicationDefinitions);
stringValueSource = mock(StringValueSource.class);
when(stringValueSource.getStringValues(root, cachedDataService)).thenReturn(new String[] { "node/root/" });
when(stringValueSource.getStringValues(level_1_1, cachedDataService)).thenReturn(new String[] { "node/level_1_1/" });
when(stringValueSource.getStringValues(level_1_2, cachedDataService)).thenReturn(new String[] { "node/level_1_2/" });
when(stringValueSource.getStringValues(level_2_1, cachedDataService)).thenReturn(new String[] { "node/level_2_1/", "node/level_2_1/multiple" });
when(businessContextManagementService.registerApplication(applicationDefinition)).thenReturn(application);
when(businessContextManagementService.registerApplication(ApplicationDefinition.DEFAULT_APPLICATION_DEFINITION)).thenReturn(application_unknown);
when(businessContextManagementService.registerBusinessTransaction(application, businessTxDefinition_1, businessTxDefinition_1.getBusinessTransactionDefinitionName()))
.thenReturn(businessTx_1);
when(businessContextManagementService.registerBusinessTransaction(application, businessTxDefinition_2, businessTxDefinition_2.getBusinessTransactionDefinitionName()))
.thenReturn(businessTx_2);
when(businessContextManagementService.registerBusinessTransaction(application, applicationDefinition.getBusinessTransactionDefinition(0),
applicationDefinition.getBusinessTransactionDefinition(0).getBusinessTransactionDefinitionName())).thenReturn(businessTx_unknown);
when(businessContextManagementService.registerBusinessTransaction(application_unknown, ApplicationDefinition.DEFAULT_APPLICATION_DEFINITION.getBusinessTransactionDefinition(0),
ApplicationDefinition.DEFAULT_APPLICATION_DEFINITION.getBusinessTransactionDefinition(0).getBusinessTransactionDefinitionName())).thenReturn(businessTx_unknown);
when(businessContextManagementService.registerApplication(applicationDefinition_empty)).thenReturn(application_empty);
when(businessContextManagementService.registerBusinessTransaction(application_empty, applicationDefinition_empty.getBusinessTransactionDefinition(0),
applicationDefinition_empty.getBusinessTransactionDefinition(0).getBusinessTransactionDefinitionName())).thenReturn(businessTx_unknown);
}
@Test
public void match() {
StringMatchingExpression stringMatchingExpression = new StringMatchingExpression(PatternMatchingType.CONTAINS, "root");
stringMatchingExpression.setStringValueSource(stringValueSource);
stringMatchingExpression.setSearchNodeInTrace(false);
StringMatchingExpression stringMatchingExpression_2 = new StringMatchingExpression(PatternMatchingType.CONTAINS, "nothing");
stringMatchingExpression_2.setStringValueSource(stringValueSource);
stringMatchingExpression_2.setSearchNodeInTrace(false);
applicationDefinition.setMatchingRuleExpression(stringMatchingExpression);
applicationDefinition_empty.setMatchingRuleExpression(stringMatchingExpression_2);
businessTxDefinition_1.setMatchingRuleExpression(stringMatchingExpression_2);
businessTxDefinition_2.setMatchingRuleExpression(stringMatchingExpression);
processor.process(root, entityManager);
assertThat(root.getApplicationId(), equalTo(application.getId()));
assertThat(root.getBusinessTransactionId(), equalTo(businessTx_2.getId()));
}
@Test
public void matchWithSearchInTrace() {
StringMatchingExpression stringMatchingExpression = new StringMatchingExpression(PatternMatchingType.CONTAINS, "multiple");
stringMatchingExpression.setStringValueSource(stringValueSource);
stringMatchingExpression.setSearchNodeInTrace(true);
stringMatchingExpression.setMaxSearchDepth(2);
StringMatchingExpression stringMatchingExpression_2 = new StringMatchingExpression(PatternMatchingType.CONTAINS, "nothing");
stringMatchingExpression_2.setStringValueSource(stringValueSource);
stringMatchingExpression_2.setSearchNodeInTrace(false);
applicationDefinition.setMatchingRuleExpression(stringMatchingExpression);
applicationDefinition_empty.setMatchingRuleExpression(stringMatchingExpression_2);
businessTxDefinition_1.setMatchingRuleExpression(stringMatchingExpression_2);
businessTxDefinition_2.setMatchingRuleExpression(stringMatchingExpression);
processor.process(root, entityManager);
assertThat(root.getApplicationId(), equalTo(application.getId()));
assertThat(root.getBusinessTransactionId(), equalTo(businessTx_2.getId()));
}
@Test
public void matchDefaultBT() {
StringMatchingExpression stringMatchingExpression = new StringMatchingExpression(PatternMatchingType.CONTAINS, "root");
stringMatchingExpression.setStringValueSource(stringValueSource);
stringMatchingExpression.setSearchNodeInTrace(false);
StringMatchingExpression stringMatchingExpression_2 = new StringMatchingExpression(PatternMatchingType.CONTAINS, "nothing");
stringMatchingExpression_2.setStringValueSource(stringValueSource);
stringMatchingExpression_2.setSearchNodeInTrace(false);
applicationDefinition.setMatchingRuleExpression(stringMatchingExpression);
applicationDefinition_empty.setMatchingRuleExpression(stringMatchingExpression_2);
businessTxDefinition_1.setMatchingRuleExpression(stringMatchingExpression_2);
businessTxDefinition_2.setMatchingRuleExpression(stringMatchingExpression_2);
processor.process(root, entityManager);
assertThat(root.getApplicationId(), equalTo(application.getId()));
assertThat(root.getBusinessTransactionId(), equalTo(businessTx_unknown.getId()));
}
@Test
public void matchDefaultAppAndBT() {
StringMatchingExpression stringMatchingExpression = new StringMatchingExpression(PatternMatchingType.CONTAINS, "nothing");
stringMatchingExpression.setStringValueSource(stringValueSource);
stringMatchingExpression.setSearchNodeInTrace(false);
StringMatchingExpression stringMatchingExpression_2 = new StringMatchingExpression(PatternMatchingType.CONTAINS, "nothing");
stringMatchingExpression_2.setStringValueSource(stringValueSource);
stringMatchingExpression_2.setSearchNodeInTrace(false);
applicationDefinition.setMatchingRuleExpression(stringMatchingExpression);
applicationDefinition_empty.setMatchingRuleExpression(stringMatchingExpression_2);
businessTxDefinition_1.setMatchingRuleExpression(stringMatchingExpression_2);
businessTxDefinition_2.setMatchingRuleExpression(stringMatchingExpression_2);
processor.process(root, entityManager);
assertThat(root.getApplicationId(), equalTo(application_unknown.getId()));
assertThat(root.getBusinessTransactionId(), equalTo(businessTx_unknown.getId()));
}
@Test
public void matchEmptyApplication() {
StringMatchingExpression stringMatchingExpression = new StringMatchingExpression(PatternMatchingType.CONTAINS, "root");
stringMatchingExpression.setStringValueSource(stringValueSource);
stringMatchingExpression.setSearchNodeInTrace(false);
StringMatchingExpression stringMatchingExpression_2 = new StringMatchingExpression(PatternMatchingType.CONTAINS, "nothing");
stringMatchingExpression_2.setStringValueSource(stringValueSource);
stringMatchingExpression_2.setSearchNodeInTrace(false);
applicationDefinition.setMatchingRuleExpression(stringMatchingExpression_2);
applicationDefinition_empty.setMatchingRuleExpression(stringMatchingExpression);
processor.process(root, entityManager);
assertThat(root.getApplicationId(), equalTo(application_empty.getId()));
assertThat(root.getBusinessTransactionId(), equalTo(businessTx_unknown.getId()));
}
@Test
public void invalidInputData() {
TimerData invalidInput = new TimerData();
processor.process(invalidInput, entityManager);
verifyNoMoreInteractions(ciService);
}
/**
* Clean test folder after each test.
*/
@AfterMethod
public void cleanUp() throws IOException {
root.setApplicationId(-1);
root.setBusinessTransactionId(-1);
}
}
/**
* Tests
* {@link BusinessContextRecognitionProcessor#onApplicationEvent(rocks.inspectit.server.ci.event.BusinessContextDefinitionUpdateEvent)}
* method.
*
*/
public static class OnApplicationEvent extends BusinessContextRecognitionProcessorTest {
private static AtomicInteger idGenerator = new AtomicInteger(100);
@Mock
CachedDataService cachedDataService;
@Mock
BusinessContextManagementService businessContextManagementService;
@Mock
BufferInvocationDataDaoImpl invocationDataDao;
@Mock
ConfigurationInterfaceService ciService;
@Mock
EntityManager entityManager;
@Mock
BusinessContextDefinitionUpdateEvent event;
@Mock
ScheduledExecutorService executorService;
InvocationSequenceData root;
InvocationSequenceData level_1_1;
InvocationSequenceData level_1_2;
InvocationSequenceData level_2_1;
ApplicationDefinition applicationDefinition;
BusinessTransactionDefinition businessTxDefinition_1;
StringValueSource stringValueSource;
ApplicationData application;
BusinessTransactionData businessTx_1;
@BeforeMethod
public void init() throws BusinessException {
root = new InvocationSequenceData();
root.setId(1);
level_1_1 = new InvocationSequenceData();
level_1_1.setId(2);
level_1_2 = new InvocationSequenceData();
level_1_2.setId(3);
level_2_1 = new InvocationSequenceData();
level_2_1.setId(4);
root.getNestedSequences().add(level_1_1);
root.getNestedSequences().add(level_1_2);
level_1_2.getNestedSequences().add(level_2_1);
root.setApplicationId(-1);
root.setBusinessTransactionId(-1);
when(cachedDataService.getApplicationForId(anyInt())).thenReturn(null);
when(cachedDataService.getBusinessTransactionForId(anyInt(), anyInt())).thenReturn(null);
applicationDefinition = new ApplicationDefinition(idGenerator.getAndIncrement(), "SomeApplication", null);
application = new ApplicationData(idGenerator.getAndIncrement(), applicationDefinition.getId(), applicationDefinition.getApplicationName());
businessTxDefinition_1 = new BusinessTransactionDefinition(idGenerator.getAndIncrement(), "businessTxDefinition_1", null);
businessTx_1 = new BusinessTransactionData(idGenerator.getAndIncrement(), businessTxDefinition_1.getId(), application, businessTxDefinition_1.getBusinessTransactionDefinitionName());
applicationDefinition.addBusinessTransactionDefinition(businessTxDefinition_1);
when(ciService.getApplicationDefinitions()).thenReturn(Collections.singletonList(applicationDefinition));
stringValueSource = mock(StringValueSource.class);
when(stringValueSource.getStringValues(root, cachedDataService)).thenReturn(new String[] { "node/root/" });
when(stringValueSource.getStringValues(level_1_1, cachedDataService)).thenReturn(new String[] { "node/level_1_1/" });
when(stringValueSource.getStringValues(level_1_2, cachedDataService)).thenReturn(new String[] { "node/level_1_2/" });
when(stringValueSource.getStringValues(level_2_1, cachedDataService)).thenReturn(new String[] { "node/level_2_1/", "node/level_2_1/multiple" });
when(businessContextManagementService.registerApplication(applicationDefinition)).thenReturn(application);
when(businessContextManagementService.registerBusinessTransaction(application, businessTxDefinition_1, businessTxDefinition_1.getBusinessTransactionDefinitionName()))
.thenReturn(businessTx_1);
when(invocationDataDao.getInvocationSequenceDetail(0, 0, -1, null, null, null)).thenReturn(Collections.singletonList(root));
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Exception {
Object[] arguments = invocation.getArguments();
Runnable runnable = (Runnable) arguments[0];
runnable.run();
return null;
}
}).when(executorService).execute(any(Runnable.class));
}
@Test
public void businessContextChanged() throws InterruptedException {
StringMatchingExpression stringMatchingExpression = new StringMatchingExpression(PatternMatchingType.CONTAINS, "root");
stringMatchingExpression.setStringValueSource(stringValueSource);
stringMatchingExpression.setSearchNodeInTrace(false);
StringMatchingExpression stringMatchingExpression_2 = new StringMatchingExpression(PatternMatchingType.CONTAINS, "node");
stringMatchingExpression_2.setStringValueSource(stringValueSource);
stringMatchingExpression_2.setSearchNodeInTrace(false);
applicationDefinition.setMatchingRuleExpression(stringMatchingExpression);
businessTxDefinition_1.setMatchingRuleExpression(stringMatchingExpression_2);
processor.onApplicationEvent(event);
assertThat(root.getApplicationId(), equalTo(application.getId()));
assertThat(root.getBusinessTransactionId(), equalTo(businessTx_1.getId()));
}
/**
* Clean test folder after each test.
*/
@AfterMethod
public void cleanUp() throws IOException {
root.setApplicationId(-1);
root.setBusinessTransactionId(-1);
}
}
}
| agpl-3.0 |
rjokelai/parkandrideAPI | application/src/main/java/fi/hsl/parkandride/front/ContactController.java | 3206 | // Copyright © 2015 HSL <https://www.hsl.fi>
// This program is dual-licensed under the EUPL v1.2 and AGPLv3 licenses.
package fi.hsl.parkandride.front;
import fi.hsl.parkandride.core.domain.Contact;
import fi.hsl.parkandride.core.domain.ContactSearch;
import fi.hsl.parkandride.core.domain.SearchResults;
import fi.hsl.parkandride.core.domain.User;
import fi.hsl.parkandride.core.service.ContactService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import javax.inject.Inject;
import static fi.hsl.parkandride.front.UrlSchema.*;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.*;
@RestController
public class ContactController {
private final Logger log = LoggerFactory.getLogger(ContactController.class);
@Inject
ContactService contactService;
@RequestMapping(method = POST, value = CONTACTS, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Contact> createContact(@RequestBody Contact contact,
User currentUser,
UriComponentsBuilder builder) {
log.info("createContact");
Contact newContact = contactService.createContact(contact, currentUser);
log.info("createContact({})", newContact.id);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path(CONTACT).buildAndExpand(newContact.id).toUri());
return new ResponseEntity<>(newContact, headers, CREATED);
}
@RequestMapping(method = GET, value = CONTACT, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Contact> getContact(@PathVariable(CONTACT_ID) long contactId) {
Contact contact = contactService.getContact(contactId);
return new ResponseEntity<>(contact, OK);
}
@RequestMapping(method = PUT, value = CONTACT, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Contact> updateContact(@PathVariable(CONTACT_ID) long contactId,
@RequestBody Contact contact,
User currentUser) {
log.info("updateContact({})", contactId);
Contact response = contactService.updateContact(contactId, contact, currentUser);
return new ResponseEntity<>(response, OK);
}
@RequestMapping(method = GET, value = CONTACTS, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<SearchResults<Contact>> findContacts(ContactSearch search) {
SearchResults<Contact> results = contactService.search(search);
return new ResponseEntity<>(results, OK);
}
}
| agpl-3.0 |
aihua/opennms | opennms-webapp-rest/src/test/java/org/opennms/web/rest/v1/config/PollerConfigurationResourceIT.java | 5424 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2009-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.rest.v1.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.test.MockLogAppender;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.test.db.annotations.JUnitTemporaryDatabase;
import org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase;
import org.opennms.core.xml.JaxbUtils;
import org.opennms.netmgt.config.poller.PollerConfiguration;
import org.opennms.netmgt.dao.api.MonitoringLocationDao;
import org.opennms.netmgt.model.monitoringLocations.OnmsMonitoringLocation;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={
"classpath:/META-INF/opennms/applicationContext-soa.xml",
"classpath:/META-INF/opennms/applicationContext-commonConfigs.xml",
"classpath:/META-INF/opennms/applicationContext-minimal-conf.xml",
"classpath:/META-INF/opennms/applicationContext-dao.xml",
"classpath*:/META-INF/opennms/component-service.xml",
"classpath*:/META-INF/opennms/component-dao.xml",
"classpath:/META-INF/opennms/applicationContext-databasePopulator.xml",
"classpath:/META-INF/opennms/mockEventIpcManager.xml",
"file:src/main/webapp/WEB-INF/applicationContext-svclayer.xml",
"file:src/main/webapp/WEB-INF/applicationContext-cxf-common.xml",
"classpath:/applicationContext-rest-test.xml"
})
@JUnitConfigurationEnvironment
@JUnitTemporaryDatabase
public class PollerConfigurationResourceIT extends AbstractSpringJerseyRestTestCase {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(PollerConfigurationResourceIT.class);
@Autowired
private MonitoringLocationDao m_monitoringLocationDao;
@Override
protected void afterServletStart() throws Exception {
MockLogAppender.setupLogging(true, "DEBUG");
OnmsMonitoringLocation location = new OnmsMonitoringLocation("RDU", "East Coast", new String[] { "example1" }, new String[] { "example1" }, "Research Triangle Park, NC", 35.715751f, -79.16262f, 1L);
m_monitoringLocationDao.saveOrUpdate(location);
location = new OnmsMonitoringLocation("00002", "IN", new String[] { "example2" }, new String[0], "2 Open St., Network, MS 00002", 38.2096f, -85.8704f, 100L, "even");
m_monitoringLocationDao.saveOrUpdate(location);
location = new OnmsMonitoringLocation("00003", "IN", new String[] { "example2" }, new String[] { "example2" }, "2 Open St., Network, MS 00002", 38.2096f, -85.8704f, 100L, "odd");
m_monitoringLocationDao.saveOrUpdate(location);
}
@Test
public void testPollerConfig() throws Exception {
sendRequest(GET, "/config/foo/polling", 404);
String xml = sendRequest(GET, "/config/RDU/polling", 200);
PollerConfiguration config = JaxbUtils.unmarshal(PollerConfiguration.class, xml);
assertNotNull(config);
assertEquals(1, config.getPackages().size());
assertEquals("example1", config.getPackages().get(0).getName());
assertEquals(17, config.getMonitors().size());
xml = sendRequest(GET, "/config/00002/polling", 200);
config = JaxbUtils.unmarshal(PollerConfiguration.class, xml);
assertNotNull(config);
assertEquals(1, config.getPackages().size());
assertEquals("example2", config.getPackages().get(0).getName());
assertEquals(1, config.getMonitors().size());
xml = sendRequest(GET, "/config/00003/polling", 200);
config = JaxbUtils.unmarshal(PollerConfiguration.class, xml);
assertNotNull(config);
assertEquals(1, config.getPackages().size());
assertEquals("example2", config.getPackages().get(0).getName());
assertEquals(1, config.getMonitors().size());
}
}
| agpl-3.0 |
esofthead/mycollab | mycollab-services/src/main/java/com/mycollab/form/view/builder/type/NumberDynaField.java | 856 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.form.view.builder.type;
/**
* @author MyCollab Ltd.
* @since 1.0
*/
public class NumberDynaField extends AbstractDynaField {
}
| agpl-3.0 |
inspectIT/inspectIT | inspectit.server.diagnosis/src/test/java/rocks/inspectit/server/diagnosis/engine/testrules/RuleB.java | 473 | package rocks.inspectit.server.diagnosis.engine.testrules;
import rocks.inspectit.server.diagnosis.engine.rule.annotation.Action;
import rocks.inspectit.server.diagnosis.engine.rule.annotation.Rule;
import rocks.inspectit.server.diagnosis.engine.rule.annotation.TagValue;
/**
* @author Alexander Wert
*
*/
@Rule(name = "RuleB")
public class RuleB {
@TagValue(type = "A")
String input;
@Action(resultTag = "B")
public int action() {
return input.length();
}
}
| agpl-3.0 |
Godin/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/SinglelineDetector.java | 4128 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// 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 com.puppycrawl.tools.checkstyle.checks.regexp;
import java.util.List;
import java.util.regex.Matcher;
/**
* A detector that matches individual lines.
* @author oliver
*/
class SinglelineDetector {
/** The detection options to use. */
private final DetectorOptions options;
/** Tracks the number of matches. */
private int currentMatches;
/**
* Creates an instance.
* @param options the options to use.
*/
public SinglelineDetector(DetectorOptions options) {
this.options = options;
}
/**
* Processes a set of lines looking for matches.
* @param lines the lines to process.
*/
public void processLines(List<String> lines) {
resetState();
int lineno = 0;
for (String line : lines) {
lineno++;
checkLine(lineno, line, options.getPattern().matcher(line), 0);
}
finish();
}
/** Perform processing at the end of a set of lines. */
private void finish() {
if (currentMatches < options.getMinimum()) {
if (options.getMessage().isEmpty()) {
options.getReporter().log(0, "regexp.minimum",
options.getMinimum(), options.getFormat());
}
else {
options.getReporter().log(0, options.getMessage());
}
}
}
/**
* Reset the state of the detector.
*/
private void resetState() {
currentMatches = 0;
}
/**
* Check a line for matches.
* @param lineno the line number of the line to check
* @param line the line to check
* @param matcher the matcher to use
* @param startPosition the position to start searching from.
*/
private void checkLine(int lineno, String line, Matcher matcher,
int startPosition) {
final boolean foundMatch = matcher.find(startPosition);
if (!foundMatch) {
return;
}
// match is found, check for intersection with comment
final int startCol = matcher.start(0);
final int endCol = matcher.end(0);
// Note that Matcher.end(int) returns the offset AFTER the
// last matched character, but shouldSuppress()
// needs column number of the last character.
// So we need to use (endCol - 1) here.
if (options.getSuppressor()
.shouldSuppress(lineno, startCol, lineno, endCol - 1)) {
if (endCol < line.length()) {
// check if the expression is on the rest of the line
checkLine(lineno, line, matcher, endCol);
}
return; // end processing here
}
currentMatches++;
if (currentMatches > options.getMaximum()) {
if (options.getMessage().isEmpty()) {
options.getReporter().log(lineno, "regexp.exceeded",
matcher.pattern().toString());
}
else {
options.getReporter().log(lineno, options.getMessage());
}
}
}
}
| lgpl-2.1 |
inesc-id-esw/jvstm | src/test/java/jvstm/test/jwormbench/BenchWorldNode__FIELDS__.java | 1096 | package jvstm.test.jwormbench;
import jwormbench.core.IWorm;
/**
* Abstracts the node object within the BenchWorld.
*
* @author F. Miguel Carvalho mcarvalho[@]cc.isel.pt
*/
public class BenchWorldNode__FIELDS__ extends BenchWorldNodeAom{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ------------------- CONSTRUCTOR -----------------
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public BenchWorldNode__FIELDS__(int value){
super(value);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ------------------- PROPERTIES -----------------
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public int getValue() {
throw new UnsupportedOperationException();
}
@Override
public void setValue(int value) {
throw new UnsupportedOperationException();
}
@Override
public IWorm getWorm() {
throw new UnsupportedOperationException();
}
@Override
public void setWorm(IWorm w) {
throw new UnsupportedOperationException();
}
}
| lgpl-2.1 |
dpisarewski/gka_wise12 | src/com/mxgraph/swing/util/mxSwingConstants.java | 4927 | /**
* $Id: mxSwingConstants.java,v 1.3 2012-01-13 11:31:01 david Exp $
* Copyright (c) 2007-2012, JGraph Ltd
*/
package com.mxgraph.swing.util;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class mxSwingConstants
{
/**
* Contains an empty image of size 1, 1.
*/
public static BufferedImage EMPTY_IMAGE;
static
{
try
{
mxSwingConstants.EMPTY_IMAGE = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_RGB);
}
catch (Exception e)
{
// Occurs when running on GAE, BufferedImage is a
// blacklisted class
mxSwingConstants.EMPTY_IMAGE = null;
}
}
/**
* Defines the color to be used for shadows. Default is gray.
*/
public static Color SHADOW_COLOR;
/**
* Specifies the default valid color. Default is green.
*/
public static Color DEFAULT_VALID_COLOR;
/**
* Specifies the default invalid color. Default is red.
*/
public static Color DEFAULT_INVALID_COLOR;
/**
* Defines the rubberband border color.
*/
public static Color RUBBERBAND_BORDERCOLOR;
/**
* Defines the rubberband fill color with an alpha of 80.
*/
public static Color RUBBERBAND_FILLCOLOR;
/**
* Defines the handle border color. Default is black.
*/
public static Color HANDLE_BORDERCOLOR;
/**
* Defines the handle fill color. Default is green.
*/
public static Color HANDLE_FILLCOLOR;
/**
* Defines the label handle fill color. Default is yellow.
*/
public static Color LABEL_HANDLE_FILLCOLOR;
/**
* Defines the connect handle fill color. Default is blue.
*/
public static Color CONNECT_HANDLE_FILLCOLOR;
/**
* Defines the handle fill color for locked handles. Default is red.
*/
public static Color LOCKED_HANDLE_FILLCOLOR;
/**
* Defines the selection color for edges. Default is green.
*/
public static Color EDGE_SELECTION_COLOR;
/**
* Defines the selection color for vertices. Default is green.
*/
public static Color VERTEX_SELECTION_COLOR;
static
{
try
{
mxSwingConstants.SHADOW_COLOR = Color.gray;
mxSwingConstants.DEFAULT_VALID_COLOR = Color.GREEN;
mxSwingConstants.DEFAULT_INVALID_COLOR = Color.RED;
mxSwingConstants.RUBBERBAND_BORDERCOLOR = new Color(51, 153, 255);
mxSwingConstants.RUBBERBAND_FILLCOLOR = new Color(51, 153, 255, 80);
mxSwingConstants.HANDLE_BORDERCOLOR = Color.black;
mxSwingConstants.HANDLE_FILLCOLOR = Color.green;
mxSwingConstants.LABEL_HANDLE_FILLCOLOR = Color.yellow;
mxSwingConstants.LOCKED_HANDLE_FILLCOLOR = Color.red;
mxSwingConstants.CONNECT_HANDLE_FILLCOLOR = Color.blue;
mxSwingConstants.EDGE_SELECTION_COLOR = Color.green;
mxSwingConstants.VERTEX_SELECTION_COLOR = Color.green;
}
catch (Exception e)
{
// Occurs when running on GAE, Color is a
// blacklisted class
mxSwingConstants.SHADOW_COLOR = null;
mxSwingConstants.DEFAULT_VALID_COLOR = null;
mxSwingConstants.DEFAULT_INVALID_COLOR = null;
mxSwingConstants.RUBBERBAND_BORDERCOLOR = null;
mxSwingConstants.RUBBERBAND_FILLCOLOR = null;
mxSwingConstants.HANDLE_BORDERCOLOR = null;
mxSwingConstants.HANDLE_FILLCOLOR = null;
mxSwingConstants.LABEL_HANDLE_FILLCOLOR = null;
mxSwingConstants.LOCKED_HANDLE_FILLCOLOR = null;
mxSwingConstants.CONNECT_HANDLE_FILLCOLOR = null;
mxSwingConstants.EDGE_SELECTION_COLOR = null;
mxSwingConstants.VERTEX_SELECTION_COLOR = null;
}
}
/**
* Defines the stroke used for painting selected edges. Default is a dashed
* line.
*/
public static Stroke EDGE_SELECTION_STROKE = new BasicStroke(1,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[] {
3, 3 }, 0.0f);
/**
* Defines the stroke used for painting the border of selected vertices.
* Default is a dashed line.
*/
public static Stroke VERTEX_SELECTION_STROKE = new BasicStroke(1,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[] {
3, 3 }, 0.0f);
/**
* Defines the stroke used for painting the preview for new and existing edges
* that are being changed. Default is a dashed line.
*/
public static Stroke PREVIEW_STROKE = new BasicStroke(1,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[] {
3, 3 }, 0.0f);
/**
* Defines the border used for painting the preview when vertices are being
* resized, or cells and labels are being moved.
*/
public static Border PREVIEW_BORDER = new LineBorder(
mxSwingConstants.HANDLE_BORDERCOLOR)
{
/**
*
*/
private static final long serialVersionUID = 1348016511717964310L;
public void paintBorder(Component c, Graphics g, int x, int y,
int width, int height)
{
((Graphics2D) g).setStroke(VERTEX_SELECTION_STROKE);
super.paintBorder(c, g, x, y, width, height);
}
};
}
| lgpl-2.1 |
ggiudetti/opencms-core | test/org/opencms/util/TestValidFilename.java | 3946 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH & Co. KG, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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.opencms.util;
import org.opencms.file.CmsResource;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.test.OpenCmsTestCase;
/**
* Test cases for file name validation.<p>
*
* @since 6.0.0
*/
public class TestValidFilename extends OpenCmsTestCase {
/**
* Tests the file name validation method in the class CmsDriverManager.<p>
*
* @throws Exception if something goes wrong
*/
public void testCheckNameForResource() throws Exception {
// according to windows, the following characters are illegal:
// \ / : * ? " < > |
// accoring to JSR 170, the following characters are illegal:
// / : [ ] * ' " |
// technically, for OpenCms only the following char can not be part of a file: /
// for HTML URL building, the following chars are "reserved characters" (see RFC 1738)
// ; / ? : @ = &
// stupidity tests
assertFalse(checkName(null));
assertFalse(checkName(""));
// all valid chars according to the OpenCms logic
assertTrue(checkName("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~$"));
// add some of the new valid chars
assertFalse(checkName("Copy of abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~$"));
assertFalse(checkName("Some German umlauts - \u00E4\u00F6\u00FC\u00C4\u00D6\u00DC\u00DF"));
assertFalse(
checkName("Some more western European special chars - \u00E9\u00E8\u00F4\u00E1\u00E0\u00FB\u00ED\u00EC"));
assertFalse(checkName("my File"));
// Window logic invalid chars
assertFalse(checkName(" my File"));
assertFalse(checkName("my File "));
assertFalse(checkName("\tmy File"));
assertFalse(checkName("\rmy File"));
assertFalse(checkName("\nmy File"));
assertFalse(checkName("my/file"));
assertFalse(checkName("my\\file"));
assertFalse(checkName("my:file"));
assertFalse(checkName("my*file"));
assertFalse(checkName("my?file"));
assertFalse(checkName("my\"file"));
assertFalse(checkName("my<file"));
assertFalse(checkName("my>file"));
assertFalse(checkName("my|file"));
// JSR 170 chars
assertFalse(checkName("my[file"));
assertFalse(checkName("my]file"));
assertFalse(checkName("my'file"));
// HTML reserved chars
assertFalse(checkName("my&file"));
assertFalse(checkName("my=file"));
assertFalse(checkName("my@file"));
}
private boolean checkName(String name) {
try {
CmsResource.checkResourceName(name);
return true;
} catch (CmsIllegalArgumentException e) {
return false;
}
}
}
| lgpl-2.1 |
magnevan/Arithmic-Agents | src/examples/content/ecommerceOntology/Price.java | 1661 | /**
* ***************************************************************
* JADE - Java Agent DEvelopment Framework is a framework to develop
* multi-agent systems in compliance with the FIPA specifications.
* Copyright (C) 2000 CSELT S.p.A.
*
* GNU Lesser General Public License
*
* 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,
* version 2.1 of the License.
*
* 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 examples.content.ecommerceOntology;
import jade.content.*;
public class Price implements Concept {
private float value;
private String currency;
public Price() {
}
public Price(float value, String currency) {
setValue(value);
setCurrency(currency);
}
// VALUE
public float getValue() {
return value;
}
public void setValue(float value) {
this.value = value;
}
// CURRENCY
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String toString() {
return value+"-"+currency;
}
}
| lgpl-2.1 |
karajrish/twitstream | src/org/loklak/api/RemoteAccess.java | 10564 | /**
* RemoteAccess
* Copyright 22.02.2015 by Michael Peter Christen, @0rb1t3r
*
* 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 program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.loklak.api;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.loklak.DAO;
/**
* Storage of a peer list which can be used for peer-to-peer communication.
* This is a static class to provide access to all other objects easily.
* We store the IPs here only temporary, not permanently.
*/
public class RemoteAccess {
public static Map<String, RemoteAccess> history = new ConcurrentHashMap<String, RemoteAccess>();
public static Post evaluate(final HttpServletRequest request) {
String clientHost = request.getRemoteHost();
String XRealIP = request.getHeader("X-Real-IP"); if (XRealIP != null && XRealIP.length() > 0) clientHost = XRealIP; // get IP through nginx config "proxy_set_header X-Real-IP $remote_addr;"
String path = request.getServletPath();
Map<String, String> qm = getQueryMap(request.getQueryString());
Post post = new Post(request, qm);
String httpports = qm == null ? request.getParameter("port.http") : qm.get("port.http");
Integer httpport = httpports == null ? null : Integer.parseInt(httpports);
String httpsports = qm == null ? request.getParameter("port.https") : qm.get("port.https");
Integer httpsport = httpsports == null ? null : Integer.parseInt(httpsports);
String peername = qm == null ? request.getParameter("peername") : qm.get("peername");
if (peername == null || peername.length() > 132) peername = "anonymous";
post.setRemoteAccess(init(clientHost, path, httpport, httpsport, peername));
return post;
}
private static RemoteAccess init(final String remoteHost, final String localPath, final Integer localHTTPPort, final Integer localHTTPSPort, final String peername) {
RemoteAccess ra;
if (localHTTPPort == null || localHTTPSPort == null) {
// if port configuration is omitted, just update the value if it exist
ra = history.get(remoteHost);
if (ra == null) {
history.put(remoteHost, new RemoteAccess(remoteHost, localPath, localHTTPPort, localHTTPSPort, peername));
} else {
assert ra.remoteHost.equals(remoteHost);
ra.localPath = localPath;
ra.accessTime = System.currentTimeMillis();
}
} else {
// overwrite if new port configuration is submitted
ra = new RemoteAccess(remoteHost, localPath, localHTTPPort, localHTTPSPort, peername);
history.put(remoteHost, ra);
}
return ra;
}
public static long latestVisit(String remoteHost) {
RemoteAccess ra = history.get(remoteHost);
return ra == null ? -1 : ra.accessTime;
}
public static String hostHash(String remoteHost) {
return Integer.toHexString(Math.abs(remoteHost.hashCode()));
}
public static class Post {
private HttpServletRequest request;
private Map<String, String> qm;
private RemoteAccess ra;
private String clientHost;
private long access_time, time_since_last_access;
private boolean DoS_blackout, DoS_servicereduction;
public Post(final HttpServletRequest request, final Map<String, String> qm) {
this.qm = qm;
this.request = request;
this.ra = null;
this.clientHost = request.getRemoteHost();
String XRealIP = request.getHeader("X-Real-IP");
if (XRealIP != null && XRealIP.length() > 0) this.clientHost = XRealIP; // get IP through nginx config "proxy_set_header X-Real-IP $remote_addr;"
this.access_time = System.currentTimeMillis();
this.time_since_last_access = this.access_time - RemoteAccess.latestVisit(this.clientHost);
this.DoS_blackout = this.time_since_last_access < DAO.getConfig("DoS.blackout", 100) || sleeping4clients.contains(this.clientHost);
this.DoS_servicereduction = this.time_since_last_access < DAO.getConfig("DoS.servicereduction", 1000);
}
public String getClientHost() {
return this.clientHost;
}
public boolean isLocalhostAccess() {
return isLocalhost(this.clientHost);
}
public long getAccessTime() {
return this.access_time;
}
public long getTimeSinceLastAccess() {
return this.time_since_last_access;
}
public boolean isDoS_blackout() {
return this.DoS_blackout;
}
public boolean isDoS_servicereduction() {
return this.DoS_servicereduction;
}
public String get(String key, String dflt) {
String val = qm == null ? request.getParameter(key) : qm.get(key);
return val == null ? dflt : val;
}
public String[] get(String key, String[] dflt, String delim) {
String val = qm == null ? request.getParameter(key) : qm.get(key);
return val == null || val.length() == 0 ? dflt : val.split(delim);
}
public int get(String key, int dflt) {
String val = qm == null ? request.getParameter(key) : qm.get(key);
return val == null ? dflt : Integer.parseInt(val);
}
public boolean get(String key, boolean dflt) {
String val = qm == null ? request.getParameter(key) : qm.get(key);
return val == null ? dflt : "true".equals(val) || "1".equals(val);
}
public void setRemoteAccess(final RemoteAccess ra) {
this.ra = ra;
}
public RemoteAccess getRemoteAccess() {
return this.ra;
}
public void setResponse(final HttpServletResponse response, final String mime) {
response.setDateHeader("Last-Modified", this.access_time);
response.setDateHeader("Expires", this.access_time + 2 * DAO.getConfig("DoS.servicereduction", 1000));
response.setContentType(mime);
response.setHeader("X-Robots-Tag", "noindex,noarchive,nofollow,nosnippet");
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
}
}
private static HashSet<String> sleeping4clients = new HashSet<>();
public static void sleep(String host, long time) {
try {
sleeping4clients.add(host);
Thread.sleep(time);
} catch (InterruptedException e) {
} finally {
sleeping4clients.remove(host);
}
}
public static boolean isSleepingForClient(String host) {
return sleeping4clients.contains(host);
}
private String remoteHost, localPath, peername;
private int localHTTPPort, localHTTPSPort;
private long accessTime;
private RemoteAccess(final String remoteHost, final String localPath, final Integer localHTTPPort, final Integer localHTTPSPort, final String peername) {
this.remoteHost = remoteHost;
this.localPath = localPath;
this.localHTTPPort = localHTTPPort == null ? -1 : localHTTPPort.intValue();
this.localHTTPSPort = localHTTPSPort == null ? -1 : localHTTPSPort.intValue();
this.peername = peername;
this.accessTime = System.currentTimeMillis();
}
public String getRemoteHost() {
return this.remoteHost;
}
public String getLocalPath() {
return this.localPath;
}
public long getAccessTime() {
return this.accessTime;
}
public int getLocalHTTPPort() {
return this.localHTTPPort;
}
public int getLocalHTTPSPort() {
return this.localHTTPSPort;
}
public String getPeername() {
return this.peername;
}
public static boolean isLocalhost(String host) {
return "0:0:0:0:0:0:0:1".equals(host) || "fe80:0:0:0:0:0:0:1%1".equals(host) || "127.0.0.1".equals(host) || "localhost".equals(host);
}
public static Map<String, String> getQueryMap(String query) {
if (query == null) return null;
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
int p = param.indexOf('=');
if (p >= 0)
try {map.put(param.substring(0, p), URLDecoder.decode(param.substring(p + 1), "UTF-8"));} catch (UnsupportedEncodingException e) {}
}
return map;
}
public static Map<String, String> getPostMap(HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>();
try {
final char[] buffer = new char[1024];
for (Part part: request.getParts()) {
String name = part.getName();
InputStream is = part.getInputStream();
final StringBuilder out = new StringBuilder();
final Reader in = new InputStreamReader(is, "UTF-8");
int c;
try {while ((c = in.read(buffer, 0, buffer.length)) > 0) {
out.append(buffer, 0, c);
}} finally {is.close();}
map.put(name, out.toString());
}
} catch (IOException e) {
} catch (ServletException e) {
}
return map;
}
}
| lgpl-2.1 |
meg0man/languagetool | languagetool-language-modules/ro/src/test/java/org/languagetool/rules/ro/GenericUnpairedBracketsRuleTest.java | 2889 | /* LanguageTool, a natural language style checker
* Copyright (C) 2008 Daniel Naber (http://www.danielnaber.de)
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.ro;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.language.Romanian;
import org.languagetool.rules.GenericUnpairedBracketsRule;
import org.languagetool.rules.RuleMatch;
import java.io.IOException;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
public class GenericUnpairedBracketsRuleTest {
private GenericUnpairedBracketsRule rule;
private JLanguageTool langTool;
@Test
public void testRomanianRule() throws IOException {
langTool = new JLanguageTool(new Romanian());
rule = org.languagetool.rules.GenericUnpairedBracketsRuleTest.getBracketsRule(langTool);
// correct sentences:
assertMatches("A fost plecat (pentru puțin timp).", 0);
assertMatches("Nu's de prin locurile astea.", 0);
assertMatches("A fost plecat pentru „puțin timp”.", 0);
assertMatches("A fost plecat „pentru... puțin timp”.", 0);
assertMatches("A fost plecat „pentru... «puțin» timp”.", 0);
// correct sentences ( " is _not_ a Romanian symbol - just
// ignore it, the correct form is [„] (start quote) and [”] (end quote)
assertMatches("A fost plecat \"pentru puțin timp.", 0);
// incorrect sentences:
assertMatches("A fost )plecat( pentru (puțin timp).", 2);
assertMatches("A fost {plecat) pentru (puțin timp}.", 4);
assertMatches("A fost plecat „pentru... puțin timp.", 1);
assertMatches("A fost plecat «puțin.", 1);
assertMatches("A fost plecat „pentru «puțin timp”.", 3);
assertMatches("A fost plecat „pentru puțin» timp”.", 3);
assertMatches("A fost plecat „pentru... puțin» timp”.", 3);
assertMatches("A fost plecat „pentru... «puțin” timp».", 4);
}
private void assertMatches(String input, int expectedMatches) throws IOException {
final RuleMatch[] matches = rule.match(Collections.singletonList(langTool.getAnalyzedSentence(input)));
assertEquals(expectedMatches, matches.length);
}
}
| lgpl-2.1 |
britt/hivedb | src/main/java/org/hivedb/HiveException.java | 545 | /**
* HiveDB is an Open Source (LGPL) system for creating large, high-transaction-volume
* data storage systems.
*
* @author Kevin Kelm (kkelm@fortress-consulting.com)
*/
package org.hivedb;
@SuppressWarnings("serial")
public class HiveException extends Exception {
public static final String CONNECTION_VALIDATION_ERROR = "Connection validator error";
public HiveException(String message) {
super(message);
}
public HiveException(String message, Exception inner) {
super(message,inner);
}
} // HiveException
| lgpl-2.1 |
raedle/univis | lib/hibernate-3.1.3/src/org/hibernate/engine/Mapping.java | 802 | //$Id: Mapping.java 7586 2005-07-21 01:11:52Z oneovthafew $
package org.hibernate.engine;
import org.hibernate.MappingException;
import org.hibernate.type.Type;
/**
* Defines operations common to "compiled" mappings (ie. <tt>SessionFactory</tt>)
* and "uncompiled" mappings (ie. <tt>Configuration</tt>) that are used by
* implementors of <tt>Type</tt>.
*
* @see org.hibernate.type.Type
* @see org.hibernate.impl.SessionFactoryImpl
* @see org.hibernate.cfg.Configuration
* @author Gavin King
*/
public interface Mapping {
public Type getIdentifierType(String className) throws MappingException;
public String getIdentifierPropertyName(String className) throws MappingException;
public Type getReferencedPropertyType(String className, String propertyName) throws MappingException;
}
| lgpl-2.1 |
syntelos/cddb | src/org/jaudiotagger/audio/mp3/MP3File.java | 34981 | /**
* @author : Paul Taylor
* @author : Eric Farng
*
* Version @version:$Id$
*
* MusicTag Copyright (C)2003,2004
*
* 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,
* you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.jaudiotagger.audio.mp3;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.logging.*;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import org.jaudiotagger.tag.TagNotFoundException;
import org.jaudiotagger.tag.TagOptionSingleton;
import org.jaudiotagger.tag.id3.*;
import org.jaudiotagger.tag.lyrics3.AbstractLyrics3;
import org.jaudiotagger.tag.reference.ID3V2Version;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Level;
/**
* This class represents a physical MP3 File
*/
public class MP3File extends AudioFile
{
private static final int MINIMUM_FILESIZE = 150;
protected static AbstractTagDisplayFormatter tagFormatter;
/**
* the ID3v2 tag that this file contains.
*/
private AbstractID3v2Tag id3v2tag = null;
/**
* Representation of the idv2 tag as a idv24 tag
*/
private ID3v24Tag id3v2Asv24tag = null;
/**
* The Lyrics3 tag that this file contains.
*/
private AbstractLyrics3 lyrics3tag = null;
/**
* The ID3v1 tag that this file contains.
*/
private ID3v1Tag id3v1tag = null;
/**
* Creates a new empty MP3File datatype that is not associated with a
* specific file.
*/
public MP3File()
{
}
/**
* Creates a new MP3File datatype and parse the tag from the given filename.
*
* @param filename MP3 file
* @throws IOException on any I/O error
* @throws TagException on any exception generated by this library.
* @throws org.jaudiotagger.audio.exceptions.ReadOnlyFileException
* @throws org.jaudiotagger.audio.exceptions.InvalidAudioFrameException
*/
public MP3File(String filename) throws IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException
{
this(new File(filename));
}
/* Load ID3V1tag if exists */
public static final int LOAD_IDV1TAG = 2;
/* Load ID3V2tag if exists */
public static final int LOAD_IDV2TAG = 4;
/**
* This option is currently ignored
*/
public static final int LOAD_LYRICS3 = 8;
public static final int LOAD_ALL = LOAD_IDV1TAG | LOAD_IDV2TAG | LOAD_LYRICS3;
/**
* Creates a new MP3File dataType and parse the tag from the given file
* Object, files must be writable to use this constructor.
*
* @param file MP3 file
* @param loadOptions decide what tags to load
* @throws IOException on any I/O error
* @throws TagException on any exception generated by this library.
* @throws org.jaudiotagger.audio.exceptions.ReadOnlyFileException
* @throws org.jaudiotagger.audio.exceptions.InvalidAudioFrameException
*/
public MP3File(File file, int loadOptions) throws IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException
{
this(file, loadOptions, false);
}
/**
* Read v1 tag
*
* @param file
* @param newFile
* @param loadOptions
* @throws IOException
*/
private void readV1Tag(File file, RandomAccessFile newFile, int loadOptions) throws IOException
{
if ((loadOptions & LOAD_IDV1TAG) != 0)
{
logger.finer("Attempting to read id3v1tags");
try
{
id3v1tag = new ID3v11Tag(newFile, file.getName());
}
catch (TagNotFoundException ex)
{
logger.config("No ids3v11 tag found");
}
try
{
if (id3v1tag == null)
{
id3v1tag = new ID3v1Tag(newFile, file.getName());
}
}
catch (TagNotFoundException ex)
{
logger.config("No id3v1 tag found");
}
}
}
/**
* Read V2tag if exists
*
* TODO:shouldn't we be handing TagExceptions:when will they be thrown
*
* @param file
* @param loadOptions
* @throws IOException
* @throws TagException
*/
private void readV2Tag(File file, int loadOptions, int startByte) throws IOException, TagException
{
//We know where the actual Audio starts so load all the file from start to that point into
//a buffer then we can read the IDv2 information without needing any more File I/O
if (startByte >= AbstractID3v2Tag.TAG_HEADER_LENGTH)
{
logger.finer("Attempting to read id3v2tags");
FileInputStream fis = null;
FileChannel fc = null;
ByteBuffer bb;
try
{
fis = new FileInputStream(file);
fc = fis.getChannel();
bb = fc.map(FileChannel.MapMode.READ_ONLY,0,startByte);
}
//#JAUDIOTAGGER-419:If reading networked file map can fail so just copy bytes instead
catch(IOException ioe)
{
bb = ByteBuffer.allocate(startByte);
fc.read(bb,0);
}
finally
{
if (fc != null)
{
fc.close();
}
if (fis != null)
{
fis.close();
}
}
try
{
bb.rewind();
if ((loadOptions & LOAD_IDV2TAG) != 0)
{
logger.config("Attempting to read id3v2tags");
try
{
this.setID3v2Tag(new ID3v24Tag(bb, file.getName()));
}
catch (TagNotFoundException ex)
{
logger.config("No id3v24 tag found");
}
try
{
if (id3v2tag == null)
{
this.setID3v2Tag(new ID3v23Tag(bb, file.getName()));
}
}
catch (TagNotFoundException ex)
{
logger.config("No id3v23 tag found");
}
try
{
if (id3v2tag == null)
{
this.setID3v2Tag(new ID3v22Tag(bb, file.getName()));
}
}
catch (TagNotFoundException ex)
{
logger.config("No id3v22 tag found");
}
}
}
finally
{
//Workaround for 4724038 on Windows
bb.clear();
if (bb != null && bb.isDirect())
{
((sun.nio.ch.DirectBuffer) bb).cleaner().clean();
}
}
}
else
{
logger.config("Not enough room for valid id3v2 tag:" + startByte);
}
}
/**
* Read lyrics3 Tag
*
* TODO:not working
*
* @param file
* @param newFile
* @param loadOptions
* @throws IOException
*/
private void readLyrics3Tag(File file, RandomAccessFile newFile, int loadOptions) throws IOException
{
/*if ((loadOptions & LOAD_LYRICS3) != 0)
{
try
{
lyrics3tag = new Lyrics3v2(newFile);
}
catch (TagNotFoundException ex)
{
}
try
{
if (lyrics3tag == null)
{
lyrics3tag = new Lyrics3v1(newFile);
}
}
catch (TagNotFoundException ex)
{
}
}
*/
}
/**
*
* @param startByte
* @param endByte
* @return
* @throws Exception
*
* @return true if all the bytes between in the file between startByte and endByte are null, false
* otherwise
*/
private boolean isFilePortionNull(int startByte, int endByte) throws IOException
{
logger.config("Checking file portion:" + Hex.asHex(startByte) + ":" + Hex.asHex(endByte));
FileInputStream fis=null;
FileChannel fc=null;
try
{
fis = new FileInputStream(file);
fc = fis.getChannel();
fc.position(startByte);
ByteBuffer bb = ByteBuffer.allocateDirect(endByte - startByte);
fc.read(bb);
while(bb.hasRemaining())
{
if(bb.get()!=0)
{
return false;
}
}
}
finally
{
if (fc != null)
{
fc.close();
}
if (fis != null)
{
fis.close();
}
}
return true;
}
/**
* Regets the audio header starting from start of file, and write appropriate logging to indicate
* potential problem to user.
*
* @param startByte
* @param firstHeaderAfterTag
* @return
* @throws IOException
* @throws InvalidAudioFrameException
*/
private MP3AudioHeader checkAudioStart(long startByte, MP3AudioHeader firstHeaderAfterTag) throws IOException, InvalidAudioFrameException
{
MP3AudioHeader headerOne;
MP3AudioHeader headerTwo;
logger.warning(ErrorMessage.MP3_ID3TAG_LENGTH_INCORRECT.getMsg(file.getPath(), Hex.asHex(startByte), Hex.asHex(firstHeaderAfterTag.getMp3StartByte())));
//because we cant agree on start location we reread the audioheader from the start of the file, at least
//this way we cant overwrite the audio although we might overwrite part of the tag if we write this file
//back later
headerOne = new MP3AudioHeader(file, 0);
logger.config("Checking from start:" + headerOne);
//Although the id3 tag size appears to be incorrect at least we have found the same location for the start
//of audio whether we start searching from start of file or at the end of the alleged of file so no real
//problem
if (firstHeaderAfterTag.getMp3StartByte() == headerOne.getMp3StartByte())
{
logger.config(ErrorMessage.MP3_START_OF_AUDIO_CONFIRMED.getMsg(file.getPath(),
Hex.asHex(headerOne.getMp3StartByte())));
return firstHeaderAfterTag;
}
else
{
//We get a different value if read from start, can't guarantee 100% correct lets do some more checks
logger.config((ErrorMessage.MP3_RECALCULATED_POSSIBLE_START_OF_MP3_AUDIO.getMsg(file.getPath(),
Hex.asHex(headerOne.getMp3StartByte()))));
//Same frame count so probably both audio headers with newAudioHeader being the first one
if (firstHeaderAfterTag.getNumberOfFrames() == headerOne.getNumberOfFrames())
{
logger.warning((ErrorMessage.MP3_RECALCULATED_START_OF_MP3_AUDIO.getMsg(file.getPath(),
Hex.asHex(headerOne.getMp3StartByte()))));
return headerOne;
}
//If the size reported by the tag header is a little short and there is only nulls between the recorded value
//and the start of the first audio found then we stick with the original header as more likely that currentHeader
//DataInputStream not really a header
if(isFilePortionNull((int) startByte,(int) firstHeaderAfterTag.getMp3StartByte()))
{
return firstHeaderAfterTag;
}
//Skip to the next header (header 2, counting from start of file)
headerTwo = new MP3AudioHeader(file, headerOne.getMp3StartByte()
+ headerOne.mp3FrameHeader.getFrameLength());
//It matches the header we found when doing the original search from after the ID3Tag therefore it
//seems that newAudioHeader was a false match and the original header was correct
if (headerTwo.getMp3StartByte() == firstHeaderAfterTag.getMp3StartByte())
{
logger.warning((ErrorMessage.MP3_START_OF_AUDIO_CONFIRMED.getMsg(file.getPath(),
Hex.asHex(firstHeaderAfterTag.getMp3StartByte()))));
return firstHeaderAfterTag;
}
//It matches the frameCount the header we just found so lends weight to the fact that the audio does indeed start at new header
//however it maybe that neither are really headers and just contain the same data being misrepresented as headers.
if (headerTwo.getNumberOfFrames() == headerOne.getNumberOfFrames())
{
logger.warning((ErrorMessage.MP3_RECALCULATED_START_OF_MP3_AUDIO.getMsg(file.getPath(),
Hex.asHex(headerOne.getMp3StartByte()))));
return headerOne;
}
///Doesnt match the frameCount lets go back to the original header
else
{
logger.warning((ErrorMessage.MP3_RECALCULATED_START_OF_MP3_AUDIO.getMsg(file.getPath(),
Hex.asHex(firstHeaderAfterTag.getMp3StartByte()))));
return firstHeaderAfterTag;
}
}
}
/**
* Creates a new MP3File dataType and parse the tag from the given file
* Object, files can be opened read only if required.
*
* @param file MP3 file
* @param loadOptions decide what tags to load
* @param readOnly causes the files to be opened readonly
* @throws IOException on any I/O error
* @throws TagException on any exception generated by this library.
* @throws org.jaudiotagger.audio.exceptions.ReadOnlyFileException
* @throws org.jaudiotagger.audio.exceptions.InvalidAudioFrameException
*/
public MP3File(File file, int loadOptions, boolean readOnly) throws IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException
{
RandomAccessFile newFile = null;
try
{
this.file = file;
//Check File accessibility
newFile = checkFilePermissions(file, readOnly);
//Read ID3v2 tag size (if tag exists) to allow audioHeader parsing to skip over tag
long tagSizeReportedByHeader = AbstractID3v2Tag.getV2TagSizeIfExists(file);
logger.config("TagHeaderSize:" + Hex.asHex(tagSizeReportedByHeader));
audioHeader = new MP3AudioHeader(file, tagSizeReportedByHeader);
//If the audio header is not straight after the end of the tag then search from start of file
if (tagSizeReportedByHeader != ((MP3AudioHeader) audioHeader).getMp3StartByte())
{
logger.config("First header found after tag:" + audioHeader);
audioHeader = checkAudioStart(tagSizeReportedByHeader, (MP3AudioHeader) audioHeader);
}
//Read v1 tags (if any)
readV1Tag(file, newFile, loadOptions);
//Read v2 tags (if any)
readV2Tag(file, loadOptions, (int)((MP3AudioHeader) audioHeader).getMp3StartByte());
//If we have a v2 tag use that, if we do not but have v1 tag use that
//otherwise use nothing
//TODO:if have both should we merge
//rather than just returning specific ID3v22 tag, would it be better to return v24 version ?
if (this.getID3v2Tag() != null)
{
tag = this.getID3v2Tag();
}
else if (id3v1tag != null)
{
tag = id3v1tag;
}
}
finally
{
if (newFile != null)
{
newFile.close();
}
}
}
/**
* Used by tags when writing to calculate the location of the music file
*
* @param file
* @return the location within the file that the audio starts
* @throws java.io.IOException
* @throws org.jaudiotagger.audio.exceptions.InvalidAudioFrameException
*/
public long getMP3StartByte(File file) throws InvalidAudioFrameException, IOException
{
try
{
//Read ID3v2 tag size (if tag exists) to allow audio header parsing to skip over tag
long startByte = AbstractID3v2Tag.getV2TagSizeIfExists(file);
MP3AudioHeader audioHeader = new MP3AudioHeader(file, startByte);
if (startByte != audioHeader.getMp3StartByte())
{
logger.config("First header found after tag:" + audioHeader);
audioHeader = checkAudioStart(startByte, audioHeader);
}
return audioHeader.getMp3StartByte();
}
catch (InvalidAudioFrameException iafe)
{
throw iafe;
}
catch (IOException ioe)
{
throw ioe;
}
}
/**
* Extracts the raw ID3v2 tag data into a file.
*
* This provides access to the raw data before manipulation, the data is written from the start of the file
* to the start of the Audio Data. This is primarily useful for manipulating corrupted tags that are not
* (fully) loaded using the standard methods.
*
* @param outputFile to write the data to
* @return
* @throws TagNotFoundException
* @throws IOException
*/
public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException
{
int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte();
if (startByte >= 0)
{
//Read byte into buffer
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocate(startByte);
fc.read(bb);
//Write bytes to outputFile
FileOutputStream out = new FileOutputStream(outputFile);
out.write(bb.array());
out.close();
fc.close();
fis.close();
return outputFile;
}
throw new TagNotFoundException("There is no ID3v2Tag data in this file");
}
/**
* Return audio header
* @return
*/
public MP3AudioHeader getMP3AudioHeader()
{
return (MP3AudioHeader) getAudioHeader();
}
/**
* Returns true if this datatype contains an <code>Id3v1</code> tag
*
* @return true if this datatype contains an <code>Id3v1</code> tag
*/
public boolean hasID3v1Tag()
{
return (id3v1tag != null);
}
/**
* Returns true if this datatype contains an <code>Id3v2</code> tag
*
* @return true if this datatype contains an <code>Id3v2</code> tag
*/
public boolean hasID3v2Tag()
{
return (id3v2tag != null);
}
/**
* Returns true if this datatype contains a <code>Lyrics3</code> tag
* TODO disabled until Lyrics3 fixed
* @return true if this datatype contains a <code>Lyrics3</code> tag
*/
/*
public boolean hasLyrics3Tag()
{
return (lyrics3tag != null);
}
*/
/**
* Creates a new MP3File datatype and parse the tag from the given file
* Object.
*
* @param file MP3 file
* @throws IOException on any I/O error
* @throws TagException on any exception generated by this library.
* @throws org.jaudiotagger.audio.exceptions.ReadOnlyFileException
* @throws org.jaudiotagger.audio.exceptions.InvalidAudioFrameException
*/
public MP3File(File file) throws IOException, TagException, ReadOnlyFileException, InvalidAudioFrameException
{
this(file, LOAD_ALL);
}
/**
* Sets the ID3v1(_1)tag to the tag provided as an argument.
*
* @param id3v1tag
*/
public void setID3v1Tag(ID3v1Tag id3v1tag)
{
logger.config("setting tagv1:v1 tag");
this.id3v1tag = id3v1tag;
}
public void setID3v1Tag(Tag id3v1tag)
{
logger.config("setting tagv1:v1 tag");
this.id3v1tag = (ID3v1Tag) id3v1tag;
}
/**
* Sets the <code>ID3v1</code> tag for this dataType. A new
* <code>ID3v1_1</code> dataType is created from the argument and then used
* here.
*
* @param mp3tag Any MP3Tag dataType can be used and will be converted into a
* new ID3v1_1 dataType.
*/
public void setID3v1Tag(AbstractTag mp3tag)
{
logger.config("setting tagv1:abstract");
id3v1tag = new ID3v11Tag(mp3tag);
}
/**
* Returns the <code>ID3v1</code> tag for this dataType.
*
* @return the <code>ID3v1</code> tag for this dataType
*/
public ID3v1Tag getID3v1Tag()
{
return id3v1tag;
}
/**
* Sets the <code>ID3v2</code> tag for this dataType. A new
* <code>ID3v2_4</code> dataType is created from the argument and then used
* here.
*
* @param mp3tag Any MP3Tag dataType can be used and will be converted into a
* new ID3v2_4 dataType.
*/
public void setID3v2Tag(AbstractTag mp3tag)
{
id3v2tag = new ID3v24Tag(mp3tag);
}
/**
* Sets the v2 tag to the v2 tag provided as an argument.
* Also store a v24 version of tag as v24 is the interface to be used
* when talking with client applications.
*
* @param id3v2tag
*/
public void setID3v2Tag(AbstractID3v2Tag id3v2tag)
{
this.id3v2tag = id3v2tag;
if (id3v2tag instanceof ID3v24Tag)
{
this.id3v2Asv24tag = (ID3v24Tag) this.id3v2tag;
}
else
{
this.id3v2Asv24tag = new ID3v24Tag(id3v2tag);
}
}
/**
* Set v2 tag ,don't need to set v24 tag because saving
*
* @param id3v2tag
*/
//TODO temp its rather messy
public void setID3v2TagOnly(AbstractID3v2Tag id3v2tag)
{
this.id3v2tag = id3v2tag;
this.id3v2Asv24tag = null;
}
/**
* Returns the <code>ID3v2</code> tag for this datatype.
*
* @return the <code>ID3v2</code> tag for this datatype
*/
public AbstractID3v2Tag getID3v2Tag()
{
return id3v2tag;
}
/**
* @return a representation of tag as v24
*/
public ID3v24Tag getID3v2TagAsv24()
{
return id3v2Asv24tag;
}
/**
* Sets the <code>Lyrics3</code> tag for this dataType. A new
* <code>Lyrics3v2</code> dataType is created from the argument and then
*
* used here.
*
* @param mp3tag Any MP3Tag dataType can be used and will be converted into a
* new Lyrics3v2 dataType.
*/
/*
public void setLyrics3Tag(AbstractTag mp3tag)
{
lyrics3tag = new Lyrics3v2(mp3tag);
}
*/
/**
*
*
* @param lyrics3tag
*/
/*
public void setLyrics3Tag(AbstractLyrics3 lyrics3tag)
{
this.lyrics3tag = lyrics3tag;
}
*/
/**
* Returns the <code>ID3v1</code> tag for this datatype.
*
* @return the <code>ID3v1</code> tag for this datatype
*/
/*
public AbstractLyrics3 getLyrics3Tag()
{
return lyrics3tag;
}
*/
/**
* Remove tag from file
*
* @param mp3tag
* @throws FileNotFoundException
* @throws IOException
*/
public void delete(AbstractTag mp3tag) throws FileNotFoundException, IOException
{
RandomAccessFile raf = new RandomAccessFile(this.file, "rw");
mp3tag.delete(raf);
raf.close();
if(mp3tag instanceof ID3v1Tag)
{
id3v1tag=null;
}
if(mp3tag instanceof AbstractID3v2Tag)
{
id3v2tag=null;
}
}
/**
* Saves the tags in this dataType to the file referred to by this dataType.
*
* @throws IOException on any I/O error
* @throws TagException on any exception generated by this library.
*/
public void save() throws IOException, TagException
{
save(this.file);
}
/**
* Overridden for compatibility with merged code
*
* @throws CannotWriteException
*/
public void commit() throws CannotWriteException
{
try
{
save();
}
catch (IOException ioe)
{
throw new CannotWriteException(ioe);
}
catch (TagException te)
{
throw new CannotWriteException(te);
}
}
/**
* Check can write to file
*
* @param file
* @throws IOException
*/
public void precheck(File file) throws IOException
{
if (!file.exists())
{
logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_NOT_FOUND.getMsg(file.getName()));
throw new IOException(ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_NOT_FOUND.getMsg(file.getName()));
}
if (!file.canWrite())
{
logger.severe(ErrorMessage.GENERAL_WRITE_FAILED.getMsg(file.getName()));
throw new IOException(ErrorMessage.GENERAL_WRITE_FAILED.getMsg(file.getName()));
}
if (file.length() <= MINIMUM_FILESIZE)
{
logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_IS_TOO_SMALL.getMsg(file.getName()));
throw new IOException(ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_IS_TOO_SMALL.getMsg(file.getName()));
}
}
/**
* Saves the tags in this dataType to the file argument. It will be saved as
* TagConstants.MP3_FILE_SAVE_WRITE
*
* @param fileToSave file to save the this dataTypes tags to
* @throws FileNotFoundException if unable to find file
* @throws IOException on any I/O error
*/
public void save(File fileToSave) throws IOException
{
//Ensure we are dealing with absolute filepaths not relative ones
File file = fileToSave.getAbsoluteFile();
logger.config("Saving : " + file.getPath());
//Checks before starting write
precheck(file);
RandomAccessFile rfile = null;
try
{
//ID3v2 Tag
if (TagOptionSingleton.getInstance().isId3v2Save())
{
if (id3v2tag == null)
{
rfile = new RandomAccessFile(file, "rw");
(new ID3v24Tag()).delete(rfile);
(new ID3v23Tag()).delete(rfile);
(new ID3v22Tag()).delete(rfile);
logger.config("Deleting ID3v2 tag:"+file.getName());
rfile.close();
}
else
{
logger.config("Writing ID3v2 tag:"+file.getName());
final MP3AudioHeader mp3AudioHeader = (MP3AudioHeader) this.getAudioHeader();
final long mp3StartByte = mp3AudioHeader.getMp3StartByte();
final long newMp3StartByte = id3v2tag.write(file, mp3StartByte);
if (mp3StartByte != newMp3StartByte) {
logger.config("New mp3 start byte: " + newMp3StartByte);
mp3AudioHeader.setMp3StartByte(newMp3StartByte);
}
}
}
rfile = new RandomAccessFile(file, "rw");
//Lyrics 3 Tag
if (TagOptionSingleton.getInstance().isLyrics3Save())
{
if (lyrics3tag != null)
{
lyrics3tag.write(rfile);
}
}
//ID3v1 tag
if (TagOptionSingleton.getInstance().isId3v1Save())
{
logger.config("Processing ID3v1");
if (id3v1tag == null)
{
logger.config("Deleting ID3v1");
(new ID3v1Tag()).delete(rfile);
}
else
{
logger.config("Saving ID3v1");
id3v1tag.write(rfile);
}
}
}
catch (FileNotFoundException ex)
{
logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_NOT_FOUND.getMsg(file.getName()), ex);
throw ex;
}
catch (IOException iex)
{
logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(file.getName(), iex.getMessage()), iex);
throw iex;
}
catch (RuntimeException re)
{
logger.log(Level.SEVERE, ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(file.getName(), re.getMessage()), re);
throw re;
}
finally
{
if (rfile != null)
{
rfile.close();
}
}
}
/**
* Displays MP3File Structure
*/
public String displayStructureAsXML()
{
createXMLStructureFormatter();
tagFormatter.openHeadingElement("file", this.getFile().getAbsolutePath());
if (this.getID3v1Tag() != null)
{
this.getID3v1Tag().createStructure();
}
if (this.getID3v2Tag() != null)
{
this.getID3v2Tag().createStructure();
}
tagFormatter.closeHeadingElement("file");
return tagFormatter.toString();
}
/**
* Displays MP3File Structure
*/
public String displayStructureAsPlainText()
{
createPlainTextStructureFormatter();
tagFormatter.openHeadingElement("file", this.getFile().getAbsolutePath());
if (this.getID3v1Tag() != null)
{
this.getID3v1Tag().createStructure();
}
if (this.getID3v2Tag() != null)
{
this.getID3v2Tag().createStructure();
}
tagFormatter.closeHeadingElement("file");
return tagFormatter.toString();
}
private static void createXMLStructureFormatter()
{
tagFormatter = new XMLTagDisplayFormatter();
}
private static void createPlainTextStructureFormatter()
{
tagFormatter = new PlainTextTagDisplayFormatter();
}
public static AbstractTagDisplayFormatter getStructureFormatter()
{
return tagFormatter;
}
/**
* Set the Tag
*
* If the parameter tag is a v1tag then the v1 tag is set if v2tag then the v2tag.
*
* @param tag
*/
public void setTag(Tag tag)
{
this.tag = tag;
if (tag instanceof ID3v1Tag)
{
setID3v1Tag((ID3v1Tag) tag);
}
else
{
setID3v2Tag((AbstractID3v2Tag) tag);
}
}
/** Create Default Tag
*
* @return
*/
@Override
public Tag createDefaultTag()
{
if(TagOptionSingleton.getInstance().getID3V2Version()==ID3V2Version.ID3_V24)
{
return new ID3v24Tag();
}
else if(TagOptionSingleton.getInstance().getID3V2Version()==ID3V2Version.ID3_V23)
{
return new ID3v23Tag();
}
else if(TagOptionSingleton.getInstance().getID3V2Version()==ID3V2Version.ID3_V22)
{
return new ID3v22Tag();
}
//Default in case not set somehow
return new ID3v24Tag();
}
/**
* Convert tag from current version to another as specified by id3V2Version
*
* @return
*/
public Tag convertTag(Tag tag, ID3V2Version id3V2Version)
{
if(tag instanceof ID3v24Tag)
{
switch(id3V2Version)
{
case ID3_V22:
return new ID3v22Tag((ID3v24Tag)tag);
case ID3_V23:
return new ID3v23Tag((ID3v24Tag)tag);
case ID3_V24:
return tag;
}
}
else if(tag instanceof ID3v23Tag)
{
switch(id3V2Version)
{
case ID3_V22:
return new ID3v22Tag((ID3v23Tag)tag);
case ID3_V23:
return tag;
case ID3_V24:
return new ID3v24Tag((ID3v23Tag)tag);
}
}
else if(tag instanceof ID3v22Tag)
{
switch(id3V2Version)
{
case ID3_V22:
return tag;
case ID3_V23:
return new ID3v23Tag((ID3v22Tag)tag);
case ID3_V24:
return new ID3v24Tag((ID3v22Tag)tag);
}
}
return tag;
}
/**
* Overidden to only consider ID3v2 Tag
*
* @return
*/
@Override
public Tag getTagOrCreateDefault()
{
Tag tag = getID3v2Tag();
if(tag==null)
{
return createDefaultTag();
}
return tag;
}
/**
* Get the ID3v2 tag and convert to preferred version or if the file doesn't have one at all
* create a default tag of preferred version and set it. The file may already contain a ID3v1 tag but because
* this is not terribly useful the v1tag is not considered for this problem.
*
* @return
*/
@Override
public Tag getTagAndConvertOrCreateAndSetDefault()
{
Tag tag = getTagOrCreateDefault();
tag=convertTag(tag, TagOptionSingleton.getInstance().getID3V2Version());
setTag(tag);
return tag;
}
}
| lgpl-3.0 |
cdman/Java-Lang | lang/src/test/java/net/openhft/lang/io/BigDecimalVsDoubleMain.java | 3807 | /*
* Copyright (C) 2015 higherfrequencytrading.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.openhft.lang.io;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
public class BigDecimalVsDoubleMain {
public static final String[] NUMBER = {"1000000", "1.1", "1.23456", "12345.67890"};
public static final Bytes[] IN_BYTES = new Bytes[NUMBER.length];
public static final Bytes OUT_BYTES;
static {
DirectStore store = new DirectStore((NUMBER.length + 1) * 16);
for (int i = 0; i < NUMBER.length; i++) {
IN_BYTES[i] = store.bytes((i + 1) * 16, 16);
IN_BYTES[i].append(NUMBER[i]);
}
OUT_BYTES = store.bytes(0, 16);
}
static int count = 0;
public static void main(String[] args) throws InterruptedException {
Bytes x = ByteBufferBytes.wrap(ByteBuffer.allocateDirect(16));
x.writeUTFΔ("Hello World");
System.out.println(x);
int runs = 5000;
for (int t = 0; t < 5; t++) {
long timeD = 0;
long timeBD = 0;
long timeB = 0;
if (t == 0)
System.out.println("Warming up");
else if (t == 1)
System.out.println("Cold code");
int r = t == 0 ? 20000 : runs;
for (int i = 0; i < r; i += 3) {
count++;
if (count >= NUMBER.length) count = 0;
if (t > 0)
Thread.sleep(1);
timeB += testDoubleWithBytes();
timeBD += testBigDecimalWithString();
timeD += testDoubleWithString();
if (t > 0)
Thread.sleep(1);
timeD += testDoubleWithString();
timeB += testDoubleWithBytes();
timeBD += testBigDecimalWithString();
if (t > 0)
Thread.sleep(1);
timeBD += testBigDecimalWithString();
timeD += testDoubleWithString();
timeB += testDoubleWithBytes();
}
System.out.printf("double took %.1f us, BigDecimal took %.1f, double with Bytes took %.1f%n",
timeD / 1e3 / r, timeBD / 1e3 / r, timeB / 1e3 / r);
}
}
static volatile double saved;
static volatile String savedStr;
public static long testDoubleWithString() {
long start = System.nanoTime();
saved = Double.parseDouble(NUMBER[count]);
savedStr = Double.toString(saved);
return System.nanoTime() - start;
}
public static long testDoubleWithBytes() {
IN_BYTES[count].position(0);
OUT_BYTES.position(0);
long start = System.nanoTime();
saved = IN_BYTES[count].parseDouble();
OUT_BYTES.append(saved);
System.out.println(OUT_BYTES);
return System.nanoTime() - start;
}
static volatile BigDecimal savedBD;
public static long testBigDecimalWithString() {
long start = System.nanoTime();
savedBD = new BigDecimal(NUMBER[count]);
savedStr = savedBD.toString();
return System.nanoTime() - start;
}
}
| lgpl-3.0 |
ericomattos/javaforce | projects/jffile/src/jffile/JFileBrowserListener.java | 241 | package jffile;
/**
* Created : Aug 14, 2012
*
* @author pquiring
*/
public interface JFileBrowserListener {
public void browserResized(JFileBrowser browser);
public void browserChangedPath(JFileBrowser browser, String newpath);
}
| lgpl-3.0 |
kba/lanterna-old | src/main/java/com/googlecode/lanterna/gui/Container.java | 2555 | /*
* This file is part of lanterna (http://code.google.com/p/lanterna/).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2012 Martin
*/
package com.googlecode.lanterna.gui;
import com.googlecode.lanterna.gui.layout.LayoutParameter;
import com.googlecode.lanterna.gui.listener.ContainerListener;
/**
* This interface must be implemented by any component this is to have
* subcomponents.
* @author Martin
*/
public interface Container extends Component
{
void addContainerListener(ContainerListener cl);
void removeContainerListener(ContainerListener cl);
/**
* Adds a new subcomponent to this container.
* @param component Component to add to this container
* @param layoutParameters Optional parameters to give hits to the layout manager
*/
void addComponent(Component component, LayoutParameter... layoutParameters);
/**
* Removes a component from this container.
* @param component Component to remove from this container
* @return {@code true} if a component was found and removed, {@code false} otherwise
*/
boolean removeComponent(Component component);
/**
* @return How many component this container currently has
*/
int getComponentCount();
/**
* @param index Index to look up a component at
* @return Component at the specified index
*/
Component getComponentAt(int index);
/**
* This method can used to see if a particular component is contained with this objects list of
* immediate children. It will not search through sub-containers, you'll need to do that manually
* if you need this functionality.
* @param component Component to search for
* @return {@code true} is the component is found in this containers list of direct children,
* otherwise {@code false}
*/
boolean containsComponent(Component component);
}
| lgpl-3.0 |
dana-i2cat/mqnaas | core/src/test/java/org/mqnaas/core/impl/samples/SampleResource.java | 1146 | package org.mqnaas.core.impl.samples;
/*
* #%L
* MQNaaS :: Core
* %%
* Copyright (C) 2007 - 2015 Fundació Privada i2CAT, Internet i Innovació a Catalunya
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import org.mqnaas.core.api.IResource;
/**
*
* @author Isart Canyameres Gimenez (i2cat)
*
*/
public class SampleResource implements IResource {
@Override
public String getId() {
return "SampleResource";
}
@Override
public String toString() {
return getId();
}
}
| lgpl-3.0 |
heuermh/genotype-list | gl-client/src/main/java/org/nmdp/gl/client/cache/GlClientLocusCache.java | 1582 | /*
gl-client Client library for the URI-based RESTful service for the gl project.
Copyright (c) 2012-2015 National Marrow Donor Program (NMDP)
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 3 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; with out 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.
> http://www.fsf.org/licensing/licenses/lgpl.html
> http://www.opensource.org/licenses/lgpl-license.php
*/
package org.nmdp.gl.client.cache;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation;
/**
* Gl client locus cache binding annotation.
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface GlClientLocusCache {
// empty
}
| lgpl-3.0 |
RaananW/SharkFW | src/java/core/net/sharkfw/kep/KEPEngine.java | 951 |
package net.sharkfw.kep;
import java.io.IOException;
import net.sharkfw.knowledgeBase.Knowledge;
import net.sharkfw.knowledgeBase.SharkCS;
/**
*
* This interface describes general protocol primitives KEP supports.
*
* @author thsc
* @author mfi
*/
public interface KEPEngine {
/**
* Send the <code>Knowledge</code> k via an insert command
*
* @see net.sharkfw.knowledgeBase.Knowledge
*
* @param k The <code>Knowledge</code> to send
* @param kp The <code>KP</code> from which this command is sent
*/
public void insert(Knowledge k) throws IOException;
/**
* Send the <code>ExposedInterest</code> via an expose command
*
* @see net.sharkfw.knowledgeBase.ExposedInterest
*
* @param exposedInterest The <code>ExposedInterest</code> to send
* @param kp The <code>KP</code> from which this command is sent
*/
public void expose(SharkCS exposedInterest) throws IOException;
}
| lgpl-3.0 |
kiereleaseuser/optaplanner | optaplanner-examples/src/main/java/org/optaplanner/examples/machinereassignment/domain/solver/MrMachineTransientUsage.java | 3016 | /*
* Copyright 2011 JBoss 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.optaplanner.examples.machinereassignment.domain.solver;
import java.io.Serializable;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.optaplanner.core.api.score.constraint.ConstraintMatch;
import org.optaplanner.examples.machinereassignment.domain.MrMachine;
import org.optaplanner.examples.machinereassignment.domain.MrMachineCapacity;
import org.optaplanner.examples.machinereassignment.domain.MrResource;
public class MrMachineTransientUsage implements Serializable, Comparable<MrMachineTransientUsage> {
private MrMachineCapacity machineCapacity;
private long usage;
public MrMachineTransientUsage(MrMachineCapacity machineCapacity, long usage) {
this.machineCapacity = machineCapacity;
this.usage = usage;
}
public MrMachineCapacity getMachineCapacity() {
return machineCapacity;
}
public long getUsage() {
return usage;
}
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof MrMachineTransientUsage) {
MrMachineTransientUsage other = (MrMachineTransientUsage) o;
return new EqualsBuilder()
.append(machineCapacity, other.machineCapacity)
.append(usage, other.usage)
.isEquals();
} else {
return false;
}
}
public int hashCode() {
return new HashCodeBuilder()
.append(machineCapacity)
.append(usage)
.toHashCode();
}
/**
* Used by the GUI to sort the {@link ConstraintMatch} list
* by {@link ConstraintMatch#getJustificationList()}.
* @param other never null
* @return comparison
*/
public int compareTo(MrMachineTransientUsage other) {
return new CompareToBuilder()
.append(machineCapacity, other.machineCapacity)
.append(usage, other.usage)
.toComparison();
}
public MrMachine getMachine() {
return machineCapacity.getMachine();
}
public MrResource getResource() {
return machineCapacity.getResource();
}
@Override
public String toString() {
return getMachine() + "-" + getResource() + "=" + usage;
}
}
| apache-2.0 |
cestella/incubator-metron | metron-platform/metron-indexing/src/main/java/org/apache/metron/indexing/dao/metaalert/MetaAlertUpdateDao.java | 6411 | /*
* 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.metron.indexing.dao.metaalert;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.metron.indexing.dao.search.GetRequest;
import org.apache.metron.indexing.dao.search.InvalidCreateException;
import org.apache.metron.indexing.dao.update.Document;
import org.apache.metron.indexing.dao.update.PatchRequest;
import org.apache.metron.indexing.dao.update.UpdateDao;
public interface MetaAlertUpdateDao extends UpdateDao {
String STATUS_PATH = "/" + MetaAlertConstants.STATUS_FIELD;
String ALERT_PATH = "/" + MetaAlertConstants.ALERT_FIELD;
/**
* Determines if a given patch request is allowed or not. By default patching the 'alert' or
* 'status' fields are not allowed, because they should be updated via the specific methods.
* @param request The patch request to examine
* @return True if patch can be performed, false otherwise
*/
default boolean isPatchAllowed(PatchRequest request) {
if (request.getPatch() != null && !request.getPatch().isEmpty()) {
for (Map<String, Object> patch : request.getPatch()) {
Object pathObj = patch.get("path");
if (pathObj != null && pathObj instanceof String) {
String path = (String) pathObj;
if (STATUS_PATH.equals(path) || ALERT_PATH.equals(path)) {
return false;
}
}
}
}
return true;
}
/**
* Creates a meta alert from a list of child alerts. The most recent version of each child alert is
* retrieved using the DAO abstractions.
*
* @param request A request object containing get requests for alerts to be added and a list of groups
* @return A response indicating success or failure along with the GUID of the new meta alert
* @throws InvalidCreateException If a malformed create request is provided
* @throws IOException If a problem occurs during communication
*/
MetaAlertCreateResponse createMetaAlert(MetaAlertCreateRequest request)
throws InvalidCreateException, IOException;
/**
* Adds alerts to a metaalert, based on a list of GetRequests provided for retrieval.
* @param metaAlertGuid The GUID of the metaalert to be given new children.
* @param alertRequests GetRequests for the appropriate alerts to add.
* @return True if metaalert is modified, false otherwise.
*/
boolean addAlertsToMetaAlert(String metaAlertGuid, List<GetRequest> alertRequests)
throws IOException;
/**
* Removes alerts from a metaalert
* @param metaAlertGuid The metaalert guid to be affected.
* @param alertRequests A list of GetReqests that will provide the alerts to remove
* @return True if there are updates, false otherwise
* @throws IOException If an error is thrown during retrieal.
*/
boolean removeAlertsFromMetaAlert(String metaAlertGuid, List<GetRequest> alertRequests)
throws IOException;
/**
* Removes a metaalert link from a given alert. An nonexistent link performs no change.
* @param metaAlertGuid The metaalert GUID to link.
* @param alert The alert to be linked to.
* @return True if the alert changed, false otherwise.
*/
default boolean removeMetaAlertFromAlert(String metaAlertGuid, Document alert) {
List<String> metaAlertField = new ArrayList<>();
@SuppressWarnings("unchecked")
List<String> alertField = (List<String>) alert.getDocument()
.get(MetaAlertConstants.METAALERT_FIELD);
if (alertField != null) {
metaAlertField.addAll(alertField);
}
boolean metaAlertRemoved = metaAlertField.remove(metaAlertGuid);
if (metaAlertRemoved) {
alert.getDocument().put(MetaAlertConstants.METAALERT_FIELD, metaAlertField);
}
return metaAlertRemoved;
}
/**
* The meta alert status field can be set to either 'active' or 'inactive' and will control whether or not meta alerts
* (and child alerts) appear in search results. An 'active' status will cause meta alerts to appear in search
* results instead of it's child alerts and an 'inactive' status will suppress the meta alert from search results
* with child alerts appearing in search results as normal. A change to 'inactive' will cause the meta alert GUID to
* be removed from all it's child alert's "metaalerts" field. A change back to 'active' will have the opposite effect.
*
* @param metaAlertGuid The GUID of the meta alert
* @param status A status value of 'active' or 'inactive'
* @return True or false depending on if the status was changed
* @throws IOException if an error occurs during the update.
*/
boolean updateMetaAlertStatus(String metaAlertGuid, MetaAlertStatus status)
throws IOException;
/**
* Adds a metaalert link to a provided alert Document. Adding an existing link does no change.
* @param metaAlertGuid The GUID to be added.
* @param alert The alert we're adding the link to.
* @return True if the alert is modified, false if not.
*/
default boolean addMetaAlertToAlert(String metaAlertGuid, Document alert) {
List<String> metaAlertField = new ArrayList<>();
@SuppressWarnings("unchecked")
List<String> alertField = (List<String>) alert.getDocument()
.get(MetaAlertConstants.METAALERT_FIELD);
if (alertField != null) {
metaAlertField.addAll(alertField);
}
boolean metaAlertAdded = !metaAlertField.contains(metaAlertGuid);
if (metaAlertAdded) {
metaAlertField.add(metaAlertGuid);
alert.getDocument().put(MetaAlertConstants.METAALERT_FIELD, metaAlertField);
}
return metaAlertAdded;
}
}
| apache-2.0 |
robin13/elasticsearch | server/src/main/java/org/elasticsearch/action/bulk/TransportShardBulkAction.java | 28011 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.bulk;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.MessageSupplier;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRunnable;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.replication.TransportReplicationAction;
import org.elasticsearch.action.support.replication.TransportWriteAction;
import org.elasticsearch.action.update.UpdateHelper;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateObserver;
import org.elasticsearch.cluster.action.index.MappingUpdatedAction;
import org.elasticsearch.cluster.action.shard.ShardStateAction;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexingPressure;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.index.mapper.MapperException;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.SystemIndices;
import org.elasticsearch.node.NodeClosedException;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.ThreadPool.Names;
import org.elasticsearch.transport.TransportRequestOptions;
import org.elasticsearch.transport.TransportService;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongSupplier;
/** Performs shard-level bulk (index, delete or update) operations */
public class TransportShardBulkAction extends TransportWriteAction<BulkShardRequest, BulkShardRequest, BulkShardResponse> {
public static final String ACTION_NAME = BulkAction.NAME + "[s]";
public static final ActionType<BulkShardResponse> TYPE = new ActionType<>(ACTION_NAME, BulkShardResponse::new);
private static final Logger logger = LogManager.getLogger(TransportShardBulkAction.class);
private static final Function<IndexShard, String> EXECUTOR_NAME_FUNCTION = shard -> {
if (shard.indexSettings().getIndexMetadata().isSystem()) {
return Names.SYSTEM_WRITE;
} else {
return Names.WRITE;
}
};
private final UpdateHelper updateHelper;
private final MappingUpdatedAction mappingUpdatedAction;
@Inject
public TransportShardBulkAction(Settings settings, TransportService transportService, ClusterService clusterService,
IndicesService indicesService, ThreadPool threadPool, ShardStateAction shardStateAction,
MappingUpdatedAction mappingUpdatedAction, UpdateHelper updateHelper, ActionFilters actionFilters,
IndexingPressure indexingPressure, SystemIndices systemIndices) {
super(settings, ACTION_NAME, transportService, clusterService, indicesService, threadPool, shardStateAction, actionFilters,
BulkShardRequest::new, BulkShardRequest::new, EXECUTOR_NAME_FUNCTION, false, indexingPressure, systemIndices);
this.updateHelper = updateHelper;
this.mappingUpdatedAction = mappingUpdatedAction;
}
@Override
protected TransportRequestOptions transportOptions() {
return BulkAction.INSTANCE.transportOptions();
}
@Override
protected BulkShardResponse newResponseInstance(StreamInput in) throws IOException {
return new BulkShardResponse(in);
}
@Override
protected void dispatchedShardOperationOnPrimary(BulkShardRequest request, IndexShard primary,
ActionListener<PrimaryResult<BulkShardRequest, BulkShardResponse>> listener) {
ClusterStateObserver observer = new ClusterStateObserver(clusterService, request.timeout(), logger, threadPool.getThreadContext());
performOnPrimary(request, primary, updateHelper, threadPool::absoluteTimeInMillis,
(update, shardId, mappingListener) -> {
assert update != null;
assert shardId != null;
mappingUpdatedAction.updateMappingOnMaster(shardId.getIndex(), update, mappingListener);
},
mappingUpdateListener -> observer.waitForNextChange(new ClusterStateObserver.Listener() {
@Override
public void onNewClusterState(ClusterState state) {
mappingUpdateListener.onResponse(null);
}
@Override
public void onClusterServiceClose() {
mappingUpdateListener.onFailure(new NodeClosedException(clusterService.localNode()));
}
@Override
public void onTimeout(TimeValue timeout) {
mappingUpdateListener.onFailure(new MapperException("timed out while waiting for a dynamic mapping update"));
}
}), listener, threadPool, executor(primary)
);
}
@Override
protected long primaryOperationSize(BulkShardRequest request) {
return request.ramBytesUsed();
}
@Override
protected int primaryOperationCount(BulkShardRequest request) {
return request.items().length;
}
public static void performOnPrimary(
BulkShardRequest request,
IndexShard primary,
UpdateHelper updateHelper,
LongSupplier nowInMillisSupplier,
MappingUpdatePerformer mappingUpdater,
Consumer<ActionListener<Void>> waitForMappingUpdate,
ActionListener<PrimaryResult<BulkShardRequest, BulkShardResponse>> listener,
ThreadPool threadPool,
String executorName) {
new ActionRunnable<>(listener) {
private final Executor executor = threadPool.executor(executorName);
private final BulkPrimaryExecutionContext context = new BulkPrimaryExecutionContext(request, primary);
final long startBulkTime = System.nanoTime();
@Override
protected void doRun() throws Exception {
while (context.hasMoreOperationsToExecute()) {
if (executeBulkItemRequest(context, updateHelper, nowInMillisSupplier, mappingUpdater, waitForMappingUpdate,
ActionListener.wrap(v -> executor.execute(this), this::onRejection)) == false) {
// We are waiting for a mapping update on another thread, that will invoke this action again once its done
// so we just break out here.
return;
}
assert context.isInitial(); // either completed and moved to next or reset
}
primary.getBulkOperationListener().afterBulk(request.totalSizeInBytes(), System.nanoTime() - startBulkTime);
// We're done, there's no more operations to execute so we resolve the wrapped listener
finishRequest();
}
@Override
public void onRejection(Exception e) {
// We must finish the outstanding request. Finishing the outstanding request can include
//refreshing and fsyncing. Therefore, we must force execution on the WRITE thread.
executor.execute(new ActionRunnable<>(listener) {
@Override
protected void doRun() {
// Fail all operations after a bulk rejection hit an action that waited for a mapping update and finish the request
while (context.hasMoreOperationsToExecute()) {
context.setRequestToExecute(context.getCurrent());
final DocWriteRequest<?> docWriteRequest = context.getRequestToExecute();
onComplete(
exceptionToResult(
e, primary, docWriteRequest.opType() == DocWriteRequest.OpType.DELETE, docWriteRequest.version()),
context, null);
}
finishRequest();
}
@Override
public boolean isForceExecution() {
return true;
}
});
}
private void finishRequest() {
ActionListener.completeWith(listener,
() -> new WritePrimaryResult<>(
context.getBulkShardRequest(), context.buildShardResponse(), context.getLocationToSync(), null,
context.getPrimary(), logger));
}
}.run();
}
/**
* Executes bulk item requests and handles request execution exceptions.
* @return {@code true} if request completed on this thread and the listener was invoked, {@code false} if the request triggered
* a mapping update that will finish and invoke the listener on a different thread
*/
static boolean executeBulkItemRequest(BulkPrimaryExecutionContext context, UpdateHelper updateHelper, LongSupplier nowInMillisSupplier,
MappingUpdatePerformer mappingUpdater, Consumer<ActionListener<Void>> waitForMappingUpdate,
ActionListener<Void> itemDoneListener) throws Exception {
final DocWriteRequest.OpType opType = context.getCurrent().opType();
final UpdateHelper.Result updateResult;
if (opType == DocWriteRequest.OpType.UPDATE) {
final UpdateRequest updateRequest = (UpdateRequest) context.getCurrent();
try {
updateResult = updateHelper.prepare(updateRequest, context.getPrimary(), nowInMillisSupplier);
} catch (Exception failure) {
// we may fail translating a update to index or delete operation
// we use index result to communicate failure while translating update request
final Engine.Result result =
new Engine.IndexResult(failure, updateRequest.version());
context.setRequestToExecute(updateRequest);
context.markOperationAsExecuted(result);
context.markAsCompleted(context.getExecutionResult());
return true;
}
// execute translated update request
switch (updateResult.getResponseResult()) {
case CREATED:
case UPDATED:
IndexRequest indexRequest = updateResult.action();
IndexMetadata metadata = context.getPrimary().indexSettings().getIndexMetadata();
MappingMetadata mappingMd = metadata.mapping();
indexRequest.process(metadata.getCreationVersion(), mappingMd, updateRequest.concreteIndex());
context.setRequestToExecute(indexRequest);
break;
case DELETED:
context.setRequestToExecute(updateResult.action());
break;
case NOOP:
context.markOperationAsNoOp(updateResult.action());
context.markAsCompleted(context.getExecutionResult());
return true;
default:
throw new IllegalStateException("Illegal update operation " + updateResult.getResponseResult());
}
} else {
context.setRequestToExecute(context.getCurrent());
updateResult = null;
}
assert context.getRequestToExecute() != null; // also checks that we're in TRANSLATED state
final IndexShard primary = context.getPrimary();
final long version = context.getRequestToExecute().version();
final boolean isDelete = context.getRequestToExecute().opType() == DocWriteRequest.OpType.DELETE;
final Engine.Result result;
if (isDelete) {
final DeleteRequest request = context.getRequestToExecute();
result = primary.applyDeleteOperationOnPrimary(version, request.id(), request.versionType(),
request.ifSeqNo(), request.ifPrimaryTerm());
} else {
final IndexRequest request = context.getRequestToExecute();
final SourceToParse sourceToParse = new SourceToParse(request.index(), request.id(), request.source(),
request.getContentType(), request.routing(), request.getDynamicTemplates());
result = primary.applyIndexOperationOnPrimary(version, request.versionType(), sourceToParse,
request.ifSeqNo(), request.ifPrimaryTerm(), request.getAutoGeneratedTimestamp(), request.isRetry());
}
if (result.getResultType() == Engine.Result.Type.MAPPING_UPDATE_REQUIRED) {
try {
primary.mapperService().merge(MapperService.SINGLE_MAPPING_NAME,
new CompressedXContent(result.getRequiredMappingUpdate(), XContentType.JSON, ToXContent.EMPTY_PARAMS),
MapperService.MergeReason.MAPPING_UPDATE_PREFLIGHT);
} catch (Exception e) {
logger.info(() -> new ParameterizedMessage("{} mapping update rejected by primary", primary.shardId()), e);
onComplete(exceptionToResult(e, primary, isDelete, version), context, updateResult);
return true;
}
mappingUpdater.updateMappings(result.getRequiredMappingUpdate(), primary.shardId(),
new ActionListener<>() {
@Override
public void onResponse(Void v) {
context.markAsRequiringMappingUpdate();
waitForMappingUpdate.accept(
ActionListener.runAfter(new ActionListener<>() {
@Override
public void onResponse(Void v) {
assert context.requiresWaitingForMappingUpdate();
context.resetForExecutionForRetry();
}
@Override
public void onFailure(Exception e) {
context.failOnMappingUpdate(e);
}
}, () -> itemDoneListener.onResponse(null))
);
}
@Override
public void onFailure(Exception e) {
onComplete(exceptionToResult(e, primary, isDelete, version), context, updateResult);
// Requesting mapping update failed, so we don't have to wait for a cluster state update
assert context.isInitial();
itemDoneListener.onResponse(null);
}
});
return false;
} else {
onComplete(result, context, updateResult);
}
return true;
}
private static Engine.Result exceptionToResult(Exception e, IndexShard primary, boolean isDelete, long version) {
return isDelete ? primary.getFailedDeleteResult(e, version) : primary.getFailedIndexResult(e, version);
}
private static void onComplete(Engine.Result r, BulkPrimaryExecutionContext context, UpdateHelper.Result updateResult) {
context.markOperationAsExecuted(r);
final DocWriteRequest<?> docWriteRequest = context.getCurrent();
final DocWriteRequest.OpType opType = docWriteRequest.opType();
final boolean isUpdate = opType == DocWriteRequest.OpType.UPDATE;
final BulkItemResponse executionResult = context.getExecutionResult();
final boolean isFailed = executionResult.isFailed();
if (isUpdate && isFailed && isConflictException(executionResult.getFailure().getCause())
&& context.getRetryCounter() < ((UpdateRequest) docWriteRequest).retryOnConflict()) {
context.resetForExecutionForRetry();
return;
}
final BulkItemResponse response;
if (isUpdate) {
response = processUpdateResponse((UpdateRequest) docWriteRequest, context.getConcreteIndex(), executionResult, updateResult);
} else {
if (isFailed) {
final Exception failure = executionResult.getFailure().getCause();
final MessageSupplier messageSupplier = () -> new ParameterizedMessage("{} failed to execute bulk item ({}) {}",
context.getPrimary().shardId(), opType.getLowercase(), docWriteRequest);
if (TransportShardBulkAction.isConflictException(failure)) {
logger.trace(messageSupplier, failure);
} else {
logger.debug(messageSupplier, failure);
}
}
response = executionResult;
}
context.markAsCompleted(response);
assert context.isInitial();
}
private static boolean isConflictException(final Exception e) {
return ExceptionsHelper.unwrapCause(e) instanceof VersionConflictEngineException;
}
/**
* Creates a new bulk item result from the given requests and result of performing the update operation on the shard.
*/
private static BulkItemResponse processUpdateResponse(final UpdateRequest updateRequest, final String concreteIndex,
BulkItemResponse operationResponse, final UpdateHelper.Result translate) {
final BulkItemResponse response;
if (operationResponse.isFailed()) {
response = new BulkItemResponse(operationResponse.getItemId(), DocWriteRequest.OpType.UPDATE, operationResponse.getFailure());
} else {
final DocWriteResponse.Result translatedResult = translate.getResponseResult();
final UpdateResponse updateResponse;
if (translatedResult == DocWriteResponse.Result.CREATED || translatedResult == DocWriteResponse.Result.UPDATED) {
final IndexRequest updateIndexRequest = translate.action();
final IndexResponse indexResponse = operationResponse.getResponse();
updateResponse = new UpdateResponse(indexResponse.getShardInfo(), indexResponse.getShardId(),
indexResponse.getId(), indexResponse.getSeqNo(), indexResponse.getPrimaryTerm(),
indexResponse.getVersion(), indexResponse.getResult());
if (updateRequest.fetchSource() != null && updateRequest.fetchSource().fetchSource()) {
final BytesReference indexSourceAsBytes = updateIndexRequest.source();
final Tuple<XContentType, Map<String, Object>> sourceAndContent =
XContentHelper.convertToMap(indexSourceAsBytes, true, updateIndexRequest.getContentType());
updateResponse.setGetResult(UpdateHelper.extractGetResult(updateRequest, concreteIndex,
indexResponse.getSeqNo(), indexResponse.getPrimaryTerm(),
indexResponse.getVersion(), sourceAndContent.v2(), sourceAndContent.v1(), indexSourceAsBytes));
}
} else if (translatedResult == DocWriteResponse.Result.DELETED) {
final DeleteResponse deleteResponse = operationResponse.getResponse();
updateResponse = new UpdateResponse(deleteResponse.getShardInfo(), deleteResponse.getShardId(),
deleteResponse.getId(), deleteResponse.getSeqNo(), deleteResponse.getPrimaryTerm(),
deleteResponse.getVersion(), deleteResponse.getResult());
final GetResult getResult = UpdateHelper.extractGetResult(updateRequest, concreteIndex,
deleteResponse.getSeqNo(), deleteResponse.getPrimaryTerm(), deleteResponse.getVersion(),
translate.updatedSourceAsMap(), translate.updateSourceContentType(), null);
updateResponse.setGetResult(getResult);
} else {
throw new IllegalArgumentException("unknown operation type: " + translatedResult);
}
response = new BulkItemResponse(operationResponse.getItemId(), DocWriteRequest.OpType.UPDATE, updateResponse);
}
return response;
}
@Override
protected void dispatchedShardOperationOnReplica(BulkShardRequest request, IndexShard replica, ActionListener<ReplicaResult> listener) {
ActionListener.completeWith(listener, () -> {
final long startBulkTime = System.nanoTime();
final Translog.Location location = performOnReplica(request, replica);
replica.getBulkOperationListener().afterBulk(request.totalSizeInBytes(), System.nanoTime() - startBulkTime);
return new WriteReplicaResult<>(request, location, null, replica, logger);
});
}
@Override
protected long replicaOperationSize(BulkShardRequest request) {
return request.ramBytesUsed();
}
@Override
protected int replicaOperationCount(BulkShardRequest request) {
return request.items().length;
}
public static Translog.Location performOnReplica(BulkShardRequest request, IndexShard replica) throws Exception {
Translog.Location location = null;
for (int i = 0; i < request.items().length; i++) {
final BulkItemRequest item = request.items()[i];
final BulkItemResponse response = item.getPrimaryResponse();
final Engine.Result operationResult;
if (item.getPrimaryResponse().isFailed()) {
if (response.getFailure().getSeqNo() == SequenceNumbers.UNASSIGNED_SEQ_NO) {
continue; // ignore replication as we didn't generate a sequence number for this request.
}
final long primaryTerm;
if (response.getFailure().getTerm() == SequenceNumbers.UNASSIGNED_PRIMARY_TERM) {
// primary is on older version, just take the current primary term
primaryTerm = replica.getOperationPrimaryTerm();
} else {
primaryTerm = response.getFailure().getTerm();
}
operationResult = replica.markSeqNoAsNoop(response.getFailure().getSeqNo(), primaryTerm,
response.getFailure().getMessage());
} else {
if (response.getResponse().getResult() == DocWriteResponse.Result.NOOP) {
continue; // ignore replication as it's a noop
}
assert response.getResponse().getSeqNo() != SequenceNumbers.UNASSIGNED_SEQ_NO;
operationResult = performOpOnReplica(response.getResponse(), item.request(), replica);
}
assert operationResult != null : "operation result must never be null when primary response has no failure";
location = syncOperationResultOrThrow(operationResult, location);
}
return location;
}
private static Engine.Result performOpOnReplica(DocWriteResponse primaryResponse, DocWriteRequest<?> docWriteRequest,
IndexShard replica) throws Exception {
final Engine.Result result;
switch (docWriteRequest.opType()) {
case CREATE:
case INDEX:
final IndexRequest indexRequest = (IndexRequest) docWriteRequest;
final ShardId shardId = replica.shardId();
final SourceToParse sourceToParse = new SourceToParse(shardId.getIndexName(), indexRequest.id(), indexRequest.source(),
indexRequest.getContentType(), indexRequest.routing(), Map.of());
result = replica.applyIndexOperationOnReplica(primaryResponse.getSeqNo(), primaryResponse.getPrimaryTerm(),
primaryResponse.getVersion(), indexRequest.getAutoGeneratedTimestamp(), indexRequest.isRetry(), sourceToParse);
break;
case DELETE:
DeleteRequest deleteRequest = (DeleteRequest) docWriteRequest;
result = replica.applyDeleteOperationOnReplica(primaryResponse.getSeqNo(), primaryResponse.getPrimaryTerm(),
primaryResponse.getVersion(), deleteRequest.id());
break;
default:
assert false : "Unexpected request operation type on replica: " + docWriteRequest + ";primary result: " + primaryResponse;
throw new IllegalStateException("Unexpected request operation type on replica: " + docWriteRequest.opType().getLowercase());
}
if (result.getResultType() == Engine.Result.Type.MAPPING_UPDATE_REQUIRED) {
// Even though the primary waits on all nodes to ack the mapping changes to the master
// (see MappingUpdatedAction.updateMappingOnMaster) we still need to protect against missing mappings
// and wait for them. The reason is concurrent requests. Request r1 which has new field f triggers a
// mapping update. Assume that that update is first applied on the primary, and only later on the replica
// (it’s happening concurrently). Request r2, which now arrives on the primary and which also has the new
// field f might see the updated mapping (on the primary), and will therefore proceed to be replicated
// to the replica. When it arrives on the replica, there’s no guarantee that the replica has already
// applied the new mapping, so there is no other option than to wait.
throw new TransportReplicationAction.RetryOnReplicaException(replica.shardId(),
"Mappings are not available on the replica yet, triggered update: " + result.getRequiredMappingUpdate());
}
return result;
}
}
| apache-2.0 |
SnappyDataInc/snappy-store | gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/catalog/GfxdSYSDISKSTORESRowFactory.java | 8050 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.impl.sql.catalog;
import java.sql.Types;
import com.pivotal.gemfirexd.internal.catalog.UUID;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.iapi.services.uuid.UUIDFactory;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.CatalogRowFactory;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.DataDictionary;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.GfxdDiskStoreDescriptor;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.SystemColumn;
import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.TupleDescriptor;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecutionFactory;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueFactory;
import com.pivotal.gemfirexd.internal.iapi.types.SQLChar;
import com.pivotal.gemfirexd.internal.iapi.types.SQLInteger;
import com.pivotal.gemfirexd.internal.iapi.types.SQLLongint;
import com.pivotal.gemfirexd.internal.iapi.types.SQLVarchar;
/**
*
* @author Asif
*
*/
public class GfxdSYSDISKSTORESRowFactory extends CatalogRowFactory
{
public static final String TABLENAME_STRING = "SYSDISKSTORES";
public static final int SYSDISKSTORES_COLUMN_COUNT = 9;
public static final int SYSDISKSTORES_NAME = 1;
public static final int SYSDISKSTORES_MAXLOGSIZE = 2;
public static final int SYSDISKSTORES_AUTOCOMPACT = 3;
public static final int SYSDISKSTORES_ALLOWFORCECOMPACTION = 4;
public static final int SYSDISKSTORES_COMPACTIONTHRESHOLD = 5;
public static final int SYSDISKSTORES_TIMEINTERVAL = 6;
public static final int SYSDISKSTORES_WRITEBUFFERSIZE = 7;
public static final int SYSDISKSTORES_QUEUESIZE = 8;
public static final int SYSDISKSTORES_DIR_PATH_SIZE = 9;
private static final int[][] indexColumnPositions = { { SYSDISKSTORES_NAME } };
// if you add a non-unique index allocate this array.
private static final boolean[] uniqueness = null;
private static final String[] uuids = {
"a073400e-00b6-fdfc-71ce-000b0a763800" // catalog UUID
, "a073400e-00b6-fbba-75d4-000b0a763800" // heap UUID
, "a073400e-00b6-00b9-bbde-000b0a763800" // SYSDISKSTORES_INDEX1
};
// ///////////////////////////////////////////////////////////////////////////
//
// CONSTRUCTORS
//
// ///////////////////////////////////////////////////////////////////////////
GfxdSYSDISKSTORESRowFactory(UUIDFactory uuidf, ExecutionFactory ef,
DataValueFactory dvf) {
super(uuidf, ef, dvf);
initInfo(SYSDISKSTORES_COLUMN_COUNT, TABLENAME_STRING,
indexColumnPositions, uniqueness, uuids);
}
public ExecRow makeRow(TupleDescriptor td, TupleDescriptor parent)
throws StandardException
{
ExecRow row;
UUID uuid = null;
String diskStoreName = null;
long maxLogSize = -1;
String autoCompact = null;
String allowForceCompaction = null;
int compactionThreshold = -1;
long timeInterval = -1;
int writeBufferSize = -1;
int queueSize = -1;
String dirPathSize = null;
if (td != null) {
GfxdDiskStoreDescriptor dsd = (GfxdDiskStoreDescriptor)td;
diskStoreName = dsd.getDiskStoreName();
uuid = dsd.getUUID();
maxLogSize = dsd.getMaxLogSize();
autoCompact = dsd.getAutocompact();
allowForceCompaction = dsd.getAllowForceCompaction();
compactionThreshold = dsd.getCompactionThreshold();
timeInterval = dsd.getTimeInterval();
writeBufferSize = dsd.getWriteBufferSize();
queueSize = dsd.getQueueSize();
dirPathSize = dsd.getDirPathAndSize();
}
/* Build the row to insert */
row = getExecutionFactory().getValueRow(SYSDISKSTORES_COLUMN_COUNT);
/* 1st column is diskstorename */
row.setColumn(1, new SQLChar(diskStoreName));
/* 2nd column is logsize */
row.setColumn(2, new SQLLongint(maxLogSize));
/* 3rd column is autocompact */
row.setColumn(3, new SQLVarchar(autoCompact));
/* 4th column is allowforcecompaction */
row.setColumn(4, new SQLVarchar(allowForceCompaction));
/* 5th column is compactionthreshold */
row.setColumn(5, new SQLInteger(compactionThreshold));
/* 6th column is TimeInterval */
row.setColumn(6, new SQLLongint(timeInterval));
/* 7th column is writeBufferSize */
row.setColumn(7, new SQLInteger(writeBufferSize));
/* 8th column is QueueSize */
row.setColumn(8, new SQLInteger(queueSize));
/* 9th column is Dircetion paths and sizes */
row.setColumn(9, new SQLVarchar(dirPathSize));
return row;
}
public TupleDescriptor buildDescriptor(ExecRow row,
TupleDescriptor parentDesc, DataDictionary dd) throws StandardException
{
if (SanityManager.DEBUG) {
SanityManager.ASSERT(row.nColumns() == SYSDISKSTORES_COLUMN_COUNT,
"Wrong number of columns for a SYSDISKSTORES row");
}
DataValueDescriptor col;
UUID id;
UUIDFactory uuidFactory = getUUIDFactory();
col = row.getColumn(SYSDISKSTORES_NAME);
String diskStoreName = col.getString();
id = getUUIDFactory().recreateUUID(diskStoreName);
col = row.getColumn(SYSDISKSTORES_MAXLOGSIZE);
int maxLogSize = col.getInt();
col = row.getColumn(SYSDISKSTORES_AUTOCOMPACT);
String autoCompact = col.getString();
col = row.getColumn(SYSDISKSTORES_ALLOWFORCECOMPACTION);
String allowForceCompact = col.getString();
col = row.getColumn(SYSDISKSTORES_COMPACTIONTHRESHOLD);
int comapctionThreshold = col.getInt();
col = row.getColumn(SYSDISKSTORES_TIMEINTERVAL);
int timeInterval = col.getInt();
col = row.getColumn(SYSDISKSTORES_WRITEBUFFERSIZE);
int writeBufferSize = col.getInt();
col = row.getColumn(SYSDISKSTORES_QUEUESIZE);
int queueSize = col.getInt();
col = row.getColumn(SYSDISKSTORES_DIR_PATH_SIZE);
String dirPathAndSize = col.getString();
return new GfxdDiskStoreDescriptor(dd, id, diskStoreName, maxLogSize,
autoCompact, allowForceCompact, comapctionThreshold, timeInterval,
writeBufferSize, queueSize, dirPathAndSize);
}
/**
* Builds a list of columns suitable for creating this Catalog.
*
*
* @return array of SystemColumn suitable for making this catalog.
*/
public SystemColumn[] buildColumnList()
{
return new SystemColumn[] {
SystemColumnImpl.getIdentifierColumn("NAME", false),
// SystemColumnImpl.getIndicatorColumn("LOCKGRANULARITY"),
// SystemColumnImpl.getIdentifierColumn("SERVERGROUPS", false),
SystemColumnImpl.getColumn("MAXLOGSIZE", Types.BIGINT, false),
SystemColumnImpl.getColumn("AUTOCOMPACT", Types.VARCHAR, false,6),
SystemColumnImpl.getColumn("ALLOWFORCECOMPACTION", Types.VARCHAR, false,6),
SystemColumnImpl.getColumn("COMPACTIONTHRESHOLD", Types.INTEGER, false,3),
SystemColumnImpl.getColumn("TIMEINTERVAL", Types.BIGINT, false),
SystemColumnImpl.getColumn("WRITEBUFFERSIZE", Types.INTEGER, false),
SystemColumnImpl.getColumn("QUEUESIZE", Types.INTEGER, false),
SystemColumnImpl.getColumn("DIR_PATH_SIZE", Types.VARCHAR, false)};
}
}
| apache-2.0 |
marcrh/gwt-material | gwt-material/src/main/java/gwt/material/design/client/constants/DatePickerLanguage.java | 4724 | /*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2017 GwtMaterialDesign
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package gwt.material.design.client.constants;
import com.google.gwt.resources.client.TextResource;
import gwt.material.design.client.resources.MaterialDatePickerClientBundle;
/**
* Language List of DatePicker - contains 43 supported languages
*
* @author kevzlou7979
*/
public enum DatePickerLanguage {
AR("ar", "Arabic", MaterialDatePickerClientBundle.INSTANCE.ar()),
BG("bg_BG", "Bulgarian", MaterialDatePickerClientBundle.INSTANCE.bg()),
BS("bs_BA", "Bosnian", MaterialDatePickerClientBundle.INSTANCE.bs()),
CA("ca_ES", "Catalan", MaterialDatePickerClientBundle.INSTANCE.ca()),
CS("cs_CZ", "Czech", MaterialDatePickerClientBundle.INSTANCE.cs()),
DA("da_DK", "Danish", MaterialDatePickerClientBundle.INSTANCE.da()),
DE("de_DE", "German", MaterialDatePickerClientBundle.INSTANCE.de()),
EL("el_GR", "Greek", MaterialDatePickerClientBundle.INSTANCE.el()),
EN("en", "English", MaterialDatePickerClientBundle.INSTANCE.en()),
ES("es_ES", "Spanish", MaterialDatePickerClientBundle.INSTANCE.es()),
ET("et_EE", "Estonian", MaterialDatePickerClientBundle.INSTANCE.et()),
EU("eu_ES", "Basque", MaterialDatePickerClientBundle.INSTANCE.eu()),
FA("fa_ir", "Farsi", MaterialDatePickerClientBundle.INSTANCE.fa()),
FI("fi_FI", "Finnish", MaterialDatePickerClientBundle.INSTANCE.fi()),
FR("fr_FR", "French", MaterialDatePickerClientBundle.INSTANCE.fr()),
GL("gl_ES", "Galician", MaterialDatePickerClientBundle.INSTANCE.gl()),
HE("he_IL", "Hebrew", MaterialDatePickerClientBundle.INSTANCE.he()),
HI("hi_IN", "Hindi", MaterialDatePickerClientBundle.INSTANCE.hi()),
HR("hr_HR", "Croatian", MaterialDatePickerClientBundle.INSTANCE.hr()),
HU("hu_HU", "Hungarian", MaterialDatePickerClientBundle.INSTANCE.hu()),
ID("id_ID", "Indonesian", MaterialDatePickerClientBundle.INSTANCE.id()),
IS("is_IS", "Icelandic", MaterialDatePickerClientBundle.INSTANCE.is()),
IT("it_IT", "Italian", MaterialDatePickerClientBundle.INSTANCE.it()),
JA("ja_JP", "Japanese", MaterialDatePickerClientBundle.INSTANCE.ja()),
KO("ko_KR", "Korean", MaterialDatePickerClientBundle.INSTANCE.ko()),
LT("lt_LT", "Lietuviškai", MaterialDatePickerClientBundle.INSTANCE.lt()),
LV("lv_LV", "Latvian", MaterialDatePickerClientBundle.INSTANCE.lv()),
NB("nb_NO", "Norwegian", MaterialDatePickerClientBundle.INSTANCE.nb()),
NE("ne_NP", "Nepali", MaterialDatePickerClientBundle.INSTANCE.ne()),
NL("nl_NL", "Dutch", MaterialDatePickerClientBundle.INSTANCE.nl()),
PL("pl_PL", "Polish", MaterialDatePickerClientBundle.INSTANCE.pl()),
PT_br("pt_BR", "Brazilian Portuguese", MaterialDatePickerClientBundle.INSTANCE.pt_BR()),
PT_PT("pt_PT", "Portuguese", MaterialDatePickerClientBundle.INSTANCE.pt_PT()),
RO("ro_RO", "Romanian", MaterialDatePickerClientBundle.INSTANCE.ro()),
RU("ru_RU", "Russian", MaterialDatePickerClientBundle.INSTANCE.ru()),
SK("sk_SK", "Slovak", MaterialDatePickerClientBundle.INSTANCE.sk()),
SL("sl_SI", "Slovenian", MaterialDatePickerClientBundle.INSTANCE.sl()),
SV("sv_SE", "Swedish", MaterialDatePickerClientBundle.INSTANCE.sv()),
TH("th_TH", "Thai", MaterialDatePickerClientBundle.INSTANCE.th()),
TR("tr_TR", "Turkish", MaterialDatePickerClientBundle.INSTANCE.tr()),
UK("uk_UA", "Ukrainian", MaterialDatePickerClientBundle.INSTANCE.uk()),
VI("vi_VN", "Vietnamese", MaterialDatePickerClientBundle.INSTANCE.vi()),
ZH_CN("zh_CN", "Simplified Chinese", MaterialDatePickerClientBundle.INSTANCE.zh_CN()),
ZH_TW("zh_TW", "Traditional Chinese", MaterialDatePickerClientBundle.INSTANCE.zh_TW());
private final String code;
private final String name;
private final TextResource js;
DatePickerLanguage(final String code, final String name, final TextResource js) {
this.code = code;
this.name = name;
this.js = js;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public TextResource getJs() {
return js;
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-elastictranscoder/src/main/java/com/amazonaws/services/elastictranscoder/model/transform/ThumbnailsJsonUnmarshaller.java | 4644 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elastictranscoder.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;
import com.amazonaws.services.elastictranscoder.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* Thumbnails JSON Unmarshaller
*/
public class ThumbnailsJsonUnmarshaller implements
Unmarshaller<Thumbnails, JsonUnmarshallerContext> {
public Thumbnails unmarshall(JsonUnmarshallerContext context)
throws Exception {
Thumbnails thumbnails = new Thumbnails();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Format", targetDepth)) {
context.nextToken();
thumbnails.setFormat(context.getUnmarshaller(String.class)
.unmarshall(context));
}
if (context.testExpression("Interval", targetDepth)) {
context.nextToken();
thumbnails.setInterval(context
.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Resolution", targetDepth)) {
context.nextToken();
thumbnails.setResolution(context.getUnmarshaller(
String.class).unmarshall(context));
}
if (context.testExpression("AspectRatio", targetDepth)) {
context.nextToken();
thumbnails.setAspectRatio(context.getUnmarshaller(
String.class).unmarshall(context));
}
if (context.testExpression("MaxWidth", targetDepth)) {
context.nextToken();
thumbnails.setMaxWidth(context
.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("MaxHeight", targetDepth)) {
context.nextToken();
thumbnails.setMaxHeight(context.getUnmarshaller(
String.class).unmarshall(context));
}
if (context.testExpression("SizingPolicy", targetDepth)) {
context.nextToken();
thumbnails.setSizingPolicy(context.getUnmarshaller(
String.class).unmarshall(context));
}
if (context.testExpression("PaddingPolicy", targetDepth)) {
context.nextToken();
thumbnails.setPaddingPolicy(context.getUnmarshaller(
String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return thumbnails;
}
private static ThumbnailsJsonUnmarshaller instance;
public static ThumbnailsJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ThumbnailsJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
zstackio/zstack | sdk/src/main/java/org/zstack/sdk/UpdateConsoleProxyAgentAction.java | 3084 | package org.zstack.sdk;
import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;
public class UpdateConsoleProxyAgentAction extends AbstractAction {
private static final HashMap<String, Parameter> parameterMap = new HashMap<>();
private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();
public static class Result {
public ErrorCode error;
public org.zstack.sdk.UpdateConsoleProxyAgentResult value;
public Result throwExceptionIfError() {
if (error != null) {
throw new ApiException(
String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
);
}
return this;
}
}
@Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String uuid;
@Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String consoleProxyOverriddenIp;
@Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public int consoleProxyPort = 0;
@Param(required = false)
public java.util.List systemTags;
@Param(required = false)
public java.util.List userTags;
@Param(required = false)
public String sessionId;
@Param(required = false)
public String accessKeyId;
@Param(required = false)
public String accessKeySecret;
@Param(required = false)
public String requestIp;
@NonAPIParam
public long timeout = -1;
@NonAPIParam
public long pollingInterval = -1;
private Result makeResult(ApiResult res) {
Result ret = new Result();
if (res.error != null) {
ret.error = res.error;
return ret;
}
org.zstack.sdk.UpdateConsoleProxyAgentResult value = res.getResult(org.zstack.sdk.UpdateConsoleProxyAgentResult.class);
ret.value = value == null ? new org.zstack.sdk.UpdateConsoleProxyAgentResult() : value;
return ret;
}
public Result call() {
ApiResult res = ZSClient.call(this);
return makeResult(res);
}
public void call(final Completion<Result> completion) {
ZSClient.call(this, new InternalCompletion() {
@Override
public void complete(ApiResult res) {
completion.complete(makeResult(res));
}
});
}
protected Map<String, Parameter> getParameterMap() {
return parameterMap;
}
protected Map<String, Parameter> getNonAPIParameterMap() {
return nonAPIParameterMap;
}
protected RestInfo getRestInfo() {
RestInfo info = new RestInfo();
info.httpMethod = "PUT";
info.path = "/consoles/agents/{uuid}/actions";
info.needSession = true;
info.needPoll = true;
info.parameterName = "updateConsoleProxyAgent";
return info;
}
}
| apache-2.0 |
line/armeria | oauth2/src/main/java/com/linecorp/armeria/server/auth/oauth2/OAuth2TokenScopeValidator.java | 4801 | /*
* Copyright 2021 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.server.auth.oauth2;
import static com.linecorp.armeria.server.auth.oauth2.OAuth2AuthorizationErrorReporter.forbidden;
import static java.util.Objects.requireNonNull;
import java.util.Set;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.auth.oauth2.OAuth2TokenDescriptor;
import com.linecorp.armeria.server.ServiceRequestContext;
import io.netty.util.AttributeKey;
/**
* A helper class that allows handling optional validation of the OAuth 2 token within specific execution
* context (e.g. to implement fine-grained access control).
*/
public final class OAuth2TokenScopeValidator {
static final AttributeKey<OAuth2TokenDescriptor> OAUTH2_TOKEN = AttributeKey.valueOf("x-oauth2-token");
static final AttributeKey<String> OAUTH2_REALM = AttributeKey.valueOf("x-oauth2-realm");
static final String INSUFFICIENT_SCOPE = "insufficient_scope";
/**
* Validates given {@link ServiceRequestContext} against permitted scope of the given execution context.
* This operation assumes that there is a valid {@link OAuth2TokenDescriptor} attached to
* {@link ServiceRequestContext} by the OAuth 2 subsystem.
* @param ctx {@link ServiceRequestContext} that contains valid {@link OAuth2TokenDescriptor}.
* @param permittedScope A {@link Set} of scope tokens (roles) to validate against. This
* {@link Set} could be empty, which means that any valid token will be permitted.
* @return {@code true} if the {@link OAuth2TokenDescriptor} includes non-empty scope, which contains all
* elements of the {@code permittedScope}.
*/
public static boolean validateScope(ServiceRequestContext ctx, Set<String> permittedScope) {
final OAuth2TokenDescriptor tokenDescriptor = ctx.attr(OAUTH2_TOKEN);
if (tokenDescriptor == null) {
return false;
}
return validateScope(tokenDescriptor, permittedScope);
}
/**
* Validates given {@link OAuth2TokenDescriptor} against permitted scope of the given execution context.
* @param tokenDescriptor An instance of {@link OAuth2TokenDescriptor} to validate.
* @param permittedScope A {@link Set} of scope tokens (roles) to validate against. This
* {@link Set} could be empty, which means that any valid token will be permitted.
* @return {@code true} if the {@link OAuth2TokenDescriptor} includes non-empty scope, which contains all
* elements of the {@code permittedScope}.
*/
public static boolean validateScope(OAuth2TokenDescriptor tokenDescriptor, Set<String> permittedScope) {
requireNonNull(permittedScope, "permittedScope");
final Set<String> tokenScopeSet = tokenDescriptor.scopeSet();
return permittedScope.isEmpty() || tokenScopeSet.containsAll(permittedScope);
}
/**
* Returns an {@link HttpResponse} with {@link HttpStatus#FORBIDDEN} result code and formatted
* error response as below.
* <pre>{@code
* HTTP/1.1 403 Forbidden
* Content-Type: application/json;charset=UTF-8
* {"error":"insufficient_scope"}
* }</pre>
*
* <p> This response indicates that the request requires higher privileges than provided by the
* access token. The resource server SHOULD respond with the HTTP 403 (Forbidden) status code and
* MAY include the "scope" attribute with the scope necessary to access the protected resource.</p>
*/
public static HttpResponse insufficientScopeErrorResponse() {
return forbidden(INSUFFICIENT_SCOPE);
}
/**
* Sets the OAuth 2 token to the request context for optional application-level validation.
*/
static void setOauth2Context(ServiceRequestContext ctx, OAuth2TokenDescriptor tokenDescriptor,
@Nullable String realm) {
ctx.setAttr(OAUTH2_TOKEN, tokenDescriptor);
if (realm != null) {
ctx.setAttr(OAUTH2_REALM, realm);
}
}
private OAuth2TokenScopeValidator() {}
}
| apache-2.0 |
sunshine-life/GoodsManagement | src/main/java/org/goodsManagement/util/spring/DigestUtils.java | 5989 | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.goodsManagement.util.spring;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Miscellaneous methods for calculating digests.
* <p>Mainly for internal use within the framework; consider
* <a href="http://commons.apache.org/codec/">Apache Commons Codec</a> for a
* more comprehensive suite of digest utilities.
*
* @author Arjen Poutsma
* @author Craig Andrews
* @since 3.0
// * @see org.apache.commons.codec.digest.DigestUtils
*/
public abstract class DigestUtils {
private static final String MD5_ALGORITHM_NAME = "MD5";
private static final char[] HEX_CHARS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Calculate the MD5 digest of the given bytes.
* @param bytes the bytes to calculate the digest over
* @return the digest
*/
public static byte[] md5Digest(byte[] bytes) {
return digest(MD5_ALGORITHM_NAME, bytes);
}
/**
* Calculate the MD5 digest of the given InputStream.
* @param inputStream the inputStream to calculate the digest over
* @return the digest
* @since 4.2
*/
public static byte[] md5Digest(InputStream inputStream) throws IOException {
return digest(MD5_ALGORITHM_NAME, inputStream);
}
/**
* Return a hexadecimal string representation of the MD5 digest of the given
* bytes.
* @param bytes the bytes to calculate the digest over
* @return a hexadecimal digest string
*/
public static String md5DigestAsHex(byte[] bytes) {
return digestAsHexString(MD5_ALGORITHM_NAME, bytes);
}
/**
* Return a hexadecimal string representation of the MD5 digest of the given
* inputStream.
* @param inputStream the inputStream to calculate the digest over
* @return a hexadecimal digest string
* @since 4.2
*/
public static String md5DigestAsHex(InputStream inputStream) throws IOException {
return digestAsHexString(MD5_ALGORITHM_NAME, inputStream);
}
/**
* Append a hexadecimal string representation of the MD5 digest of the given
* bytes to the given {@link StringBuilder}.
* @param bytes the bytes to calculate the digest over
* @param builder the string builder to append the digest to
* @return the given string builder
*/
public static StringBuilder appendMd5DigestAsHex(byte[] bytes, StringBuilder builder) {
return appendDigestAsHex(MD5_ALGORITHM_NAME, bytes, builder);
}
/**
* Append a hexadecimal string representation of the MD5 digest of the given
* inputStream to the given {@link StringBuilder}.
* @param inputStream the inputStream to calculate the digest over
* @param builder the string builder to append the digest to
* @return the given string builder
* @since 4.2
*/
public static StringBuilder appendMd5DigestAsHex(InputStream inputStream, StringBuilder builder) throws IOException {
return appendDigestAsHex(MD5_ALGORITHM_NAME, inputStream, builder);
}
/**
* Create a new {@link MessageDigest} with the given algorithm.
* Necessary because {@code MessageDigest} is not thread-safe.
*/
private static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + algorithm + "\"", ex);
}
}
private static byte[] digest(String algorithm, byte[] bytes) {
return getDigest(algorithm).digest(bytes);
}
private static byte[] digest(String algorithm, InputStream inputStream) throws IOException {
MessageDigest messageDigest = getDigest(algorithm);
if (inputStream instanceof UpdateMessageDigestInputStream){
((UpdateMessageDigestInputStream) inputStream).updateMessageDigest(messageDigest);
return messageDigest.digest();
}
else{
return messageDigest.digest(StreamUtils.copyToByteArray(inputStream));
}
}
private static String digestAsHexString(String algorithm, byte[] bytes) {
char[] hexDigest = digestAsHexChars(algorithm, bytes);
return new String(hexDigest);
}
private static String digestAsHexString(String algorithm, InputStream inputStream) throws IOException {
char[] hexDigest = digestAsHexChars(algorithm, inputStream);
return new String(hexDigest);
}
private static StringBuilder appendDigestAsHex(String algorithm, byte[] bytes, StringBuilder builder) {
char[] hexDigest = digestAsHexChars(algorithm, bytes);
return builder.append(hexDigest);
}
private static StringBuilder appendDigestAsHex(String algorithm, InputStream inputStream, StringBuilder builder)
throws IOException {
char[] hexDigest = digestAsHexChars(algorithm, inputStream);
return builder.append(hexDigest);
}
private static char[] digestAsHexChars(String algorithm, byte[] bytes) {
byte[] digest = digest(algorithm, bytes);
return encodeHex(digest);
}
private static char[] digestAsHexChars(String algorithm, InputStream inputStream) throws IOException {
byte[] digest = digest(algorithm, inputStream);
return encodeHex(digest);
}
private static char[] encodeHex(byte[] bytes) {
char chars[] = new char[32];
for (int i = 0; i < chars.length; i = i + 2) {
byte b = bytes[i / 2];
chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
chars[i + 1] = HEX_CHARS[b & 0xf];
}
return chars;
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/CreateRouteTableResultStaxUnmarshaller.java | 2627 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model.transform;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* CreateRouteTableResult StAX Unmarshaller
*/
public class CreateRouteTableResultStaxUnmarshaller implements
Unmarshaller<CreateRouteTableResult, StaxUnmarshallerContext> {
public CreateRouteTableResult unmarshall(StaxUnmarshallerContext context)
throws Exception {
CreateRouteTableResult createRouteTableResult = new CreateRouteTableResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return createRouteTableResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("routeTable", targetDepth)) {
createRouteTableResult
.setRouteTable(RouteTableStaxUnmarshaller
.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return createRouteTableResult;
}
}
}
}
private static CreateRouteTableResultStaxUnmarshaller instance;
public static CreateRouteTableResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new CreateRouteTableResultStaxUnmarshaller();
return instance;
}
}
| apache-2.0 |
Soo000/SooChat | src/org/jivesoftware/smackx/bytestreams/socks5/packet/Bytestream.java | 13046 | /**
*
* Copyright the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.bytestreams.socks5.packet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.NamedElement;
import org.jivesoftware.smack.util.XmlStringBuilder;
/**
* A stanza(/packet) representing part of a SOCKS5 Bytestream negotiation.
*
* @author Alexander Wenckus
*/
public class Bytestream extends IQ {
public static final String ELEMENT = QUERY_ELEMENT;
/**
* The XMPP namespace of the SOCKS5 Bytestream
*/
public static final String NAMESPACE = "http://jabber.org/protocol/bytestreams";
private String sessionID;
private Mode mode = Mode.tcp;
private final List<StreamHost> streamHosts = new ArrayList<StreamHost>();
private StreamHostUsed usedHost;
private Activate toActivate;
/**
* The default constructor
*/
public Bytestream() {
super(ELEMENT, NAMESPACE);
}
/**
* A constructor where the session ID can be specified.
*
* @param SID The session ID related to the negotiation.
* @see #setSessionID(String)
*/
public Bytestream(final String SID) {
this();
setSessionID(SID);
}
/**
* Set the session ID related to the bytestream. The session ID is a unique identifier used to
* differentiate between stream negotiations.
*
* @param sessionID the unique session ID that identifies the transfer.
*/
public void setSessionID(final String sessionID) {
this.sessionID = sessionID;
}
/**
* Returns the session ID related to the bytestream negotiation.
*
* @return Returns the session ID related to the bytestream negotiation.
* @see #setSessionID(String)
*/
public String getSessionID() {
return sessionID;
}
/**
* Set the transport mode. This should be put in the initiation of the interaction.
*
* @param mode the transport mode, either UDP or TCP
* @see Mode
*/
public void setMode(final Mode mode) {
this.mode = mode;
}
/**
* Returns the transport mode.
*
* @return Returns the transport mode.
* @see #setMode(Mode)
*/
public Mode getMode() {
return mode;
}
/**
* Adds a potential stream host that the remote user can connect to to receive the file.
*
* @param JID The JID of the stream host.
* @param address The internet address of the stream host.
* @return The added stream host.
*/
public StreamHost addStreamHost(final String JID, final String address) {
return addStreamHost(JID, address, 0);
}
/**
* Adds a potential stream host that the remote user can connect to to receive the file.
*
* @param JID The JID of the stream host.
* @param address The internet address of the stream host.
* @param port The port on which the remote host is seeking connections.
* @return The added stream host.
*/
public StreamHost addStreamHost(final String JID, final String address, final int port) {
StreamHost host = new StreamHost(JID, address, port);
addStreamHost(host);
return host;
}
/**
* Adds a potential stream host that the remote user can transfer the file through.
*
* @param host The potential stream host.
*/
public void addStreamHost(final StreamHost host) {
streamHosts.add(host);
}
/**
* Returns the list of stream hosts contained in the packet.
*
* @return Returns the list of stream hosts contained in the packet.
*/
public List<StreamHost> getStreamHosts() {
return Collections.unmodifiableList(streamHosts);
}
/**
* Returns the stream host related to the given JID, or null if there is none.
*
* @param JID The JID of the desired stream host.
* @return Returns the stream host related to the given JID, or null if there is none.
*/
public StreamHost getStreamHost(final String JID) {
if (JID == null) {
return null;
}
for (StreamHost host : streamHosts) {
if (host.getJID().equals(JID)) {
return host;
}
}
return null;
}
/**
* Returns the count of stream hosts contained in this packet.
*
* @return Returns the count of stream hosts contained in this packet.
*/
public int countStreamHosts() {
return streamHosts.size();
}
/**
* Upon connecting to the stream host the target of the stream replies to the initiator with the
* JID of the SOCKS5 host that they used.
*
* @param JID The JID of the used host.
*/
public void setUsedHost(final String JID) {
this.usedHost = new StreamHostUsed(JID);
}
/**
* Returns the SOCKS5 host connected to by the remote user.
*
* @return Returns the SOCKS5 host connected to by the remote user.
*/
public StreamHostUsed getUsedHost() {
return usedHost;
}
/**
* Returns the activate element of the stanza(/packet) sent to the proxy host to verify the identity of
* the initiator and match them to the appropriate stream.
*
* @return Returns the activate element of the stanza(/packet) sent to the proxy host to verify the
* identity of the initiator and match them to the appropriate stream.
*/
public Activate getToActivate() {
return toActivate;
}
/**
* Upon the response from the target of the used host the activate stanza(/packet) is sent to the SOCKS5
* proxy. The proxy will activate the stream or return an error after verifying the identity of
* the initiator, using the activate packet.
*
* @param targetID The JID of the target of the file transfer.
*/
public void setToActivate(final String targetID) {
this.toActivate = new Activate(targetID);
}
@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
switch(getType()) {
case set:
xml.optAttribute("sid", getSessionID());
xml.optAttribute("mode", getMode());
xml.rightAngleBracket();
if (getToActivate() == null) {
for (StreamHost streamHost : getStreamHosts()) {
xml.append(streamHost.toXML());
}
}
else {
xml.append(getToActivate().toXML());
}
break;
case result:
xml.rightAngleBracket();
xml.optAppend(getUsedHost());
// TODO Bytestream can include either used host *or* streamHosts. Never both. This should be ensured by the
// constructions mechanisms of Bytestream
// A result from the server can also contain stream hosts
for (StreamHost host : streamHosts) {
xml.append(host.toXML());
}
break;
case get:
xml.setEmptyElement();
break;
default:
throw new IllegalStateException();
}
return xml;
}
/**
* Stanza(/Packet) extension that represents a potential SOCKS5 proxy for the file transfer. Stream hosts
* are forwarded to the target of the file transfer who then chooses and connects to one.
*
* @author Alexander Wenckus
*/
public static class StreamHost implements NamedElement {
public static String ELEMENTNAME = "streamhost";
private final String JID;
private final String addy;
private final int port;
public StreamHost(String jid, String address) {
this(jid, address, 0);
}
/**
* Default constructor.
*
* @param JID The JID of the stream host.
* @param address The internet address of the stream host.
*/
public StreamHost(final String JID, final String address, int port) {
this.JID = JID;
this.addy = address;
this.port = port;
}
/**
* Returns the JID of the stream host.
*
* @return Returns the JID of the stream host.
*/
public String getJID() {
return JID;
}
/**
* Returns the internet address of the stream host.
*
* @return Returns the internet address of the stream host.
*/
public String getAddress() {
return addy;
}
/**
* Returns the port on which the potential stream host would accept the connection.
*
* @return Returns the port on which the potential stream host would accept the connection.
*/
public int getPort() {
return port;
}
public String getElementName() {
return ELEMENTNAME;
}
@Override
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder(this);
xml.attribute("jid", getJID());
xml.attribute("host", getAddress());
if (getPort() != 0) {
xml.attribute("port", Integer.toString(getPort()));
} else {
xml.attribute("zeroconf", "_jabber.bytestreams");
}
xml.closeEmptyElement();
return xml;
}
}
/**
* After selected a SOCKS5 stream host and successfully connecting, the target of the file
* transfer returns a byte stream stanza(/packet) with the stream host used extension.
*
* @author Alexander Wenckus
*/
public static class StreamHostUsed implements NamedElement {
public static String ELEMENTNAME = "streamhost-used";
private final String JID;
/**
* Default constructor.
*
* @param JID The JID of the selected stream host.
*/
public StreamHostUsed(final String JID) {
this.JID = JID;
}
/**
* Returns the JID of the selected stream host.
*
* @return Returns the JID of the selected stream host.
*/
public String getJID() {
return JID;
}
public String getElementName() {
return ELEMENTNAME;
}
@Override
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder(this);
xml.attribute("jid", getJID());
xml.closeEmptyElement();
return xml;
}
}
/**
* The stanza(/packet) sent by the stream initiator to the stream proxy to activate the connection.
*
* @author Alexander Wenckus
*/
public static class Activate implements NamedElement {
public static String ELEMENTNAME = "activate";
private final String target;
/**
* Default constructor specifying the target of the stream.
*
* @param target The target of the stream.
*/
public Activate(final String target) {
this.target = target;
}
/**
* Returns the target of the activation.
*
* @return Returns the target of the activation.
*/
public String getTarget() {
return target;
}
public String getElementName() {
return ELEMENTNAME;
}
@Override
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder(this);
xml.rightAngleBracket();
xml.escape(getTarget());
xml.closeElement(this);
return xml;
}
}
/**
* The stream can be either a TCP stream or a UDP stream.
*
* @author Alexander Wenckus
*/
public enum Mode {
/**
* A TCP based stream.
*/
tcp,
/**
* A UDP based stream.
*/
udp;
public static Mode fromName(String name) {
Mode mode;
try {
mode = Mode.valueOf(name);
}
catch (Exception ex) {
mode = tcp;
}
return mode;
}
}
}
| apache-2.0 |
chibenwa/james | dns-service/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/netmatcher/NetMatcher.java | 5335 | /****************************************************************
* 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.james.dnsservice.library.netmatcher;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.james.dnsservice.api.DNSService;
import org.apache.james.dnsservice.library.inetnetwork.InetNetworkBuilder;
import org.apache.james.dnsservice.library.inetnetwork.model.InetNetwork;
/**
* NetMatcher Class is used to check if an ipAddress match a network.
*
* NetMatcher provides a means for checking whether a particular IPv4 or IPv6
* address or domain name is within a set of subnets.
*/
public class NetMatcher {
/**
* The DNS Service used to build InetNetworks.
*/
private final DNSService dnsServer;
/**
* The Set of InetNetwork to match against.
*/
private SortedSet<InetNetwork> networks;
/**
* Create a new instance of Netmatcher.
*
* @param nets
* a String[] which holds all networks
* @param dnsServer
* the DNSService which will be used in this class
*/
public NetMatcher(final String[] nets, DNSService dnsServer) {
this.dnsServer = dnsServer;
initInetNetworks(nets);
}
/**
* Create a new instance of Netmatcher.
*
* @param nets
* a Collection which holds all networks
* @param dnsServer
* the DNSService which will be used in this class
*/
public NetMatcher(final Collection<String> nets, DNSService dnsServer) {
this.dnsServer = dnsServer;
initInetNetworks(nets);
}
/**
* The given String may represent an IP address or a host name.
*
* @param hostIP
* the ipAddress or host name to check
* @see #matchInetNetwork(InetAddress)
*/
public boolean matchInetNetwork(final String hostIP) {
InetAddress ip;
try {
ip = dnsServer.getByName(hostIP);
} catch (UnknownHostException uhe) {
log("Cannot resolve address for " + hostIP + ": " + uhe.getMessage());
return false;
}
return matchInetNetwork(ip);
}
/**
* Return true if passed InetAddress match a network which was used to
* construct the Netmatcher.
*
* @param ip
* InetAddress
* @return true if match the network
*/
public boolean matchInetNetwork(final InetAddress ip) {
boolean sameNet = false;
for (Iterator<InetNetwork> iter = networks.iterator(); (!sameNet) && iter.hasNext();) {
InetNetwork network = iter.next();
sameNet = network.contains(ip);
}
return sameNet;
}
@Override
public String toString() {
return networks.toString();
}
/**
* Can be overwritten for logging
*
* @param s
* the String to log
*/
protected void log(String s) {
}
/**
* Init the class with the given networks.
*
* @param nets
* a Collection which holds all networks
*/
private void initInetNetworks(final Collection<String> nets) {
initInetNetworks(nets.toArray(new String[nets.size()]));
}
/**
* Init the class with the given networks.
*
* @param nets
* a String[] which holds all networks
*/
private void initInetNetworks(final String[] nets) {
networks = new TreeSet<InetNetwork>(new Comparator<InetNetwork>() {
public int compare(InetNetwork in1, InetNetwork in2) {
return in1.toString().compareTo(in2.toString());
}
});
final InetNetworkBuilder inetNetwork = new InetNetworkBuilder(dnsServer);
for (String net : nets) {
try {
InetNetwork inet = inetNetwork.getFromString(net);
networks.add(inet);
} catch (UnknownHostException uhe) {
log("Cannot resolve address: " + uhe.getMessage());
}
}
}
}
| apache-2.0 |
anycrane/apollo | apollo-client/src/main/java/com/ctrip/framework/apollo/spring/util/BeanRegistrationUtil.java | 1149 | package com.ctrip.framework.apollo.spring.util;
import java.util.Objects;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class BeanRegistrationUtil {
public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName,
Class<?> beanClass) {
if (registry.containsBeanDefinition(beanName)) {
return false;
}
String[] candidates = registry.getBeanDefinitionNames();
for (String candidate : candidates) {
BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
if (Objects.equals(beanDefinition.getBeanClassName(), beanClass.getName())) {
return false;
}
}
BeanDefinition annotationProcessor = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition();
registry.registerBeanDefinition(beanName, annotationProcessor);
return true;
}
}
| apache-2.0 |
peterl1084/framework | compatibility-client/src/main/java/com/vaadin/v7/client/ui/VUpload.java | 14058 | /*
* Copyright 2000-2016 Vaadin Ltd.
*
* 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.vaadin.v7.client.ui;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.FormElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.vaadin.client.ApplicationConnection;
import com.vaadin.client.BrowserInfo;
import com.vaadin.client.ConnectorMap;
import com.vaadin.client.StyleConstants;
import com.vaadin.client.VConsole;
import com.vaadin.client.ui.VButton;
import com.vaadin.v7.client.ui.upload.UploadConnector;
import com.vaadin.v7.client.ui.upload.UploadIFrameOnloadStrategy;
import com.vaadin.v7.shared.ui.upload.UploadServerRpc;
/**
*
* Note, we are not using GWT FormPanel as we want to listen submitcomplete
* events even though the upload component is already detached.
*
*/
public class VUpload extends SimplePanel {
private final class MyFileUpload extends FileUpload {
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (event.getTypeInt() == Event.ONCHANGE) {
if (immediate && fu.getFilename() != null
&& !"".equals(fu.getFilename())) {
submit();
}
} else if (BrowserInfo.get().isIE()
&& event.getTypeInt() == Event.ONFOCUS) {
// IE and user has clicked on hidden textarea part of upload
// field. Manually open file selector, other browsers do it by
// default.
fireNativeClick(fu.getElement());
// also remove focus to enable hack if user presses cancel
// button
fireNativeBlur(fu.getElement());
}
}
}
public static final String CLASSNAME = "v-upload";
/**
* FileUpload component that opens native OS dialog to select file.
* <p>
* For internal use only. May be removed or replaced in the future.
*/
public FileUpload fu = new MyFileUpload();
Panel panel = new FlowPanel();
UploadIFrameOnloadStrategy onloadstrategy = GWT
.create(UploadIFrameOnloadStrategy.class);
/** For internal use only. May be removed or replaced in the future. */
public ApplicationConnection client;
/** For internal use only. May be removed or replaced in the future. */
public String paintableId;
/**
* Button that initiates uploading.
* <p>
* For internal use only. May be removed or replaced in the future.
*/
public final VButton submitButton;
/**
* When expecting big files, programmer may initiate some UI changes when
* uploading the file starts. Bit after submitting file we'll visit the
* server to check possible changes.
* <p>
* For internal use only. May be removed or replaced in the future.
*/
public Timer t;
/**
* some browsers tries to send form twice if submit is called in button
* click handler, some don't submit at all without it, so we need to track
* if form is already being submitted
*/
private boolean submitted = false;
private boolean enabled = true;
private boolean immediate;
private Hidden maxfilesize = new Hidden();
/** For internal use only. May be removed or replaced in the future. */
public FormElement element;
private com.google.gwt.dom.client.Element synthesizedFrame;
/** For internal use only. May be removed or replaced in the future. */
public int nextUploadId;
public VUpload() {
super(com.google.gwt.dom.client.Document.get().createFormElement());
element = getElement().cast();
setEncoding(getElement(), FormPanel.ENCODING_MULTIPART);
element.setMethod(FormPanel.METHOD_POST);
setWidget(panel);
panel.add(maxfilesize);
panel.add(fu);
submitButton = new VButton();
submitButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (immediate) {
// fire click on upload (eg. focused button and hit space)
fireNativeClick(fu.getElement());
} else {
submit();
}
}
});
panel.add(submitButton);
setStyleName(CLASSNAME);
}
private static native void setEncoding(Element form, String encoding)
/*-{
form.enctype = encoding;
// IE8 not supported in Vaadin 8
}-*/;
/** For internal use only. May be removed or replaced in the future. */
public void setImmediate(boolean booleanAttribute) {
if (immediate != booleanAttribute) {
immediate = booleanAttribute;
if (immediate) {
fu.sinkEvents(Event.ONCHANGE);
fu.sinkEvents(Event.ONFOCUS);
}
}
setStyleName(getElement(), CLASSNAME + "-immediate", immediate);
}
private static native void fireNativeClick(Element element)
/*-{
element.click();
}-*/;
private static native void fireNativeBlur(Element element)
/*-{
element.blur();
}-*/;
/** For internal use only. May be removed or replaced in the future. */
public void disableUpload() {
setEnabledForSubmitButton(false);
if (!submitted) {
// Cannot disable the fileupload while submitting or the file won't
// be submitted at all
fu.getElement().setPropertyBoolean("disabled", true);
}
enabled = false;
}
/** For internal use only. May be removed or replaced in the future. */
public void enableUpload() {
setEnabledForSubmitButton(true);
fu.getElement().setPropertyBoolean("disabled", false);
enabled = true;
if (submitted) {
/*
* An old request is still in progress (most likely cancelled),
* ditching that target frame to make it possible to send a new
* file. A new target frame is created later."
*/
cleanTargetFrame();
submitted = false;
}
}
private void setEnabledForSubmitButton(boolean enabled) {
submitButton.setEnabled(enabled);
submitButton.setStyleName(StyleConstants.DISABLED, !enabled);
}
/**
* Re-creates file input field and populates panel. This is needed as we
* want to clear existing values from our current file input field.
*/
private void rebuildPanel() {
panel.remove(submitButton);
panel.remove(fu);
fu = new MyFileUpload();
fu.setName(paintableId + "_file");
fu.getElement().setPropertyBoolean("disabled", !enabled);
panel.add(fu);
panel.add(submitButton);
if (immediate) {
fu.sinkEvents(Event.ONCHANGE);
}
}
/**
* Called by JSNI (hooked via {@link #onloadstrategy})
*/
private void onSubmitComplete() {
/* Needs to be run dereferred to avoid various browser issues. */
Scheduler.get().scheduleDeferred(new Command() {
@Override
public void execute() {
if (submitted) {
if (client != null) {
if (t != null) {
t.cancel();
}
VConsole.log("VUpload:Submit complete");
if (isAttached()) {
// no need to call poll() if component is already
// detached #8728
((UploadConnector) ConnectorMap.get(client).getConnector(VUpload.this))
.getRpcProxy(UploadServerRpc.class).poll();
}
}
rebuildPanel();
submitted = false;
enableUpload();
if (!isAttached()) {
/*
* Upload is complete when upload is already abandoned.
*/
cleanTargetFrame();
}
}
}
});
}
ScheduledCommand startUploadCmd = new ScheduledCommand() {
@Override
public void execute() {
element.submit();
submitted = true;
disableUpload();
/*
* Visit server a moment after upload has started to see possible
* changes from UploadStarted event. Will be cleared on complete.
*
* Must get the id here as the upload can finish before the timer
* expires and in that case nextUploadId has been updated and is
* wrong.
*/
final int thisUploadId = nextUploadId;
t = new Timer() {
@Override
public void run() {
// Only visit the server if the upload has not already
// finished
if (thisUploadId == nextUploadId) {
VConsole.log(
"Visiting server to see if upload started event changed UI.");
client.updateVariable(paintableId, "pollForStart",
thisUploadId, true);
}
}
};
t.schedule(800);
}
};
/** For internal use only. May be removed or replaced in the future. */
public void submit() {
if (submitted || !enabled) {
VConsole.log("Submit cancelled (disabled or already submitted)");
return;
}
if (fu.getFilename().length() == 0) {
VConsole.log("Submitting empty selection (no file)");
}
// flush possibly pending variable changes, so they will be handled
// before upload
client.sendPendingVariableChanges();
// This is done as deferred because sendPendingVariableChanges is also
// deferred and we want to start the upload only after the changes have
// been sent to the server
Scheduler.get().scheduleDeferred(startUploadCmd);
}
/** For internal use only. May be removed or replaced in the future. */
public void disableTitle(boolean disable) {
if (disable) {
// Disable title attribute for upload element.
if (BrowserInfo.get().isChrome()) {
// In Chrome title has to be set to " " to make it invisible
fu.setTitle(" ");
} else if (BrowserInfo.get().isFirefox()) {
// In FF title has to be set to empty string to make it
// invisible
// Method setTitle removes title attribute when it's an empty
// string, so setAttribute() should be used here
fu.getElement().setAttribute("title", "");
}
// For other browsers absent title doesn't show default tooltip for
// input element
} else {
fu.setTitle(null);
}
}
@Override
protected void onAttach() {
super.onAttach();
if (client != null) {
ensureTargetFrame();
}
}
/** For internal use only. May be removed or replaced in the future. */
public void ensureTargetFrame() {
if (synthesizedFrame == null) {
// Attach a hidden IFrame to the form. This is the target iframe to
// which the form will be submitted. We have to create the iframe
// using innerHTML, because setting an iframe's 'name' property
// dynamically doesn't work on most browsers.
DivElement dummy = Document.get().createDivElement();
dummy.setInnerHTML("<iframe src=\"javascript:''\" name='"
+ getFrameName()
+ "' style='position:absolute;width:0;height:0;border:0'>");
synthesizedFrame = dummy.getFirstChildElement();
Document.get().getBody().appendChild(synthesizedFrame);
element.setTarget(getFrameName());
onloadstrategy.hookEvents(synthesizedFrame, this);
}
}
private String getFrameName() {
return paintableId + "_TGT_FRAME";
}
@Override
protected void onDetach() {
super.onDetach();
if (!submitted) {
cleanTargetFrame();
}
}
private void cleanTargetFrame() {
if (synthesizedFrame != null) {
Document.get().getBody().removeChild(synthesizedFrame);
onloadstrategy.unHookEvents(synthesizedFrame);
synthesizedFrame = null;
}
}
}
| apache-2.0 |
citywander/pinpoint | web/src/test/java/com/navercorp/pinpoint/web/alarm/checker/GcCountCheckerTest.java | 4837 | /*
* Copyright 2014 NAVER 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 com.navercorp.pinpoint.web.alarm.checker;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.BeforeClass;
import com.navercorp.pinpoint.web.dao.AgentStatDao;
import com.navercorp.pinpoint.web.dao.ApplicationIndexDao;
import com.navercorp.pinpoint.web.vo.AgentStat;
import com.navercorp.pinpoint.web.vo.Application;
import com.navercorp.pinpoint.web.vo.Range;
public class GcCountCheckerTest {
private static final String SERVICE_NAME = "local_service";
private static final String SERVICE_TYPE = "tomcat";
private static ApplicationIndexDao applicationIndexDao;
private static AgentStatDao agentStatDao;
@BeforeClass
public static void before() {
agentStatDao = new AgentStatDao() {
@Override
public List<AgentStat> getAgentStatList(String agentId, Range range) {
List<AgentStat> agentStatList = new LinkedList<AgentStat>();
for (int i = 36; i > 0; i--) {
AgentStat stat = new AgentStat("AGENT_NAME", 1L);
stat.setGcOldCount(i);
agentStatList.add(stat);
}
return agentStatList;
}
@Override
public List<AgentStat> getAggregatedAgentStatList(String agentId, Range range) {
return getAgentStatList(agentId, range);
}
@Override
public boolean agentStatExists(String agentId, Range range) {
return true;
}
};
applicationIndexDao = new ApplicationIndexDao() {
@Override
public List<Application> selectAllApplicationNames() {
throw new UnsupportedOperationException();
}
@Override
public List<String> selectAgentIds(String applicationName) {
if (SERVICE_NAME.equals(applicationName)) {
List<String> agentIds = new LinkedList<String>();
agentIds.add("local_tomcat");
return agentIds;
}
throw new IllegalArgumentException();
}
@Override
public void deleteApplicationName(String applicationName) {
throw new UnsupportedOperationException();
}
@Override
public void deleteAgentIds(Map<String, List<String>> applicationAgentIdMap) {
throw new UnsupportedOperationException();
}
@Override
public void deleteAgentId(String applicationName, String agentId) {
throw new UnsupportedOperationException();
}
};
}
// @Test
// public void checkTest1() {
// Rule rule = new Rule(SERVICE_NAME, SERVICE_TYPE, CheckerCategory.GC_COUNT.getName(), 35, "testGroup", false, false, "");
// Application application = new Application(SERVICE_NAME, ServiceType.STAND_ALONE);
// AgentStatDataCollector collector = new AgentStatDataCollector(DataCollectorCategory.AGENT_STAT, application, agentStatDao, applicationIndexDao, System.currentTimeMillis(), DataCollectorFactory.SLOT_INTERVAL_FIVE_MIN);
// AgentChecker checker = new GcCountChecker(collector, rule);
//
// checker.check();
// assertTrue(checker.isDetected());
// }
//
// @Test
// public void checkTest2() {
// Rule rule = new Rule(SERVICE_NAME, SERVICE_TYPE, CheckerCategory.GC_COUNT.getName(), 36, "testGroup", false, false, "");
// Application application = new Application(SERVICE_NAME, ServiceType.STAND_ALONE);
// AgentStatDataCollector collector = new AgentStatDataCollector(DataCollectorCategory.AGENT_STAT, application, agentStatDao, applicationIndexDao, System.currentTimeMillis(), DataCollectorFactory.SLOT_INTERVAL_FIVE_MIN);
// AgentChecker checker = new GcCountChecker(collector, rule);
//
// checker.check();
// assertFalse(checker.isDetected());
// }
}
| apache-2.0 |
NiteshKant/RxNetty | rxnetty-examples/src/main/java/io/reactivex/netty/examples/tcp/interceptors/transformation/TransformingInterceptorsServer.java | 5378 | /*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.reactivex.netty.examples.tcp.interceptors.transformation;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.reactivex.netty.channel.AllocatingTransformer;
import io.reactivex.netty.examples.ExamplesEnvironment;
import io.reactivex.netty.examples.tcp.interceptors.simple.InterceptingServer;
import io.reactivex.netty.protocol.tcp.server.ConnectionHandler;
import io.reactivex.netty.protocol.tcp.server.TcpServer;
import io.reactivex.netty.protocol.tcp.server.TcpServerInterceptorChain;
import io.reactivex.netty.protocol.tcp.server.TcpServerInterceptorChain.Interceptor;
import io.reactivex.netty.protocol.tcp.server.TcpServerInterceptorChain.TransformingInterceptor;
import io.reactivex.netty.util.StringLineDecoder;
import rx.Observable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* A TCP server that follows a simple text based, new line delimited message protocol.
* The server sends a "Hello" as the first message and then expects a stream of integers to be sent by the client.
* For every integer received, it sends the next two integers in a single message separated by a space.<p>
*
* This example demonstrates the usage of server side interceptors which do data transformations.
* For interceptors requiring no data transformation see {@link InterceptingServer}
*/
public final class TransformingInterceptorsServer {
public static void main(final String[] args) {
ExamplesEnvironment env = ExamplesEnvironment.newEnvironment(TransformingInterceptorsServer.class);
TcpServer<String, ByteBuf> server;
/*Starts a new TCP server on an ephemeral port.*/
server = TcpServer.newServer(0)
.<String, ByteBuf>addChannelHandlerLast("string-line-decoder", StringLineDecoder::new)
.start(TcpServerInterceptorChain.start(sendHello())
.nextWithWriteTransform(writeStrings())
.nextWithTransform(readAndWriteInts())
.end(numberIncrementingHandler()));
/*Wait for shutdown if not called from the client (passed an arg)*/
if (env.shouldWaitForShutdown(args)) {
server.awaitShutdown();
}
/*If not waiting for shutdown, assign the ephemeral port used to a field so that it can be read and used by
the caller, if any.*/
env.registerServerAddress(server.getServerAddress());
}
/**
* Sends a hello on accepting a new connection.
*/
private static Interceptor<String, ByteBuf> sendHello() {
return in -> newConnection -> newConnection.writeString(Observable.just("Hello\n"))
.concatWith(in.handle(newConnection));
}
private static TransformingInterceptor<String, ByteBuf, String, String> writeStrings() {
return in -> newConnection ->
in.handle(newConnection.transformWrite(transformStringToBytes()));
}
private static TransformingInterceptor<String, String, Integer, Integer> readAndWriteInts() {
return in -> newConnection -> in.handle(newConnection.transformRead(o -> o.map(String::trim)
.filter(s -> !s.isEmpty())
.map(Integer::parseInt))
.transformWrite(transformStringToInteger())
);
}
/**
* New {@link ConnectionHandler} that echoes all data received.
*
* @return Connection handler.
*/
private static ConnectionHandler<Integer, Integer> numberIncrementingHandler() {
return conn -> conn.writeAndFlushOnEach(conn.getInput().map(anInt -> ++anInt));
}
private static AllocatingTransformer<String, ByteBuf> transformStringToBytes() {
return new AllocatingTransformer<String, ByteBuf>() {
@Override
public List<ByteBuf> transform(String toTransform, ByteBufAllocator allocator) {
return Collections.singletonList(allocator.buffer().writeBytes(toTransform.getBytes()));
}
};
}
private static AllocatingTransformer<Integer, String> transformStringToInteger() {
return new AllocatingTransformer<Integer, String>() {
@Override
public List<String> transform(Integer toTransform, ByteBufAllocator allocator) {
return Arrays.asList(String.valueOf(toTransform), " ", String.valueOf(++toTransform), "\n");
}
};
}
}
| apache-2.0 |
RobWin/circuitbreaker-java8 | resilience4j-micronaut/src/main/java/io/github/resilience4j/micronaut/retry/package-info.java | 651 | /*
* Copyright 2019 Michael Pollind
*
* 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.github.resilience4j.micronaut.retry;
| apache-2.0 |
AndroidX/androidx | core/core/src/main/java/androidx/core/view/PointerIconCompat.java | 7242 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.view;
import static android.os.Build.VERSION.SDK_INT;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.view.PointerIcon;
import androidx.annotation.DoNotInline;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
/**
* Helper for accessing features in {@link PointerIcon} in a backwards compatible
* fashion.
*/
public final class PointerIconCompat {
/** Synonym for {@link PointerIcon#TYPE_NULL} */
public static final int TYPE_NULL = 0;
/** Synonym for {@link PointerIcon#TYPE_ARROW} */
public static final int TYPE_ARROW = 1000;
/** Synonym for {@link PointerIcon#TYPE_CONTEXT_MENU} */
public static final int TYPE_CONTEXT_MENU = 1001;
/** Synonym for {@link PointerIcon#TYPE_HAND} */
public static final int TYPE_HAND = 1002;
/** Synonym for {@link PointerIcon#TYPE_HELP} */
public static final int TYPE_HELP = 1003;
/** Synonym for {@link PointerIcon#TYPE_WAIT} */
public static final int TYPE_WAIT = 1004;
/** Synonym for {@link PointerIcon#TYPE_CELL} */
public static final int TYPE_CELL = 1006;
/** Synonym for {@link PointerIcon#TYPE_CROSSHAIR} */
public static final int TYPE_CROSSHAIR = 1007;
/** Synonym for {@link PointerIcon#TYPE_TEXT} */
public static final int TYPE_TEXT = 1008;
/** Synonym for {@link PointerIcon#TYPE_VERTICAL_TEXT} */
public static final int TYPE_VERTICAL_TEXT = 1009;
/** Synonym for {@link PointerIcon#TYPE_ALIAS} */
public static final int TYPE_ALIAS = 1010;
/** Synonym for {@link PointerIcon#TYPE_COPY} */
public static final int TYPE_COPY = 1011;
/** Synonym for {@link PointerIcon#TYPE_NO_DROP} */
public static final int TYPE_NO_DROP = 1012;
/** Synonym for {@link PointerIcon#TYPE_ALL_SCROLL} */
public static final int TYPE_ALL_SCROLL = 1013;
/** Synonym for {@link PointerIcon#TYPE_HORIZONTAL_DOUBLE_ARROW} */
public static final int TYPE_HORIZONTAL_DOUBLE_ARROW = 1014;
/** Synonym for {@link PointerIcon#TYPE_VERTICAL_DOUBLE_ARROW} */
public static final int TYPE_VERTICAL_DOUBLE_ARROW = 1015;
/** Synonym for {@link PointerIcon#TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW} */
public static final int TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW = 1016;
/** Synonym for {@link PointerIcon#TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW} */
public static final int TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW = 1017;
/** Synonym for {@link PointerIcon#TYPE_ZOOM_IN} */
public static final int TYPE_ZOOM_IN = 1018;
/** Synonym for {@link PointerIcon#TYPE_ZOOM_OUT} */
public static final int TYPE_ZOOM_OUT = 1019;
/** Synonym for {@link PointerIcon#TYPE_GRAB} */
public static final int TYPE_GRAB = 1020;
/** Synonym for {@link PointerIcon#TYPE_GRABBING} */
public static final int TYPE_GRABBING = 1021;
/** Synonym for {@link PointerIcon#TYPE_DEFAULT} */
public static final int TYPE_DEFAULT = TYPE_ARROW;
private final PointerIcon mPointerIcon;
private PointerIconCompat(PointerIcon pointerIcon) {
mPointerIcon = pointerIcon;
}
/**
* @hide
*/
@Nullable
@RestrictTo(LIBRARY_GROUP_PREFIX)
public Object getPointerIcon() {
return mPointerIcon;
}
/**
* Gets a system pointer icon for the given style.
* If style is not recognized, returns the default pointer icon.
*
* @param context The context.
* @param style The pointer icon style.
* @return The pointer icon.
*/
@NonNull
public static PointerIconCompat getSystemIcon(@NonNull Context context, int style) {
if (SDK_INT >= 24) {
return new PointerIconCompat(Api24Impl.getSystemIcon(context, style));
} else {
return new PointerIconCompat(null);
}
}
/**
* Creates a custom pointer from the given bitmap and hotspot information.
*
* @param bitmap The bitmap for the icon.
* @param hotSpotX The X offset of the pointer icon hotspot in the bitmap.
* Must be within the [0, bitmap.getWidth()) range.
* @param hotSpotY The Y offset of the pointer icon hotspot in the bitmap.
* Must be within the [0, bitmap.getHeight()) range.
* @return A pointer icon for this bitmap.
*
* @throws IllegalArgumentException if bitmap is null, or if the x/y hotspot
* parameters are invalid.
*/
@NonNull
public static PointerIconCompat create(@NonNull Bitmap bitmap, float hotSpotX, float hotSpotY) {
if (SDK_INT >= 24) {
return new PointerIconCompat(Api24Impl.create(bitmap, hotSpotX, hotSpotY));
} else {
return new PointerIconCompat(null);
}
}
/**
* Loads a custom pointer icon from an XML resource.
* <p>
* The XML resource should have the following form:
* <code>
* <?xml version="1.0" encoding="utf-8"?>
* <pointer-icon xmlns:android="http://schemas.android.com/apk/res/android"
* android:bitmap="@drawable/my_pointer_bitmap"
* android:hotSpotX="24"
* android:hotSpotY="24" />
* </code>
* </p>
*
* @param resources The resources object.
* @param resourceId The resource id.
* @return The pointer icon.
*
* @throws Resources.NotFoundException if the resource was not found or the drawable
* linked in the resource was not found.
*/
@NonNull
public static PointerIconCompat load(@NonNull Resources resources, int resourceId) {
if (SDK_INT >= 24) {
return new PointerIconCompat(Api24Impl.load(resources, resourceId));
} else {
return new PointerIconCompat(null);
}
}
@RequiresApi(24)
static class Api24Impl {
private Api24Impl() {
// This class is not instantiable.
}
@DoNotInline
static PointerIcon getSystemIcon(Context context, int type) {
return PointerIcon.getSystemIcon(context, type);
}
@DoNotInline
static PointerIcon create(Bitmap bitmap, float hotSpotX, float hotSpotY) {
return PointerIcon.create(bitmap, hotSpotX, hotSpotY);
}
@DoNotInline
static PointerIcon load(Resources resources, int resourceId) {
return PointerIcon.load(resources, resourceId);
}
}
}
| apache-2.0 |
milcom/hibernate-redis | hibernate-redis/src/test/java/org/hibernate/test/domain/HolidayCalendar.java | 1306 | package org.hibernate.test.domain;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* org.hibernate.test.domain.HolidayCalendar
*
* @author sunghyouk.bae@gmail.com
* @since 13. 4. 6. 오전 12:54
*/
@Entity
@Getter
@Setter
public class HolidayCalendar implements Serializable {
private static final long serialVersionUID = 1863327691656323002L;
@Id
@GeneratedValue
private Long id;
@CollectionTable(name = "HolidayMap", joinColumns = @JoinColumn(name = "CalendarId"))
@MapKeyClass(Date.class) // Map의 Key 의 수형
@ElementCollection(targetClass = String.class, fetch = FetchType.EAGER) // Map의 Value의 수형
private Map<Date, String> holidays = new HashMap<Date, String>();
public HolidayCalendar init() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
holidays.clear();
holidays.put(df.parse("2013-01-01"), "New Year's Day");
holidays.put(df.parse("2013-05-05"), "Children's Day");
holidays.put(df.parse("2013-10-14"), "My Birthday");
} catch (ParseException e) {
throw new RuntimeException(e);
}
return this;
}
}
| apache-2.0 |
apache/jmeter | src/core/src/test/java/org/apache/jorphan/test/AllTests.java | 14961 | /*
* 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.jorphan.test;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.crypto.Cipher;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.jmeter.junit.categories.ExcludeCategoryFilter;
import org.apache.jmeter.junit.categories.NeedGuiTests;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.reflect.ClassFilter;
import org.apache.jorphan.reflect.ClassFinder;
import org.apache.jorphan.util.JOrphanUtils;
import org.junit.experimental.ParallelComputer;
import org.junit.internal.TextListener;
import org.junit.runner.Computer;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;
import org.junit.runner.notification.RunListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import junit.framework.TestCase;
import spock.lang.Specification;
/**
* Provides a quick and easy way to run all <a href="http://http://junit.org">junit</a>
* unit tests (including Spock tests) in your Java project.
* It will find all unit test classes and run all their test methods.
* There is no need to configure it in any way to find these classes except to
* give it a path to search.
* <p>
* Here is an example Ant target (See Ant at <a
* href="http://ant.apache.org">Apache Ant</a>) that runs all your unit
* tests:
*
* <pre>
*
* <target name="test" depends="compile">
* <java classname="org.apache.jorphan.test.AllTests" fork="yes">
* <classpath>
* <path refid="YOUR_CLASSPATH"/>
* <pathelement location="ROOT_DIR_OF_YOUR_COMPILED_CLASSES"/>
* </classpath>
* <arg value="SEARCH_PATH/"/>
* <arg value="PROPERTY_FILE"/>
* <arg value="NAME_OF_UNITTESTMANAGER_CLASS"/>
* </java>
* </target>
*
* </pre>
*
* <dl>
* <dt>YOUR_CLASSPATH</dt>
* <dd>Refers to the classpath that includes all jars and libraries need to run
* your unit tests</dd>
*
* <dt>ROOT_DIR_OF_YOUR_COMPILED_CLASSES</dt>
* <dd>The classpath should include the directory where all your project's
* classes are compiled to, if it doesn't already.</dd>
*
* <dt>SEARCH_PATH</dt>
* <dd>The first argument tells AllTests where to look for unit test classes to
* execute. In most cases, it is identical to ROOT_DIR_OF_YOUR_COMPILED_CLASSES.
* You can specify multiple directories or jars to search by providing a
* comma-delimited list.</dd>
*
* <dt>PROPERTY_FILE</dt>
* <dd>A simple property file that sets logging parameters. It is optional and
* is only relevant if you use the same logging packages that JOrphan uses.</dd>
*
* <dt>NAME_OF_UNITTESTMANAGER_CLASS</dt>
* <dd>If your system requires some configuration to run correctly, you can
* implement the {@link UnitTestManager} interface and be given an opportunity
* to initialize your system from a configuration file.</dd>
* </dl>
*
* @see UnitTestManager
*/
public final class AllTests {
private static final Logger log = LoggerFactory.getLogger(AllTests.class);
/**
* Private constructor to prevent instantiation.
*/
private AllTests() {
}
private static void logprop(String prop, boolean show) {
String value = System.getProperty(prop);
log.info("{}={}", prop, value);
if (show) {
System.out.println(prop + "=" + value);
}
}
private static void logprop(String prop) {
logprop(prop, false);
}
/**
* Starts a run through all unit tests found in the specified classpaths.
* The first argument should be a list of paths to search. The second
* argument is optional and specifies a properties file used to initialize
* logging. The third argument is also optional, and specifies a class that
* implements the UnitTestManager interface. This provides a means of
* initializing your application with a configuration file prior to the
* start of any unit tests.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("You must specify a comma-delimited list of paths to search " + "for unit tests");
return;
}
String home = new File(System.getProperty("user.dir")).getParent();
System.out.println("Setting JMeterHome: "+home);
JMeterUtils.setJMeterHome(home);
initializeManager(args);
log.info("JMeterVersion={}", JMeterUtils.getJMeterVersion());
System.out.println("JMeterVersion=" + JMeterUtils.getJMeterVersion());
logprop("java.version", true);
logprop("java.vm.name");
logprop("java.vendor");
logprop("java.home", true);
logprop("file.encoding", true);
// Display actual encoding used (will differ if file.encoding is not recognised)
System.out.println("default encoding="+Charset.defaultCharset());
log.info("default encoding={}", Charset.defaultCharset());
logprop("user.home");
logprop("user.dir", true);
logprop("user.language");
logprop("user.region");
logprop("user.country");
logprop("user.variant");
log.info("Locale={}", Locale.getDefault());
System.out.println("Locale=" + Locale.getDefault());
logprop("os.name", true);
logprop("os.version", true);
logprop("os.arch");
logprop("java.class.version");
if (Boolean.getBoolean("jmeter.test.log.classpath")) {
String cp = System.getProperty("java.class.path");
String[] cpe = JOrphanUtils.split(cp, java.io.File.pathSeparator);
StringBuilder sb = new StringBuilder(3000);
sb.append("java.class.path=");
for (String path : cpe) {
sb.append("\n");
sb.append(path);
if (new File(path).exists()) {
sb.append(" - OK");
} else {
sb.append(" - ??");
}
}
log.info(sb.toString());
}
try {
int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
System.out.println("JCE max key length = " + maxKeyLen);
} catch (NoSuchAlgorithmException e) {
log.warn(e.getLocalizedMessage());
}
System.out.println("+++++++++++");
logprop("java.awt.headless", true);
logprop("java.awt.graphicsenv", true);
System.out.println("------------");
JUnitCore jUnitCore = new JUnitCore();
// this listener is in the internal junit package
// if it breaks, replace it with a custom text listener
jUnitCore.addListener(new TextListener(System.out));
// this will time each unit test and then print to file
// TODO: put behind a flag
jUnitCore.addListener(new TimePrinter());
System.out.println("Searching junit tests in : "+args[0]);
try {
List<String> tests = findJMeterJUnitTests(args[0]);
List<Class<?>> classes = asClasses(tests);
Result parallelResults = jUnitCore.run(getParallelTests(classes));
Result serialResults = jUnitCore.run(getSerialTests(classes));
boolean allTestsSuccessful =
parallelResults.wasSuccessful() && serialResults.wasSuccessful();
System.exit(allTestsSuccessful ? 0 : 1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static Request getParallelTests(List<Class<?>> classes) {
Request parallelRequest = Request.classes(
ParallelComputer.methods(), // ParallelComputer.classes() causes failures
classes.stream()
.filter(c -> !JMeterSerialTest.class.isAssignableFrom(c))
.toArray(Class<?>[]::new));
return filterGUITests(parallelRequest);
}
private static Request getSerialTests(List<Class<?>> classes) {
Request serialRequest = Request.classes(Computer.serial(),
classes.stream()
.filter(JMeterSerialTest.class::isAssignableFrom)
.toArray(Class<?>[]::new));
return filterGUITests(serialRequest);
}
private static Request filterGUITests(Request request) {
if (GraphicsEnvironment.isHeadless()) {
return request.filterWith(new ExcludeCategoryFilter(NeedGuiTests.class));
} else {
return request;
}
}
private static List<Class<?>> asClasses(List<String> tests) {
return tests.stream()
.map(AllTests::asClass)
.collect(Collectors.toList());
}
private static Class<?> asClass(String test) {
try {
return Class.forName(test, true, Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Used to time each unit test and then write the results to file
*/
private static class TimePrinter extends RunListener {
private ConcurrentHashMap<Description, StopWatch> testTimers = new ConcurrentHashMap<>();
private List<String> logLines = new ArrayList<>();
@Override
public void testStarted(Description description) {
StopWatch sw = new StopWatch();
sw.start();
testTimers.put(description, sw);
}
@Override
public void testFinished(Description desc) {
StopWatch sw = testTimers.get(desc);
sw.stop();
logLines.add(desc.getClassName() + "." + desc.getMethodName() + "\t" + sw.getNanoTime());
}
@Override
public void testRunFinished(Result result) throws Exception {
Files.write(Paths.get("unit-test-perf.log"), logLines);
}
}
/**
* An overridable method that instantiates a UnitTestManager (if one
* was specified in the command-line arguments), and hands it the name of
* the properties file to use to configure the system.
*
* @param args arguments with the initialization parameter
* arg[0] - not used
* arg[1] - relative name of properties file
* arg[2] - used as label
*/
private static void initializeManager(String[] args) {
if (args.length >= 3) {
try {
System.out.println("Using initializeProperties() from " + args[2]);
UnitTestManager um = Class.forName(args[2]).asSubclass(UnitTestManager.class).getDeclaredConstructor()
.newInstance();
System.out.println("Setting up initial properties using: " + args[1]);
um.initializeProperties(args[1]);
} catch (IllegalArgumentException | ReflectiveOperationException | SecurityException e) {
System.out.println("Couldn't create: " + args[2]);
e.printStackTrace();
}
}
}
private static List<String> findJMeterJUnitTests(String searchPathString) throws IOException {
final String[] searchPaths = JOrphanUtils.split(searchPathString, ",");
return ClassFinder.findClasses(searchPaths, new JunitTestFilter());
}
/**
* Match JUnit (including Spock) tests
*/
private static class JunitTestFilter implements ClassFilter {
private final transient ClassLoader contextClassLoader =
Thread.currentThread().getContextClassLoader();
@Override
public boolean accept(String className) {
boolean isJunitTest = false;
try {
Class<?> clazz = Class.forName(className, false, contextClassLoader);
if (!clazz.isAnnotation()
&& !clazz.isEnum()
&& !clazz.isInterface()
&& !Modifier.isAbstract(clazz.getModifiers())) {
isJunitTest = TestCase.class.isAssignableFrom(clazz)
|| Specification.class.isAssignableFrom(clazz) // Spock
|| checkForJUnitAnnotations(clazz);
}
} catch (UnsupportedClassVersionError
| ClassNotFoundException
| NoClassDefFoundError e) {
log.debug("Exception while filtering class {}. {}", className, e.toString());
}
return isJunitTest;
}
private boolean checkForJUnitAnnotations(Class<?> clazz) {
Class<?> classToCheck = clazz;
while (classToCheck != null) {
if (checkForTestAnnotationOnMethods(classToCheck)) {
return true;
}
classToCheck = classToCheck.getSuperclass();
}
return false;
}
private boolean checkForTestAnnotationOnMethods(Class<?> clazz) {
return Arrays.stream(clazz.getDeclaredMethods())
.flatMap(method -> Arrays.stream(method.getAnnotations()))
.map(Annotation::annotationType)
.anyMatch(org.junit.Test.class::isAssignableFrom);
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "JunitTestFilter []";
}
}
}
| apache-2.0 |
prigaux/cas | core/cas-server-core-tickets/src/test/java/org/apereo/cas/ticket/support/HardTimeoutExpirationPolicyTests.java | 1027 | package org.apereo.cas.ticket.support;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apereo.cas.ticket.ExpirationPolicy;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* @author Misagh Moayyed
* @since 4.1
*/
@Slf4j
public class HardTimeoutExpirationPolicyTests {
private static final File JSON_FILE = new File(FileUtils.getTempDirectoryPath(), "hardTimeoutExpirationPolicy.json");
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
public void verifySerializeANeverExpiresExpirationPolicyToJson() throws IOException {
final HardTimeoutExpirationPolicy policyWritten = new HardTimeoutExpirationPolicy();
MAPPER.writeValue(JSON_FILE, policyWritten);
final ExpirationPolicy policyRead = MAPPER.readValue(JSON_FILE, HardTimeoutExpirationPolicy.class);
assertEquals(policyWritten, policyRead);
}
}
| apache-2.0 |
dolfdijkstra/gst-foundation | gsf-legacy/src/main/java/com/fatwire/gst/foundation/controller/AppContext.java | 788 | /*
* Copyright 2011 FatWire Corporation. 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.fatwire.gst.foundation.controller;
/**
* @deprecated
*/
public interface AppContext {
void init();
<T> T getBean(String name, Class<T> c);
}
| apache-2.0 |
stevenbower/frontend-maven-plugin | frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/KarmaRunner.java | 366 | package com.github.eirslett.maven.plugins.frontend.lib;
public interface KarmaRunner extends NodeTaskRunner {}
final class DefaultKarmaRunner extends NodeTaskExecutor implements KarmaRunner {
static final String TASK_LOCATION = "node_modules/karma/bin/karma";
DefaultKarmaRunner(NodeExecutorConfig config) {
super(config, TASK_LOCATION);
}
}
| apache-2.0 |
sashadidukh/kaa | server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/data/LogSchemasDataProvider.java | 1962 | /*
* Copyright 2014-2016 CyberVision, 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.kaaproject.kaa.server.admin.client.mvp.data;
import com.google.gwt.user.client.rpc.AsyncCallback;
import org.kaaproject.avro.ui.gwt.client.widget.grid.AbstractGrid;
import org.kaaproject.kaa.common.dto.logs.LogSchemaDto;
import org.kaaproject.kaa.server.admin.client.KaaAdmin;
import org.kaaproject.kaa.server.admin.client.mvp.activity.grid.AbstractDataProvider;
import org.kaaproject.kaa.server.admin.client.util.HasErrorMessage;
import java.util.List;
public class LogSchemasDataProvider extends AbstractDataProvider<LogSchemaDto, String> {
private String applicationId;
/**
* All-args constructor.
*/
public LogSchemasDataProvider(AbstractGrid<LogSchemaDto, String> dataGrid,
HasErrorMessage hasErrorMessage,
String applicationId) {
super(dataGrid, hasErrorMessage, false);
this.applicationId = applicationId;
addDataDisplay();
}
@Override
protected void loadData(final LoadCallback callback) {
KaaAdmin.getDataSource().loadLogSchemas(applicationId, new AsyncCallback<List<LogSchemaDto>>() {
@Override
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
@Override
public void onSuccess(List<LogSchemaDto> result) {
callback.onSuccess(result);
}
});
}
}
| apache-2.0 |
tomncooper/heron | examples/src/java/org/apache/heron/examples/api/ExclamationTopology.java | 5401 | /**
* 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.heron.examples.api;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.apache.heron.api.Config;
import org.apache.heron.api.HeronSubmitter;
import org.apache.heron.api.bolt.BaseRichBolt;
import org.apache.heron.api.bolt.OutputCollector;
import org.apache.heron.api.metric.GlobalMetrics;
import org.apache.heron.api.topology.IUpdatable;
import org.apache.heron.api.topology.OutputFieldsDeclarer;
import org.apache.heron.api.topology.TopologyBuilder;
import org.apache.heron.api.topology.TopologyContext;
import org.apache.heron.api.tuple.Tuple;
import org.apache.heron.api.utils.Utils;
import org.apache.heron.examples.api.spout.TestWordSpout;
import org.apache.heron.simulator.Simulator;
/**
* This is a basic example of a Storm topology.
*/
public final class ExclamationTopology {
private ExclamationTopology() {
}
public static void main(String[] args) throws Exception {
TopologyBuilder builder = new TopologyBuilder();
int parallelism = 2;
int spouts = parallelism;
builder.setSpout("word", new TestWordSpout(Duration.ofMillis(0)), spouts);
int bolts = 2 * parallelism;
builder.setBolt("exclaim1", new ExclamationBolt(), bolts)
.shuffleGrouping("word");
Config conf = new Config();
conf.setDebug(true);
conf.setMaxSpoutPending(10);
conf.setMessageTimeoutSecs(600);
conf.put(Config.TOPOLOGY_WORKER_CHILDOPTS, "-XX:+HeapDumpOnOutOfMemoryError");
// resources configuration
conf.setComponentRam("word", ExampleResources.getComponentRam());
conf.setComponentRam("exclaim1",
ExampleResources.getComponentRam());
conf.setContainerDiskRequested(
ExampleResources.getContainerDisk(spouts + bolts, parallelism));
conf.setContainerRamRequested(
ExampleResources.getContainerRam(spouts + bolts, parallelism));
conf.setContainerCpuRequested(1);
if (args != null && args.length > 0) {
conf.setNumStmgrs(parallelism);
HeronSubmitter.submitTopology(args[0], conf, builder.createTopology());
} else {
System.out.println("Topology name not provided as an argument, running in simulator mode.");
Simulator simulator = new Simulator();
simulator.submitTopology("test", conf, builder.createTopology());
Utils.sleep(10000);
simulator.killTopology("test");
simulator.shutdown();
}
}
public static class ExclamationBolt extends BaseRichBolt implements IUpdatable {
private static final long serialVersionUID = 1184860508880121352L;
private long nItems;
private long startTime;
@Override
@SuppressWarnings("rawtypes")
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
nItems = 0;
startTime = System.currentTimeMillis();
}
@Override
public void execute(Tuple tuple) {
if (++nItems % 100000 == 0) {
long latency = System.currentTimeMillis() - startTime;
System.out.println(tuple.getString(0) + "!!!");
System.out.println("Bolt processed " + nItems + " tuples in " + latency + " ms");
GlobalMetrics.incr("selected_items");
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
// declarer.declare(new Fields("word"));
}
/**
* Implementing this method is optional and only necessary if BOTH of the following are true:
*
* a.) you plan to dynamically scale your bolt/spout at runtime using 'heron update'.
* b.) you need to take action based on a runtime change to the component parallelism.
*
* Most bolts and spouts should be written to be unaffected by changes in their parallelism,
* but some must be aware of it. An example would be a spout that consumes a subset of queue
* partitions, which must be algorithmically divided amongst the total number of spouts.
* <P>
* Note that this method is from the IUpdatable Heron interface which does not exist in Storm.
* It is fine to implement IUpdatable along with other Storm interfaces, but implementing it
* will bind an otherwise generic Storm implementation to Heron.
*
* @param heronTopologyContext Heron topology context.
*/
@Override
public void update(org.apache.heron.api.topology.TopologyContext heronTopologyContext) {
List<Integer> newTaskIds =
heronTopologyContext.getComponentTasks(heronTopologyContext.getThisComponentId());
System.out.println("Bolt updated with new topologyContext. New taskIds: " + newTaskIds);
}
}
}
| apache-2.0 |
sujianping/Office-365-SDK-for-Android | sdk/office365-mail-calendar-contact-sdk/odata/engine/src/main/java/com/msopentech/odatajclient/engine/data/metadata/edm/v4/EnumType.java | 2006 | /**
* Copyright © Microsoft Open Technologies, Inc.
*
* All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
* ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
* PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
*
* See the Apache License, Version 2.0 for the specific language
* governing permissions and limitations under the License.
*/
package com.msopentech.odatajclient.engine.data.metadata.edm.v4;
import com.msopentech.odatajclient.engine.data.metadata.edm.AbstractEnumType;
import java.util.ArrayList;
import java.util.List;
public class EnumType extends AbstractEnumType implements AnnotatedEdm {
private static final long serialVersionUID = -3329664331877556957L;
private Annotation annotation;
private final List<Member> members = new ArrayList<Member>();
@Override
public List<Member> getMembers() {
return members;
}
@Override
public Member getMember(final String name) {
Member result = null;
for (Member member : getMembers()) {
if (name.equals(member.getName())) {
result = member;
}
}
return result;
}
@Override
public Member getMember(final Integer value) {
Member result = null;
for (Member member : getMembers()) {
if (value.equals(member.getValue())) {
result = member;
}
}
return result;
}
@Override
public Annotation getAnnotation() {
return annotation;
}
@Override
public void setAnnotation(final Annotation annotation) {
this.annotation = annotation;
}
}
| apache-2.0 |
apache/portals-pluto | pluto-container/src/main/java/org/apache/pluto/container/impl/PortletContainerFactory.java | 3141 | /*
* 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.pluto.container.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.pluto.container.ContainerServices;
import org.apache.pluto.container.PortletContainer;
import org.apache.pluto.container.PortletContainerException;
import org.apache.pluto.container.util.ArgumentUtility;
/**
* Factory used to create new PortletContainer instances. The factor constructs
* the underlying pluto container implementation by using the the given
* container services.
*
* @version 1.0
* @since Sep 18, 2004
* @deprecated just use blueprint or spring to construct the PortletContainer
*/
public class PortletContainerFactory {
/** Logger. */
private static final Logger LOG = LoggerFactory.getLogger(PortletContainerFactory.class);
/** Singleton instance of the <code>PortletContainerFactory</code>. */
private static final PortletContainerFactory FACTORY =
new PortletContainerFactory();
/**
* Accessor method for the singleton instance of the
* <code>PortletContainerFactory</code>.
* @return singleton instance of the PortletContainerFactory
*/
public static PortletContainerFactory getInstance() {
return FACTORY;
}
/**
* Private constructor that prevents external instantiation.
*/
private PortletContainerFactory() {
// Do nothing.
}
/**
* Create a container with the given containerName, initialized from the given
* servlet config, and using the given container services.
* @param containerName the name of the portlet container.
* @param requiredServices the required portlet container services.
* @return newly created PortletContainer instance.
* @throws PortletContainerException
*/
public PortletContainer createContainer(
String containerName,
ContainerServices requiredServices)
throws PortletContainerException {
ArgumentUtility.validateNotNull("requiredServices", requiredServices);
ArgumentUtility.validateNotEmpty("containerName", containerName);
PortletContainer container = new PortletContainerImpl(
containerName, requiredServices);
if (LOG.isInfoEnabled()) {
LOG.info("Portlet Container [" + containerName + "] created.");
}
return container;
}
}
| apache-2.0 |
AndroidX/androidx | media/media/src/main/java/androidx/media/MediaBrowserServiceCompat.java | 84256 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.media;
import static androidx.annotation.RestrictTo.Scope.LIBRARY;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP_PREFIX;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_ADD_SUBSCRIPTION;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_CONNECT;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_DISCONNECT;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_GET_MEDIA_ITEM;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_REGISTER_CALLBACK_MESSENGER;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_REMOVE_SUBSCRIPTION;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_SEARCH;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_SEND_CUSTOM_ACTION;
import static androidx.media.MediaBrowserProtocol.CLIENT_MSG_UNREGISTER_CALLBACK_MESSENGER;
import static androidx.media.MediaBrowserProtocol.DATA_CALLBACK_TOKEN;
import static androidx.media.MediaBrowserProtocol.DATA_CALLING_PID;
import static androidx.media.MediaBrowserProtocol.DATA_CALLING_UID;
import static androidx.media.MediaBrowserProtocol.DATA_CUSTOM_ACTION;
import static androidx.media.MediaBrowserProtocol.DATA_CUSTOM_ACTION_EXTRAS;
import static androidx.media.MediaBrowserProtocol.DATA_MEDIA_ITEM_ID;
import static androidx.media.MediaBrowserProtocol.DATA_MEDIA_ITEM_LIST;
import static androidx.media.MediaBrowserProtocol.DATA_MEDIA_SESSION_TOKEN;
import static androidx.media.MediaBrowserProtocol.DATA_NOTIFY_CHILDREN_CHANGED_OPTIONS;
import static androidx.media.MediaBrowserProtocol.DATA_OPTIONS;
import static androidx.media.MediaBrowserProtocol.DATA_PACKAGE_NAME;
import static androidx.media.MediaBrowserProtocol.DATA_RESULT_RECEIVER;
import static androidx.media.MediaBrowserProtocol.DATA_ROOT_HINTS;
import static androidx.media.MediaBrowserProtocol.DATA_SEARCH_EXTRAS;
import static androidx.media.MediaBrowserProtocol.DATA_SEARCH_QUERY;
import static androidx.media.MediaBrowserProtocol.EXTRA_CALLING_PID;
import static androidx.media.MediaBrowserProtocol.EXTRA_CLIENT_VERSION;
import static androidx.media.MediaBrowserProtocol.EXTRA_MESSENGER_BINDER;
import static androidx.media.MediaBrowserProtocol.EXTRA_SERVICE_VERSION;
import static androidx.media.MediaBrowserProtocol.EXTRA_SESSION_BINDER;
import static androidx.media.MediaBrowserProtocol.SERVICE_MSG_ON_CONNECT;
import static androidx.media.MediaBrowserProtocol.SERVICE_MSG_ON_CONNECT_FAILED;
import static androidx.media.MediaBrowserProtocol.SERVICE_MSG_ON_LOAD_CHILDREN;
import static androidx.media.MediaBrowserProtocol.SERVICE_VERSION_CURRENT;
import static androidx.media.MediaSessionManager.RemoteUserInfo.LEGACY_CONTROLLER;
import static androidx.media.MediaSessionManager.RemoteUserInfo.UNKNOWN_PID;
import static androidx.media.MediaSessionManager.RemoteUserInfo.UNKNOWN_UID;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.browse.MediaBrowser;
import android.media.session.MediaSession;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Parcel;
import android.os.RemoteException;
import android.service.media.MediaBrowserService;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.session.IMediaSession;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.os.ResultReceiver;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.collection.ArrayMap;
import androidx.core.app.BundleCompat;
import androidx.core.util.Pair;
import androidx.media.MediaSessionManager.RemoteUserInfo;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Base class for media browse services.
* <p>
* Media browse services enable applications to browse media content provided by an application
* and ask the application to start playing it. They may also be used to control content that
* is already playing by way of a {@link MediaSessionCompat}.
* </p>
*
* To extend this class, you must declare the service in your manifest file with
* an intent filter with the {@link #SERVICE_INTERFACE} action.
*
* For example:
* </p><pre>
* <service android:name=".MyMediaBrowserServiceCompat"
* android:label="@string/service_name" >
* <intent-filter>
* <action android:name="android.media.browse.MediaBrowserService" />
* </intent-filter>
* </service>
* </pre>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about building your media application, read the
* <a href="{@docRoot}guide/topics/media-apps/index.html">Media Apps</a> developer guide.</p>
* </div>
*/
public abstract class MediaBrowserServiceCompat extends Service {
static final String TAG = "MBServiceCompat";
static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
private static final float EPSILON = 0.00001f;
private MediaBrowserServiceImpl mImpl;
/**
* The {@link Intent} that must be declared as handled by the service.
*/
public static final String SERVICE_INTERFACE = "android.media.browse.MediaBrowserService";
/**
* A key for passing the MediaItem to the ResultReceiver in getItem.
*
* @hide
*/
@RestrictTo(LIBRARY)
public static final String KEY_MEDIA_ITEM = "media_item";
/**
* A key for passing the list of MediaItems to the ResultReceiver in search.
*
* @hide
*/
@RestrictTo(LIBRARY)
public static final String KEY_SEARCH_RESULTS = "search_results";
static final int RESULT_FLAG_OPTION_NOT_HANDLED = 1 << 0;
static final int RESULT_FLAG_ON_LOAD_ITEM_NOT_IMPLEMENTED = 1 << 1;
static final int RESULT_FLAG_ON_SEARCH_NOT_IMPLEMENTED = 1 << 2;
/**
* @hide
*/
@RestrictTo(LIBRARY)
public static final int RESULT_ERROR = -1;
/**
* @hide
*/
@RestrictTo(LIBRARY)
public static final int RESULT_OK = 0;
/**
* @hide
*/
@RestrictTo(LIBRARY)
public static final int RESULT_PROGRESS_UPDATE = 1;
@Retention(RetentionPolicy.SOURCE)
@IntDef(flag = true, value = {RESULT_FLAG_OPTION_NOT_HANDLED,
RESULT_FLAG_ON_LOAD_ITEM_NOT_IMPLEMENTED, RESULT_FLAG_ON_SEARCH_NOT_IMPLEMENTED})
private @interface ResultFlags {
}
final ConnectionRecord mConnectionFromFwk = new ConnectionRecord(
LEGACY_CONTROLLER, UNKNOWN_PID, UNKNOWN_UID, null, null);
final ArrayList<ConnectionRecord> mPendingConnections = new ArrayList<>();
final ArrayMap<IBinder, ConnectionRecord> mConnections = new ArrayMap<>();
ConnectionRecord mCurConnection;
final ServiceHandler mHandler = new ServiceHandler();
MediaSessionCompat.Token mSession;
interface MediaBrowserServiceImpl {
void onCreate();
IBinder onBind(Intent intent);
void setSessionToken(MediaSessionCompat.Token token);
void notifyChildrenChanged(String parentId, Bundle options);
void notifyChildrenChanged(RemoteUserInfo remoteUserInfo, String parentId, Bundle options);
Bundle getBrowserRootHints();
RemoteUserInfo getCurrentBrowserInfo();
}
class MediaBrowserServiceImplBase implements MediaBrowserServiceImpl {
private Messenger mMessenger;
@Override
public void onCreate() {
mMessenger = new Messenger(mHandler);
}
@Override
public IBinder onBind(Intent intent) {
if (SERVICE_INTERFACE.equals(intent.getAction())) {
return mMessenger.getBinder();
}
return null;
}
@Override
public void setSessionToken(final MediaSessionCompat.Token token) {
mHandler.post(new Runnable() {
@Override
public void run() {
Iterator<ConnectionRecord> iter = mConnections.values().iterator();
while (iter.hasNext()) {
ConnectionRecord connection = iter.next();
try {
connection.callbacks.onConnect(connection.root.getRootId(), token,
connection.root.getExtras());
} catch (RemoteException e) {
Log.w(TAG, "Connection for " + connection.pkg + " is no longer valid.");
iter.remove();
}
}
}
});
}
@Override
public void notifyChildrenChanged(@NonNull final String parentId, final Bundle options) {
mHandler.post(new Runnable() {
@Override
public void run() {
for (IBinder binder : mConnections.keySet()) {
ConnectionRecord connection = mConnections.get(binder);
notifyChildrenChangedOnHandler(connection, parentId, options);
}
}
});
}
@Override
public void notifyChildrenChanged(@NonNull final RemoteUserInfo remoteUserInfo,
@NonNull final String parentId, final Bundle options) {
mHandler.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < mConnections.size(); i++) {
ConnectionRecord connection = mConnections.valueAt(i);
if (connection.browserInfo.equals(remoteUserInfo)) {
notifyChildrenChangedOnHandler(connection, parentId, options);
break;
}
}
}
});
}
@SuppressWarnings("WeakerAccess") /* synthetic access */
void notifyChildrenChangedOnHandler(final ConnectionRecord connection,
final String parentId, final Bundle options) {
List<Pair<IBinder, Bundle>> callbackList = connection.subscriptions.get(parentId);
if (callbackList != null) {
for (Pair<IBinder, Bundle> callback : callbackList) {
if (MediaBrowserCompatUtils.hasDuplicatedItems(options, callback.second)) {
performLoadChildren(parentId, connection, callback.second, options);
}
}
}
// Don't break, because multiple remoteUserInfo may match.
}
@Override
public Bundle getBrowserRootHints() {
if (mCurConnection == null) {
throw new IllegalStateException("This should be called inside of onLoadChildren,"
+ " onLoadItem, onSearch, or onCustomAction methods");
}
return mCurConnection.rootHints == null ? null : new Bundle(mCurConnection.rootHints);
}
@Override
public RemoteUserInfo getCurrentBrowserInfo() {
if (mCurConnection == null) {
throw new IllegalStateException("This should be called inside of onLoadChildren,"
+ " onLoadItem, onSearch, or onCustomAction methods");
}
return mCurConnection.browserInfo;
}
}
@RequiresApi(21)
class MediaBrowserServiceImplApi21 implements MediaBrowserServiceImpl {
final List<Bundle> mRootExtrasList = new ArrayList<>();
MediaBrowserService mServiceFwk;
Messenger mMessenger;
@Override
public void onCreate() {
mServiceFwk = new MediaBrowserServiceApi21(MediaBrowserServiceCompat.this);
mServiceFwk.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return mServiceFwk.onBind(intent);
}
@Override
public void setSessionToken(final MediaSessionCompat.Token token) {
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
setSessionTokenOnHandler(token);
}
});
}
void setSessionTokenOnHandler(MediaSessionCompat.Token token) {
if (!mRootExtrasList.isEmpty()) {
IMediaSession extraBinder = token.getExtraBinder();
if (extraBinder != null) {
for (Bundle rootExtras : mRootExtrasList) {
BundleCompat.putBinder(rootExtras, EXTRA_SESSION_BINDER,
extraBinder.asBinder());
}
}
mRootExtrasList.clear();
}
mServiceFwk.setSessionToken((MediaSession.Token) token.getToken());
}
@Override
public void notifyChildrenChanged(final String parentId, final Bundle options) {
notifyChildrenChangedForFramework(parentId, options);
notifyChildrenChangedForCompat(parentId, options);
}
@Override
public void notifyChildrenChanged(final RemoteUserInfo remoteUserInfo,
final String parentId, final Bundle options) {
// TODO(Post-P): Need a way to notify to a specific browser in framework.
notifyChildrenChangedForCompat(remoteUserInfo, parentId, options);
}
public BrowserRoot onGetRoot(
String clientPackageName, int clientUid, Bundle rootHints) {
Bundle rootExtras = null;
int clientPid = UNKNOWN_PID;
if (rootHints != null && rootHints.getInt(EXTRA_CLIENT_VERSION, 0) != 0) {
rootHints.remove(EXTRA_CLIENT_VERSION);
mMessenger = new Messenger(mHandler);
rootExtras = new Bundle();
rootExtras.putInt(EXTRA_SERVICE_VERSION, SERVICE_VERSION_CURRENT);
BundleCompat.putBinder(rootExtras, EXTRA_MESSENGER_BINDER, mMessenger.getBinder());
if (mSession != null) {
IMediaSession extraBinder = mSession.getExtraBinder();
BundleCompat.putBinder(rootExtras, EXTRA_SESSION_BINDER,
extraBinder == null ? null : extraBinder.asBinder());
} else {
mRootExtrasList.add(rootExtras);
}
clientPid = rootHints.getInt(EXTRA_CALLING_PID, UNKNOWN_PID);
rootHints.remove(EXTRA_CALLING_PID);
}
ConnectionRecord connection = new ConnectionRecord(
clientPackageName, clientPid, clientUid, rootHints, null);
// We aren't sure whether this connection request would be accepted.
// Temporarily set mCurConnection just to make getCurrentBrowserInfo() working.
mCurConnection = connection;
BrowserRoot root = MediaBrowserServiceCompat.this.onGetRoot(
clientPackageName, clientUid, rootHints);
mCurConnection = null;
if (root == null) {
return null;
}
if (mMessenger != null) {
// Keeps the connection request from the MediaBrowserCompat to reuse the package
// name here.
// Note: Connection will be completed after it gets extra binder call with
// CLIENT_MSG_REGISTER_CALLBACK_MESSENGER.
mPendingConnections.add(connection);
}
if (rootExtras == null) {
rootExtras = root.getExtras();
} else if (root.getExtras() != null) {
rootExtras.putAll(root.getExtras());
}
return new BrowserRoot(root.getRootId(), rootExtras);
}
public void onLoadChildren(String parentId,
final ResultWrapper<List<Parcel>> resultWrapper) {
final Result<List<MediaBrowserCompat.MediaItem>> result =
new Result<List<MediaBrowserCompat.MediaItem>>(parentId) {
@Override
void onResultSent(@Nullable List<MediaBrowserCompat.MediaItem> list) {
List<Parcel> parcelList = null;
if (list != null) {
parcelList = new ArrayList<>(list.size());
for (MediaBrowserCompat.MediaItem item : list) {
Parcel parcel = Parcel.obtain();
item.writeToParcel(parcel, 0);
parcelList.add(parcel);
}
}
resultWrapper.sendResult(parcelList);
}
@Override
public void detach() {
resultWrapper.detach();
}
};
mCurConnection = mConnectionFromFwk;
MediaBrowserServiceCompat.this.onLoadChildren(parentId, result);
mCurConnection = null;
}
void notifyChildrenChangedForFramework(final String parentId, final Bundle options) {
mServiceFwk.notifyChildrenChanged(parentId);
}
void notifyChildrenChangedForCompat(final String parentId, final Bundle options) {
mHandler.post(new Runnable() {
@Override
public void run() {
for (IBinder binder : mConnections.keySet()) {
ConnectionRecord connection = mConnections.get(binder);
notifyChildrenChangedForCompatOnHandler(connection, parentId, options);
}
}
});
}
void notifyChildrenChangedForCompat(final RemoteUserInfo remoteUserInfo,
final String parentId, final Bundle options) {
mHandler.post(new Runnable() {
@Override
public void run() {
for (int i = 0; i < mConnections.size(); i++) {
ConnectionRecord connection = mConnections.valueAt(i);
if (connection.browserInfo.equals(remoteUserInfo)) {
notifyChildrenChangedForCompatOnHandler(connection, parentId, options);
}
}
}
});
}
@SuppressWarnings("WeakerAccess") /* synthetic access */
void notifyChildrenChangedForCompatOnHandler(final ConnectionRecord connection,
final String parentId, final Bundle options) {
List<Pair<IBinder, Bundle>> callbackList = connection.subscriptions.get(parentId);
if (callbackList != null) {
for (Pair<IBinder, Bundle> callback : callbackList) {
if (MediaBrowserCompatUtils.hasDuplicatedItems(options, callback.second)) {
performLoadChildren(parentId, connection, callback.second, options);
}
}
}
}
@Override
public Bundle getBrowserRootHints() {
if (mMessenger == null) {
// TODO: Handle getBrowserRootHints when connected with framework MediaBrowser.
return null;
}
if (mCurConnection == null) {
throw new IllegalStateException("This should be called inside of onGetRoot,"
+ " onLoadChildren, onLoadItem, onSearch, or onCustomAction methods");
}
return mCurConnection.rootHints == null ? null : new Bundle(mCurConnection.rootHints);
}
@Override
public RemoteUserInfo getCurrentBrowserInfo() {
if (mCurConnection == null) {
throw new IllegalStateException("This should be called inside of onGetRoot,"
+ " onLoadChildren, onLoadItem, onSearch, or onCustomAction methods");
}
return mCurConnection.browserInfo;
}
@RequiresApi(21)
class MediaBrowserServiceApi21 extends MediaBrowserService {
MediaBrowserServiceApi21(Context context) {
attachBaseContext(context);
}
@Override
@SuppressLint("SyntheticAccessor")
public MediaBrowserService.BrowserRoot onGetRoot(String clientPackageName,
int clientUid, Bundle rootHints) {
MediaSessionCompat.ensureClassLoader(rootHints);
MediaBrowserServiceCompat.BrowserRoot browserRootCompat =
MediaBrowserServiceImplApi21.this.onGetRoot(clientPackageName, clientUid,
rootHints == null ? null : new Bundle(rootHints));
return browserRootCompat == null ? null : new MediaBrowserService.BrowserRoot(
browserRootCompat.mRootId, browserRootCompat.mExtras);
}
@Override
public void onLoadChildren(String parentId,
Result<List<MediaBrowser.MediaItem>> result) {
MediaBrowserServiceImplApi21.this.onLoadChildren(parentId,
new ResultWrapper<List<Parcel>>(result));
}
}
}
@RequiresApi(23)
class MediaBrowserServiceImplApi23 extends MediaBrowserServiceImplApi21 {
@Override
public void onCreate() {
mServiceFwk = new MediaBrowserServiceApi23(MediaBrowserServiceCompat.this);
mServiceFwk.onCreate();
}
public void onLoadItem(String itemId, final ResultWrapper<Parcel> resultWrapper) {
final Result<MediaBrowserCompat.MediaItem> result =
new Result<MediaBrowserCompat.MediaItem>(itemId) {
@Override
void onResultSent(@Nullable MediaBrowserCompat.MediaItem item) {
if (item == null) {
resultWrapper.sendResult(null);
} else {
Parcel parcelItem = Parcel.obtain();
item.writeToParcel(parcelItem, 0);
resultWrapper.sendResult(parcelItem);
}
}
@Override
public void detach() {
resultWrapper.detach();
}
};
mCurConnection = mConnectionFromFwk;
MediaBrowserServiceCompat.this.onLoadItem(itemId, result);
mCurConnection = null;
}
class MediaBrowserServiceApi23 extends MediaBrowserServiceApi21 {
MediaBrowserServiceApi23(Context context) {
super(context);
}
@Override
public void onLoadItem(String itemId, Result<MediaBrowser.MediaItem> result) {
MediaBrowserServiceImplApi23.this.onLoadItem(itemId,
new ResultWrapper<Parcel>(result));
}
}
}
@RequiresApi(26)
class MediaBrowserServiceImplApi26 extends MediaBrowserServiceImplApi23 {
@Override
public void onCreate() {
mServiceFwk = new MediaBrowserServiceApi26(MediaBrowserServiceCompat.this);
mServiceFwk.onCreate();
}
public void onLoadChildren(String parentId,
final ResultWrapper<List<Parcel>> resultWrapper,
final Bundle options) {
final Result<List<MediaBrowserCompat.MediaItem>> result =
new Result<List<MediaBrowserCompat.MediaItem>>(parentId) {
@Override
void onResultSent(@Nullable List<MediaBrowserCompat.MediaItem> list) {
if (list == null) {
resultWrapper.sendResult(null);
return;
}
if ((getFlags() & RESULT_FLAG_OPTION_NOT_HANDLED) != 0) {
// If onLoadChildren(options) is not overridden, the list we get
// here is not paginated. Therefore, we need to manually cut
// the list. In other words, we need to apply options here.
list = applyOptions(list, options);
}
List<Parcel> parcelList = new ArrayList<>(list.size());
for (MediaBrowserCompat.MediaItem item : list) {
Parcel parcel = Parcel.obtain();
item.writeToParcel(parcel, 0);
parcelList.add(parcel);
}
resultWrapper.sendResult(parcelList);
}
@Override
public void detach() {
resultWrapper.detach();
}
};
mCurConnection = mConnectionFromFwk;
MediaBrowserServiceCompat.this.onLoadChildren(parentId, result, options);
mCurConnection = null;
}
@Override
public Bundle getBrowserRootHints() {
if (mCurConnection == null) {
throw new IllegalStateException("This should be called inside of onGetRoot,"
+ " onLoadChildren, onLoadItem, onSearch, or onCustomAction methods");
}
if (mCurConnection == mConnectionFromFwk) {
return mServiceFwk.getBrowserRootHints();
}
return mCurConnection.rootHints == null ? null : new Bundle(mCurConnection.rootHints);
}
@Override
void notifyChildrenChangedForFramework(final String parentId, final Bundle options) {
if (options != null) {
mServiceFwk.notifyChildrenChanged(parentId, options);
} else {
super.notifyChildrenChangedForFramework(parentId, options);
}
}
class MediaBrowserServiceApi26 extends MediaBrowserServiceApi23 {
MediaBrowserServiceApi26(Context context) {
super(context);
}
@Override
public void onLoadChildren(String parentId, Result<List<MediaBrowser.MediaItem>> result,
Bundle options) {
MediaSessionCompat.ensureClassLoader(options);
mCurConnection = mConnectionFromFwk;
MediaBrowserServiceImplApi26.this.onLoadChildren(parentId,
new ResultWrapper<List<Parcel>>(result), options);
mCurConnection = null;
}
}
}
@RequiresApi(28)
class MediaBrowserServiceImplApi28 extends MediaBrowserServiceImplApi26 {
@Override
public RemoteUserInfo getCurrentBrowserInfo() {
if (mCurConnection == null) {
throw new IllegalStateException("This should be called inside of onGetRoot,"
+ " onLoadChildren, onLoadItem, onSearch, or onCustomAction methods");
}
if (mCurConnection == mConnectionFromFwk) {
return new RemoteUserInfo(mServiceFwk.getCurrentBrowserInfo());
}
return mCurConnection.browserInfo;
}
}
private final class ServiceHandler extends Handler {
private final ServiceBinderImpl mServiceBinderImpl = new ServiceBinderImpl();
ServiceHandler() {
}
@Override
@SuppressWarnings("deprecation")
public void handleMessage(Message msg) {
Bundle data = msg.getData();
switch (msg.what) {
case CLIENT_MSG_CONNECT: {
Bundle rootHints = data.getBundle(DATA_ROOT_HINTS);
MediaSessionCompat.ensureClassLoader(rootHints);
mServiceBinderImpl.connect(
data.getString(DATA_PACKAGE_NAME),
data.getInt(DATA_CALLING_PID),
data.getInt(DATA_CALLING_UID),
rootHints,
new ServiceCallbacksCompat(msg.replyTo));
break;
}
case CLIENT_MSG_DISCONNECT:
mServiceBinderImpl.disconnect(new ServiceCallbacksCompat(msg.replyTo));
break;
case CLIENT_MSG_ADD_SUBSCRIPTION: {
Bundle options = data.getBundle(DATA_OPTIONS);
MediaSessionCompat.ensureClassLoader(options);
mServiceBinderImpl.addSubscription(
data.getString(DATA_MEDIA_ITEM_ID),
BundleCompat.getBinder(data, DATA_CALLBACK_TOKEN),
options,
new ServiceCallbacksCompat(msg.replyTo));
break;
}
case CLIENT_MSG_REMOVE_SUBSCRIPTION:
mServiceBinderImpl.removeSubscription(
data.getString(DATA_MEDIA_ITEM_ID),
BundleCompat.getBinder(data, DATA_CALLBACK_TOKEN),
new ServiceCallbacksCompat(msg.replyTo));
break;
case CLIENT_MSG_GET_MEDIA_ITEM:
mServiceBinderImpl.getMediaItem(
data.getString(DATA_MEDIA_ITEM_ID),
(ResultReceiver) data.getParcelable(DATA_RESULT_RECEIVER),
new ServiceCallbacksCompat(msg.replyTo));
break;
case CLIENT_MSG_REGISTER_CALLBACK_MESSENGER: {
Bundle rootHints = data.getBundle(DATA_ROOT_HINTS);
MediaSessionCompat.ensureClassLoader(rootHints);
mServiceBinderImpl.registerCallbacks(
new ServiceCallbacksCompat(msg.replyTo),
data.getString(DATA_PACKAGE_NAME),
data.getInt(DATA_CALLING_PID),
data.getInt(DATA_CALLING_UID),
rootHints);
break;
}
case CLIENT_MSG_UNREGISTER_CALLBACK_MESSENGER:
mServiceBinderImpl.unregisterCallbacks(
new ServiceCallbacksCompat(msg.replyTo));
break;
case CLIENT_MSG_SEARCH: {
Bundle searchExtras = data.getBundle(DATA_SEARCH_EXTRAS);
MediaSessionCompat.ensureClassLoader(searchExtras);
mServiceBinderImpl.search(
data.getString(DATA_SEARCH_QUERY),
searchExtras,
(ResultReceiver) data.getParcelable(DATA_RESULT_RECEIVER),
new ServiceCallbacksCompat(msg.replyTo));
break;
}
case CLIENT_MSG_SEND_CUSTOM_ACTION: {
Bundle customActionExtras = data.getBundle(DATA_CUSTOM_ACTION_EXTRAS);
MediaSessionCompat.ensureClassLoader(customActionExtras);
mServiceBinderImpl.sendCustomAction(
data.getString(DATA_CUSTOM_ACTION),
customActionExtras,
(ResultReceiver) data.getParcelable(DATA_RESULT_RECEIVER),
new ServiceCallbacksCompat(msg.replyTo));
break;
}
default:
Log.w(TAG, "Unhandled message: " + msg
+ "\n Service version: " + SERVICE_VERSION_CURRENT
+ "\n Client version: " + msg.arg1);
}
}
@Override
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
// Binder.getCallingUid() in handleMessage will return the uid of this process.
// In order to get the right calling uid, Binder.getCallingUid() should be called here.
Bundle data = msg.getData();
data.setClassLoader(MediaBrowserCompat.class.getClassLoader());
data.putInt(DATA_CALLING_UID, Binder.getCallingUid());
int pid = Binder.getCallingPid();
if (pid > 0) {
data.putInt(DATA_CALLING_PID, pid);
} else if (!data.containsKey(DATA_CALLING_PID)) {
// If the MediaBrowserCompat didn't send its PID, then put UNKNOWN_PID.
data.putInt(DATA_CALLING_PID, UNKNOWN_PID);
}
return super.sendMessageAtTime(msg, uptimeMillis);
}
public void postOrRun(Runnable r) {
if (Thread.currentThread() == getLooper().getThread()) {
r.run();
} else {
post(r);
}
}
}
/**
* All the info about a connection.
*/
private class ConnectionRecord implements IBinder.DeathRecipient {
public final String pkg;
public final int pid;
public final int uid;
public final RemoteUserInfo browserInfo;
public final Bundle rootHints;
public final ServiceCallbacks callbacks;
public final HashMap<String, List<Pair<IBinder, Bundle>>> subscriptions = new HashMap<>();
public BrowserRoot root;
ConnectionRecord(String pkg, int pid, int uid, Bundle rootHints,
ServiceCallbacks callback) {
this.pkg = pkg;
this.pid = pid;
this.uid = uid;
this.browserInfo = new RemoteUserInfo(pkg, pid, uid);
this.rootHints = rootHints;
this.callbacks = callback;
}
@Override
public void binderDied() {
mHandler.post(new Runnable() {
@Override
public void run() {
mConnections.remove(callbacks.asBinder());
}
});
}
}
/**
* Completion handler for asynchronous callback methods in {@link MediaBrowserServiceCompat}.
* <p>
* Each of the methods that takes one of these to send the result must call either
* {@link #sendResult} or {@link #sendError} to respond to the caller with the given results or
* errors. If those functions return without calling {@link #sendResult} or {@link #sendError},
* they must instead call {@link #detach} before returning, and then may call
* {@link #sendResult} or {@link #sendError} when they are done. If {@link #sendResult},
* {@link #sendError}, or {@link #detach} is called twice, an exception will be thrown.
* </p><p>
* Those functions might also want to call {@link #sendProgressUpdate} to send interim updates
* to the caller. If it is called after calling {@link #sendResult} or {@link #sendError}, an
* exception will be thrown.
* </p>
*
* @see MediaBrowserServiceCompat#onLoadChildren
* @see MediaBrowserServiceCompat#onLoadItem
* @see MediaBrowserServiceCompat#onSearch
* @see MediaBrowserServiceCompat#onCustomAction
*/
public static class Result<T> {
private final Object mDebug;
private boolean mDetachCalled;
private boolean mSendResultCalled;
private boolean mSendErrorCalled;
private int mFlags;
Result(Object debug) {
mDebug = debug;
}
/**
* Send the result back to the caller.
*/
public void sendResult(@Nullable T result) {
if (mSendResultCalled || mSendErrorCalled) {
throw new IllegalStateException("sendResult() called when either sendResult() or "
+ "sendError() had already been called for: " + mDebug);
}
mSendResultCalled = true;
onResultSent(result);
}
/**
* Send an interim update to the caller. This method is supported only when it is used in
* {@link #onCustomAction}.
*
* @param extras A bundle that contains extra data.
*/
public void sendProgressUpdate(@Nullable Bundle extras) {
if (mSendResultCalled || mSendErrorCalled) {
throw new IllegalStateException("sendProgressUpdate() called when either "
+ "sendResult() or sendError() had already been called for: " + mDebug);
}
checkExtraFields(extras);
onProgressUpdateSent(extras);
}
/**
* Notify the caller of a failure. This is supported only when it is used in
* {@link #onCustomAction}.
*
* @param extras A bundle that contains extra data.
*/
public void sendError(@Nullable Bundle extras) {
if (mSendResultCalled || mSendErrorCalled) {
throw new IllegalStateException("sendError() called when either sendResult() or "
+ "sendError() had already been called for: " + mDebug);
}
mSendErrorCalled = true;
onErrorSent(extras);
}
/**
* Detach this message from the current thread and allow the {@link #sendResult}
* call to happen later.
*/
public void detach() {
if (mDetachCalled) {
throw new IllegalStateException("detach() called when detach() had already"
+ " been called for: " + mDebug);
}
if (mSendResultCalled) {
throw new IllegalStateException("detach() called when sendResult() had already"
+ " been called for: " + mDebug);
}
if (mSendErrorCalled) {
throw new IllegalStateException("detach() called when sendError() had already"
+ " been called for: " + mDebug);
}
mDetachCalled = true;
}
boolean isDone() {
return mDetachCalled || mSendResultCalled || mSendErrorCalled;
}
void setFlags(@ResultFlags int flags) {
mFlags = flags;
}
int getFlags() {
return mFlags;
}
/**
* Called when the result is sent, after assertions about not being called twice have
* happened.
*/
void onResultSent(@Nullable T result) {
}
/**
* Called when an interim update is sent.
*/
void onProgressUpdateSent(@Nullable Bundle extras) {
throw new UnsupportedOperationException("It is not supported to send an interim update "
+ "for " + mDebug);
}
/**
* Called when an error is sent, after assertions about not being called twice have
* happened.
*/
void onErrorSent(@Nullable Bundle extras) {
throw new UnsupportedOperationException("It is not supported to send an error for "
+ mDebug);
}
private void checkExtraFields(@Nullable Bundle extras) {
if (extras == null) {
return;
}
if (extras.containsKey(MediaBrowserCompat.EXTRA_DOWNLOAD_PROGRESS)) {
float value = extras.getFloat(MediaBrowserCompat.EXTRA_DOWNLOAD_PROGRESS);
if (value < -EPSILON || value > 1.0f + EPSILON) {
throw new IllegalArgumentException("The value of the EXTRA_DOWNLOAD_PROGRESS "
+ "field must be a float number within [0.0, 1.0]");
}
}
}
}
private class ServiceBinderImpl {
ServiceBinderImpl() {
}
public void connect(final String pkg, final int pid, final int uid, final Bundle rootHints,
final ServiceCallbacks callbacks) {
if (!isValidPackage(pkg, uid)) {
throw new IllegalArgumentException("Package/uid mismatch: uid=" + uid
+ " package=" + pkg);
}
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
// Clear out the old subscriptions. We are getting new ones.
mConnections.remove(b);
final ConnectionRecord connection = new ConnectionRecord(pkg, pid, uid,
rootHints, callbacks);
mCurConnection = connection;
connection.root = MediaBrowserServiceCompat.this.onGetRoot(pkg, uid, rootHints);
mCurConnection = null;
// If they didn't return something, don't allow this client.
if (connection.root == null) {
Log.i(TAG, "No root for client " + pkg + " from service "
+ getClass().getName());
try {
callbacks.onConnectFailed();
} catch (RemoteException ex) {
Log.w(TAG, "Calling onConnectFailed() failed. Ignoring. "
+ "pkg=" + pkg);
}
} else {
try {
mConnections.put(b, connection);
b.linkToDeath(connection, 0);
if (mSession != null) {
callbacks.onConnect(connection.root.getRootId(),
mSession, connection.root.getExtras());
}
} catch (RemoteException ex) {
Log.w(TAG, "Calling onConnect() failed. Dropping client. "
+ "pkg=" + pkg);
mConnections.remove(b);
}
}
}
});
}
public void disconnect(final ServiceCallbacks callbacks) {
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
// Clear out the old subscriptions. We are getting new ones.
final ConnectionRecord old = mConnections.remove(b);
if (old != null) {
// TODO
old.callbacks.asBinder().unlinkToDeath(old, 0);
}
}
});
}
public void addSubscription(final String id, final IBinder token, final Bundle options,
final ServiceCallbacks callbacks) {
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
// Get the record for the connection
final ConnectionRecord connection = mConnections.get(b);
if (connection == null) {
Log.w(TAG, "addSubscription for callback that isn't registered id="
+ id);
return;
}
MediaBrowserServiceCompat.this.addSubscription(id, connection, token, options);
}
});
}
public void removeSubscription(final String id, final IBinder token,
final ServiceCallbacks callbacks) {
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
ConnectionRecord connection = mConnections.get(b);
if (connection == null) {
Log.w(TAG, "removeSubscription for callback that isn't registered id="
+ id);
return;
}
if (!MediaBrowserServiceCompat.this.removeSubscription(
id, connection, token)) {
Log.w(TAG, "removeSubscription called for " + id
+ " which is not subscribed");
}
}
});
}
public void getMediaItem(final String mediaId, final ResultReceiver receiver,
final ServiceCallbacks callbacks) {
if (TextUtils.isEmpty(mediaId) || receiver == null) {
return;
}
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
ConnectionRecord connection = mConnections.get(b);
if (connection == null) {
Log.w(TAG, "getMediaItem for callback that isn't registered id=" + mediaId);
return;
}
performLoadItem(mediaId, connection, receiver);
}
});
}
// Used when {@link MediaBrowserProtocol#EXTRA_MESSENGER_BINDER} is used.
public void registerCallbacks(final ServiceCallbacks callbacks, final String pkg,
final int pid, final int uid, final Bundle rootHints) {
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
// Clear out the old subscriptions. We are getting new ones.
mConnections.remove(b);
ConnectionRecord connection = null;
Iterator<ConnectionRecord> iter = mPendingConnections.iterator();
while (iter.hasNext()) {
ConnectionRecord pendingConnection = iter.next();
// Note: We cannot use Map/Set for mPendingConnections but List because
// multiple MediaBrowserCompats with the same UID can request connect.
if (pendingConnection.uid == uid) {
// If caller hasn't set pkg and pid, do the best effort to get it.
if (TextUtils.isEmpty(pkg) || pid <= 0) {
// Note: Do not assign pendingConnection directly because it doesn't
// have callback information.
connection = new ConnectionRecord(pendingConnection.pkg,
pendingConnection.pid, pendingConnection.uid,
rootHints, callbacks);
}
iter.remove();
break;
}
}
if (connection == null) {
connection = new ConnectionRecord(pkg, pid, uid, rootHints, callbacks);
}
mConnections.put(b, connection);
try {
b.linkToDeath(connection, 0);
} catch (RemoteException e) {
Log.w(TAG, "IBinder is already dead.");
}
}
});
}
// Used when {@link MediaBrowserProtocol#EXTRA_MESSENGER_BINDER} is used.
public void unregisterCallbacks(final ServiceCallbacks callbacks) {
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
ConnectionRecord old = mConnections.remove(b);
if (old != null) {
b.unlinkToDeath(old, 0);
}
}
});
}
public void search(final String query, final Bundle extras, final ResultReceiver receiver,
final ServiceCallbacks callbacks) {
if (TextUtils.isEmpty(query) || receiver == null) {
return;
}
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
ConnectionRecord connection = mConnections.get(b);
if (connection == null) {
Log.w(TAG, "search for callback that isn't registered query=" + query);
return;
}
performSearch(query, extras, connection, receiver);
}
});
}
public void sendCustomAction(final String action, final Bundle extras,
final ResultReceiver receiver, final ServiceCallbacks callbacks) {
if (TextUtils.isEmpty(action) || receiver == null) {
return;
}
mHandler.postOrRun(new Runnable() {
@Override
public void run() {
final IBinder b = callbacks.asBinder();
ConnectionRecord connection = mConnections.get(b);
if (connection == null) {
Log.w(TAG, "sendCustomAction for callback that isn't registered action="
+ action + ", extras=" + extras);
return;
}
performCustomAction(action, extras, connection, receiver);
}
});
}
}
private interface ServiceCallbacks {
IBinder asBinder();
void onConnect(String root, MediaSessionCompat.Token session, Bundle extras)
throws RemoteException;
void onConnectFailed() throws RemoteException;
void onLoadChildren(String mediaId, List<MediaBrowserCompat.MediaItem> list, Bundle options,
Bundle notifyChildrenChangedOptions) throws RemoteException;
}
private static class ServiceCallbacksCompat implements ServiceCallbacks {
final Messenger mCallbacks;
ServiceCallbacksCompat(Messenger callbacks) {
mCallbacks = callbacks;
}
@Override
public IBinder asBinder() {
return mCallbacks.getBinder();
}
@Override
public void onConnect(String root, MediaSessionCompat.Token session, Bundle extras)
throws RemoteException {
if (extras == null) {
extras = new Bundle();
}
extras.putInt(EXTRA_SERVICE_VERSION, SERVICE_VERSION_CURRENT);
Bundle data = new Bundle();
data.putString(DATA_MEDIA_ITEM_ID, root);
data.putParcelable(DATA_MEDIA_SESSION_TOKEN, session);
data.putBundle(DATA_ROOT_HINTS, extras);
sendRequest(SERVICE_MSG_ON_CONNECT, data);
}
@Override
public void onConnectFailed() throws RemoteException {
sendRequest(SERVICE_MSG_ON_CONNECT_FAILED, null);
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void onLoadChildren(String mediaId, List<MediaBrowserCompat.MediaItem> list,
Bundle options, Bundle notifyChildrenChangedOptions) throws RemoteException {
Bundle data = new Bundle();
data.putString(DATA_MEDIA_ITEM_ID, mediaId);
data.putBundle(DATA_OPTIONS, options);
data.putBundle(DATA_NOTIFY_CHILDREN_CHANGED_OPTIONS, notifyChildrenChangedOptions);
if (list != null) {
data.putParcelableArrayList(DATA_MEDIA_ITEM_LIST,
list instanceof ArrayList ? (ArrayList) list : new ArrayList<>(list));
}
sendRequest(SERVICE_MSG_ON_LOAD_CHILDREN, data);
}
private void sendRequest(int what, Bundle data) throws RemoteException {
Message msg = Message.obtain();
msg.what = what;
msg.arg1 = SERVICE_VERSION_CURRENT;
msg.setData(data);
mCallbacks.send(msg);
}
}
@RequiresApi(21)
@SuppressWarnings({"rawtypes", "unchecked"})
static class ResultWrapper<T> {
MediaBrowserService.Result mResultFwk;
ResultWrapper(MediaBrowserService.Result result) {
mResultFwk = result;
}
public void sendResult(T result) {
if (result instanceof List) {
mResultFwk.sendResult(parcelListToItemList((List<Parcel>) result));
} else if (result instanceof Parcel) {
Parcel parcel = (Parcel) result;
parcel.setDataPosition(0);
mResultFwk.sendResult(MediaBrowser.MediaItem.CREATOR.createFromParcel(parcel));
parcel.recycle();
} else {
// The result is null or an invalid instance.
mResultFwk.sendResult(null);
}
}
public void detach() {
mResultFwk.detach();
}
List<MediaBrowser.MediaItem> parcelListToItemList(List<Parcel> parcelList) {
if (parcelList == null) {
return null;
}
List<MediaBrowser.MediaItem> items = new ArrayList<>(parcelList.size());
for (Parcel parcel : parcelList) {
parcel.setDataPosition(0);
items.add(MediaBrowser.MediaItem.CREATOR.createFromParcel(parcel));
parcel.recycle();
}
return items;
}
}
/**
* Attaches to the base context. This method is added to change the visibility of
* {@link Service#attachBaseContext(Context)}.
* <p>
* Note that we cannot simply override {@link Service#attachBaseContext(Context)} and hide it
* because lint checks considers the overriden method as the new public API that needs update
* of current.txt.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP_PREFIX) // accessed by media2-session
public void attachToBaseContext(Context base) {
attachBaseContext(base);
}
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= 28) {
mImpl = new MediaBrowserServiceImplApi28();
} else if (Build.VERSION.SDK_INT >= 26) {
mImpl = new MediaBrowserServiceImplApi26();
} else if (Build.VERSION.SDK_INT >= 23) {
mImpl = new MediaBrowserServiceImplApi23();
} else if (Build.VERSION.SDK_INT >= 21) {
mImpl = new MediaBrowserServiceImplApi21();
} else {
mImpl = new MediaBrowserServiceImplBase();
}
mImpl.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return mImpl.onBind(intent);
}
@Override
public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
}
/**
* Called to get the root information for browsing by a particular client.
* <p>
* The implementation should verify that the client package has permission
* to access browse media information before returning the root id; it
* should return null if the client is not allowed to access this
* information.
* </p>
*
* @param clientPackageName The package name of the application which is
* requesting access to browse media.
* @param clientUid The uid of the application which is requesting access to
* browse media.
* @param rootHints An optional bundle of service-specific arguments to send
* to the media browse service when connecting and retrieving the
* root id for browsing, or null if none. The contents of this
* bundle may affect the information returned when browsing.
* @return The {@link BrowserRoot} for accessing this app's content or null.
* @see BrowserRoot#EXTRA_RECENT
* @see BrowserRoot#EXTRA_OFFLINE
* @see BrowserRoot#EXTRA_SUGGESTED
*/
public abstract @Nullable BrowserRoot onGetRoot(@NonNull String clientPackageName,
int clientUid, @Nullable Bundle rootHints);
/**
* Called to get information about the children of a media item.
* <p>
* Implementations must call {@link Result#sendResult result.sendResult}
* with the list of children. If loading the children will be an expensive
* operation that should be performed on another thread,
* {@link Result#detach result.detach} may be called before returning from
* this function, and then {@link Result#sendResult result.sendResult}
* called when the loading is complete.
* </p><p>
* In case the media item does not have any children, call {@link Result#sendResult}
* with an empty list. When the given {@code parentId} is invalid, implementations must
* call {@link Result#sendResult result.sendResult} with {@code null}, which will invoke
* {@link MediaBrowserCompat.SubscriptionCallback#onError}.
* </p>
*
* @param parentId The id of the parent media item whose children are to be
* queried.
* @param result The Result to send the list of children to.
*/
public abstract void onLoadChildren(@NonNull String parentId,
@NonNull Result<List<MediaBrowserCompat.MediaItem>> result);
/**
* Called to get information about the children of a media item.
* <p>
* Implementations must call {@link Result#sendResult result.sendResult}
* with the list of children. If loading the children will be an expensive
* operation that should be performed on another thread,
* {@link Result#detach result.detach} may be called before returning from
* this function, and then {@link Result#sendResult result.sendResult}
* called when the loading is complete.
* </p><p>
* In case the media item does not have any children, call {@link Result#sendResult}
* with an empty list. When the given {@code parentId} is invalid, implementations must
* call {@link Result#sendResult result.sendResult} with {@code null}, which will invoke
* {@link MediaBrowserCompat.SubscriptionCallback#onError}.
* </p>
*
* @param parentId The id of the parent media item whose children are to be
* queried.
* @param result The Result to send the list of children to.
* @param options A bundle of service-specific arguments sent from the media
* browse. The information returned through the result should be
* affected by the contents of this bundle.
*/
public void onLoadChildren(@NonNull String parentId,
@NonNull Result<List<MediaBrowserCompat.MediaItem>> result, @NonNull Bundle options) {
// To support backward compatibility, when the implementation of MediaBrowserService doesn't
// override onLoadChildren() with options, onLoadChildren() without options will be used
// instead, and the options will be applied in the implementation of result.onResultSent().
result.setFlags(RESULT_FLAG_OPTION_NOT_HANDLED);
onLoadChildren(parentId, result);
}
/**
* Called when a {@link MediaBrowserCompat#subscribe} is called.
*
* @param id id
* @param option option
* @hide
*/
@RestrictTo(LIBRARY)
public void onSubscribe(String id, Bundle option) {
}
/**
* Called when a {@link MediaBrowserCompat#unsubscribe} is called.
*
* @param id
* @hide
*/
@RestrictTo(LIBRARY)
public void onUnsubscribe(String id) {
}
/**
* Called to get information about a specific media item.
* <p>
* Implementations must call {@link Result#sendResult result.sendResult}. If
* loading the item will be an expensive operation {@link Result#detach
* result.detach} may be called before returning from this function, and
* then {@link Result#sendResult result.sendResult} called when the item has
* been loaded.
* </p><p>
* When the given {@code itemId} is invalid, implementations must call
* {@link Result#sendResult result.sendResult} with {@code null}.
* </p><p>
* The default implementation will invoke {@link MediaBrowserCompat.ItemCallback#onError}.
*
* @param itemId The id for the specific {@link MediaBrowserCompat.MediaItem}.
* @param result The Result to send the item to, or null if the id is
* invalid.
*/
public void onLoadItem(String itemId, @NonNull Result<MediaBrowserCompat.MediaItem> result) {
result.setFlags(RESULT_FLAG_ON_LOAD_ITEM_NOT_IMPLEMENTED);
result.sendResult(null);
}
/**
* Called to get the search result.
* <p>
* Implementations must call {@link Result#sendResult result.sendResult}. If the search will be
* an expensive operation {@link Result#detach result.detach} may be called before returning
* from this function, and then {@link Result#sendResult result.sendResult} called when the
* search has been completed.
* </p><p>
* In case there are no search results, call {@link Result#sendResult result.sendResult} with an
* empty list. In case there are some errors happened, call {@link Result#sendResult
* result.sendResult} with {@code null}, which will invoke {@link
* MediaBrowserCompat.SearchCallback#onError}.
* </p><p>
* The default implementation will invoke {@link MediaBrowserCompat.SearchCallback#onError}.
* </p>
*
* @param query The search query sent from the media browser. It contains keywords separated
* by space.
* @param extras The bundle of service-specific arguments sent from the media browser.
* @param result The {@link Result} to send the search result.
*/
public void onSearch(@NonNull String query, Bundle extras,
@NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
result.setFlags(RESULT_FLAG_ON_SEARCH_NOT_IMPLEMENTED);
result.sendResult(null);
}
/**
* Called to request a custom action to this service.
* <p>
* Implementations must call either {@link Result#sendResult} or {@link Result#sendError}. If
* the requested custom action will be an expensive operation {@link Result#detach} may be
* called before returning from this function, and then the service can send the result later
* when the custom action is completed. Implementation can also call
* {@link Result#sendProgressUpdate} to send an interim update to the requester.
* </p><p>
* If the requested custom action is not supported by this service, call
* {@link Result#sendError}. The default implementation will invoke {@link Result#sendError}.
* </p>
*
* @param action The custom action sent from the media browser.
* @param extras The bundle of service-specific arguments sent from the media browser.
* @param result The {@link Result} to send the result of the requested custom action.
* @see MediaBrowserCompat#CUSTOM_ACTION_DOWNLOAD
* @see MediaBrowserCompat#CUSTOM_ACTION_REMOVE_DOWNLOADED_FILE
*/
public void onCustomAction(@NonNull String action, Bundle extras,
@NonNull Result<Bundle> result) {
result.sendError(null);
}
/**
* Call to set the media session.
* <p>
* This should be called as soon as possible during the service's startup.
* It may only be called once.
*
* @param token The token for the service's {@link MediaSessionCompat}.
*/
public void setSessionToken(MediaSessionCompat.Token token) {
if (token == null) {
throw new IllegalArgumentException("Session token may not be null");
}
if (mSession != null) {
throw new IllegalStateException("The session token has already been set");
}
mSession = token;
mImpl.setSessionToken(token);
}
/**
* Gets the session token, or null if it has not yet been created
* or if it has been destroyed.
*/
@Nullable
public MediaSessionCompat.Token getSessionToken() {
return mSession;
}
/**
* Gets the root hints sent from the currently connected {@link MediaBrowserCompat}.
* The root hints are service-specific arguments included in an optional bundle sent to the
* media browser service when connecting and retrieving the root id for browsing, or null if
* none. The contents of this bundle may affect the information returned when browsing.
* <p>
* Note that this will return null when connected to {@link android.media.browse.MediaBrowser}
* and running on API 23 or lower.
*
* @throws IllegalStateException If this method is called outside of {@link #onLoadChildren},
* {@link #onLoadItem} or {@link #onSearch}.
* @see MediaBrowserServiceCompat.BrowserRoot#EXTRA_RECENT
* @see MediaBrowserServiceCompat.BrowserRoot#EXTRA_OFFLINE
* @see MediaBrowserServiceCompat.BrowserRoot#EXTRA_SUGGESTED
*/
public final Bundle getBrowserRootHints() {
return mImpl.getBrowserRootHints();
}
/**
* Gets the browser information who sent the current request.
*
* @throws IllegalStateException If this method is called outside of {@link #onGetRoot} or
* {@link #onLoadChildren} or {@link #onLoadItem}.
* @see MediaSessionManager#isTrustedForMediaControl(RemoteUserInfo)
*/
@NonNull
public final RemoteUserInfo getCurrentBrowserInfo() {
return mImpl.getCurrentBrowserInfo();
}
/**
* Notifies all connected media browsers that the children of
* the specified parent id have changed in some way.
* This will cause browsers to fetch subscribed content again.
*
* @param parentId The id of the parent media item whose
* children changed.
*/
public void notifyChildrenChanged(@NonNull String parentId) {
if (parentId == null) {
throw new IllegalArgumentException("parentId cannot be null in notifyChildrenChanged");
}
mImpl.notifyChildrenChanged(parentId, null);
}
/**
* Notifies all connected media browsers that the children of
* the specified parent id have changed in some way.
* This will cause browsers to fetch subscribed content again.
*
* @param parentId The id of the parent media item whose
* children changed.
* @param options A bundle of service-specific arguments to send
* to the media browse. The contents of this bundle may
* contain the information about the change.
*/
public void notifyChildrenChanged(@NonNull String parentId, @NonNull Bundle options) {
if (parentId == null) {
throw new IllegalArgumentException("parentId cannot be null in notifyChildrenChanged");
}
if (options == null) {
throw new IllegalArgumentException("options cannot be null in notifyChildrenChanged");
}
mImpl.notifyChildrenChanged(parentId, options);
}
/**
* Notifies a connected media browsers that the children of
* the specified parent id have changed in some way.
* This will cause browsers to fetch subscribed content again.
*
* @param remoteUserInfo to receive this event.
* @param parentId The id of the parent media item whose
* children changed.
* @param options A bundle of service-specific arguments to send
* to the media browse. The contents of this bundle may
* contain the information about the change.
* @hide
*/
@RestrictTo(LIBRARY_GROUP_PREFIX) // accessed by media2-session
public void notifyChildrenChanged(@NonNull RemoteUserInfo remoteUserInfo,
@NonNull String parentId, @NonNull Bundle options) {
if (remoteUserInfo == null) {
throw new IllegalArgumentException("remoteUserInfo cannot be null in"
+ " notifyChildrenChanged");
}
if (parentId == null) {
throw new IllegalArgumentException("parentId cannot be null in notifyChildrenChanged");
}
if (options == null) {
throw new IllegalArgumentException("options cannot be null in notifyChildrenChanged");
}
mImpl.notifyChildrenChanged(remoteUserInfo, parentId, options);
}
/**
* Return whether the given package is one of the ones that is owned by the uid.
*/
boolean isValidPackage(String pkg, int uid) {
if (pkg == null) {
return false;
}
final PackageManager pm = getPackageManager();
final String[] packages = pm.getPackagesForUid(uid);
final int N = packages.length;
for (int i=0; i<N; i++) {
if (packages[i].equals(pkg)) {
return true;
}
}
return false;
}
/**
* Save the subscription and if it is a new subscription send the results.
*/
void addSubscription(String id, ConnectionRecord connection, IBinder token,
Bundle options) {
// Save the subscription
List<Pair<IBinder, Bundle>> callbackList = connection.subscriptions.get(id);
if (callbackList == null) {
callbackList = new ArrayList<>();
}
for (Pair<IBinder, Bundle> callback : callbackList) {
if (token == callback.first
&& MediaBrowserCompatUtils.areSameOptions(options, callback.second)) {
return;
}
}
callbackList.add(new Pair<>(token, options));
connection.subscriptions.put(id, callbackList);
// send the results
performLoadChildren(id, connection, options, null);
mCurConnection = connection;
onSubscribe(id, options);
mCurConnection = null;
}
/**
* Remove the subscription.
*/
boolean removeSubscription(String id, ConnectionRecord connection, IBinder token) {
try {
if (token == null) {
return connection.subscriptions.remove(id) != null;
}
boolean removed = false;
List<Pair<IBinder, Bundle>> callbackList = connection.subscriptions.get(id);
if (callbackList != null) {
Iterator<Pair<IBinder, Bundle>> iter = callbackList.iterator();
while (iter.hasNext()) {
if (token == iter.next().first) {
removed = true;
iter.remove();
}
}
if (callbackList.size() == 0) {
connection.subscriptions.remove(id);
}
}
return removed;
} finally {
mCurConnection = connection;
onUnsubscribe(id);
mCurConnection = null;
}
}
/**
* Call onLoadChildren and then send the results back to the connection.
* <p>
* Callers must make sure that this connection is still connected.
*/
void performLoadChildren(final String parentId, final ConnectionRecord connection,
final Bundle subscribeOptions, final Bundle notifyChildrenChangedOptions) {
final Result<List<MediaBrowserCompat.MediaItem>> result
= new Result<List<MediaBrowserCompat.MediaItem>>(parentId) {
@Override
void onResultSent(@Nullable List<MediaBrowserCompat.MediaItem> list) {
if (mConnections.get(connection.callbacks.asBinder()) != connection) {
if (DEBUG) {
Log.d(TAG, "Not sending onLoadChildren result for connection that has"
+ " been disconnected. pkg=" + connection.pkg + " id=" + parentId);
}
return;
}
List<MediaBrowserCompat.MediaItem> filteredList =
(getFlags() & RESULT_FLAG_OPTION_NOT_HANDLED) != 0
? applyOptions(list, subscribeOptions) : list;
try {
connection.callbacks.onLoadChildren(parentId, filteredList, subscribeOptions,
notifyChildrenChangedOptions);
} catch (RemoteException ex) {
// The other side is in the process of crashing.
Log.w(TAG, "Calling onLoadChildren() failed for id=" + parentId
+ " package=" + connection.pkg);
}
}
};
mCurConnection = connection;
if (subscribeOptions == null) {
onLoadChildren(parentId, result);
} else {
onLoadChildren(parentId, result, subscribeOptions);
}
mCurConnection = null;
if (!result.isDone()) {
throw new IllegalStateException("onLoadChildren must call detach() or sendResult()"
+ " before returning for package=" + connection.pkg + " id=" + parentId);
}
}
List<MediaBrowserCompat.MediaItem> applyOptions(List<MediaBrowserCompat.MediaItem> list,
final Bundle options) {
if (list == null) {
return null;
}
int page = options.getInt(MediaBrowserCompat.EXTRA_PAGE, -1);
int pageSize = options.getInt(MediaBrowserCompat.EXTRA_PAGE_SIZE, -1);
if (page == -1 && pageSize == -1) {
return list;
}
int fromIndex = pageSize * page;
int toIndex = fromIndex + pageSize;
if (page < 0 || pageSize < 1 || fromIndex >= list.size()) {
return Collections.emptyList();
}
if (toIndex > list.size()) {
toIndex = list.size();
}
return list.subList(fromIndex, toIndex);
}
void performLoadItem(String itemId, ConnectionRecord connection,
final ResultReceiver receiver) {
final Result<MediaBrowserCompat.MediaItem> result =
new Result<MediaBrowserCompat.MediaItem>(itemId) {
@Override
void onResultSent(@Nullable MediaBrowserCompat.MediaItem item) {
if ((getFlags() & RESULT_FLAG_ON_LOAD_ITEM_NOT_IMPLEMENTED) != 0) {
receiver.send(RESULT_ERROR, null);
return;
}
Bundle bundle = new Bundle();
bundle.putParcelable(KEY_MEDIA_ITEM, item);
receiver.send(RESULT_OK, bundle);
}
};
mCurConnection = connection;
onLoadItem(itemId, result);
mCurConnection = null;
if (!result.isDone()) {
throw new IllegalStateException("onLoadItem must call detach() or sendResult()"
+ " before returning for id=" + itemId);
}
}
void performSearch(final String query, Bundle extras, ConnectionRecord connection,
final ResultReceiver receiver) {
final Result<List<MediaBrowserCompat.MediaItem>> result =
new Result<List<MediaBrowserCompat.MediaItem>>(query) {
@Override
void onResultSent(@Nullable List<MediaBrowserCompat.MediaItem> items) {
if ((getFlags() & RESULT_FLAG_ON_SEARCH_NOT_IMPLEMENTED) != 0
|| items == null) {
receiver.send(RESULT_ERROR, null);
return;
}
Bundle bundle = new Bundle();
bundle.putParcelableArray(KEY_SEARCH_RESULTS,
items.toArray(new MediaBrowserCompat.MediaItem[0]));
receiver.send(RESULT_OK, bundle);
}
};
mCurConnection = connection;
onSearch(query, extras, result);
mCurConnection = null;
if (!result.isDone()) {
throw new IllegalStateException("onSearch must call detach() or sendResult()"
+ " before returning for query=" + query);
}
}
void performCustomAction(final String action, Bundle extras, ConnectionRecord connection,
final ResultReceiver receiver) {
final Result<Bundle> result = new Result<Bundle>(action) {
@Override
void onResultSent(@Nullable Bundle result) {
receiver.send(RESULT_OK, result);
}
@Override
void onProgressUpdateSent(@Nullable Bundle data) {
receiver.send(RESULT_PROGRESS_UPDATE, data);
}
@Override
void onErrorSent(@Nullable Bundle data) {
receiver.send(RESULT_ERROR, data);
}
};
mCurConnection = connection;
onCustomAction(action, extras, result);
mCurConnection = null;
if (!result.isDone()) {
throw new IllegalStateException("onCustomAction must call detach() or sendResult() or "
+ "sendError() before returning for action=" + action + " extras="
+ extras);
}
}
/**
* Contains information that the browser service needs to send to the client
* when first connected.
*/
public static final class BrowserRoot {
/**
* The lookup key for a boolean that indicates whether the browser service should return a
* browser root for recently played media items.
*
* <p>When creating a media browser for a given media browser service, this key can be
* supplied as a root hint for retrieving media items that are recently played.
* If the media browser service can provide such media items, the implementation must return
* the key in the root hint when {@link #onGetRoot(String, int, Bundle)} is called back.
*
* <p>The root hint may contain multiple keys.
*
* @see #EXTRA_OFFLINE
* @see #EXTRA_SUGGESTED
*/
public static final String EXTRA_RECENT = "android.service.media.extra.RECENT";
/**
* The lookup key for a boolean that indicates whether the browser service should return a
* browser root for offline media items.
*
* <p>When creating a media browser for a given media browser service, this key can be
* supplied as a root hint for retrieving media items that are can be played without an
* internet connection.
* If the media browser service can provide such media items, the implementation must return
* the key in the root hint when {@link #onGetRoot(String, int, Bundle)} is called back.
*
* <p>The root hint may contain multiple keys.
*
* @see #EXTRA_RECENT
* @see #EXTRA_SUGGESTED
*/
public static final String EXTRA_OFFLINE = "android.service.media.extra.OFFLINE";
/**
* The lookup key for a boolean that indicates whether the browser service should return a
* browser root for suggested media items.
*
* <p>When creating a media browser for a given media browser service, this key can be
* supplied as a root hint for retrieving the media items suggested by the media browser
* service. The list of media items passed in {@link MediaBrowserCompat.SubscriptionCallback#onChildrenLoaded(String, List)}
* is considered ordered by relevance, first being the top suggestion.
* If the media browser service can provide such media items, the implementation must return
* the key in the root hint when {@link #onGetRoot(String, int, Bundle)} is called back.
*
* <p>The root hint may contain multiple keys.
*
* @see #EXTRA_RECENT
* @see #EXTRA_OFFLINE
*/
public static final String EXTRA_SUGGESTED = "android.service.media.extra.SUGGESTED";
/**
* The lookup key for a string that indicates specific keywords which will be considered
* when the browser service suggests media items.
*
* <p>When creating a media browser for a given media browser service, this key can be
* supplied as a root hint together with {@link #EXTRA_SUGGESTED} for retrieving suggested
* media items related with the keywords. The list of media items passed in
* {@link android.media.browse.MediaBrowser.SubscriptionCallback#onChildrenLoaded(String, List)}
* is considered ordered by relevance, first being the top suggestion.
* If the media browser service can provide such media items, the implementation must return
* the key in the root hint when {@link #onGetRoot(String, int, Bundle)} is called back.
*
* <p>The root hint may contain multiple keys.
*
* @see #EXTRA_RECENT
* @see #EXTRA_OFFLINE
* @see #EXTRA_SUGGESTED
* @deprecated The search functionality is now supported by the methods
* {@link MediaBrowserCompat#search} and {@link #onSearch}. Use those methods
* instead.
*/
@Deprecated
public static final String EXTRA_SUGGESTION_KEYWORDS
= "android.service.media.extra.SUGGESTION_KEYWORDS";
final private String mRootId;
final private Bundle mExtras;
/**
* Constructs a browser root.
* @param rootId The root id for browsing.
* @param extras Any extras about the browser service.
*/
public BrowserRoot(@NonNull String rootId, @Nullable Bundle extras) {
if (rootId == null) {
throw new IllegalArgumentException("The root id in BrowserRoot cannot be null. " +
"Use null for BrowserRoot instead");
}
mRootId = rootId;
mExtras = extras;
}
/**
* Gets the root id for browsing.
*/
public String getRootId() {
return mRootId;
}
/**
* Gets any extras about the browser service.
*/
public Bundle getExtras() {
return mExtras;
}
}
}
| apache-2.0 |
EMResearch/EMB | jdk_11_maven/cs/graphql/timbuctoo/ContractDiff/src/test/java/nl/knaw/huygens/contractdiff/jsondiff/JsonDifferTest.java | 3856 | package nl.knaw.huygens.contractdiff.jsondiff;
import nl.knaw.huygens.contractdiff.diffresults.DiffResult;
import org.junit.Test;
import static nl.knaw.huygens.contractdiff.JsonBuilder.jsn;
import static nl.knaw.huygens.contractdiff.JsonBuilder.jsnA;
import static nl.knaw.huygens.contractdiff.JsonBuilder.jsnO;
import static nl.knaw.huygens.contractdiff.jsondiff.JsonDiffer.jsonDiffer;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class JsonDifferTest {
@Test
public void handlesEqualValues() throws Exception {
JsonDiffer differ = jsonDiffer().build();
DiffResult result = differ.diff(
jsnO(
"match", jsn(1)
),
jsnO(
"match", jsn(1)
)
);
assertThat(result.wasSuccess(), is(true));
assertThat(result.asConsoleAnsiStripped(),
is("{\n" +
" \"match\": 1, //is 1\n" +
"}\n")
);
}
@Test
public void handlesUnEqualValues() throws Exception {
JsonDiffer differ = jsonDiffer().build();
DiffResult result = differ.diff(
jsnO(
"mismatch", jsn(1)
),
jsnO(
"mismatch", jsn(3)
)
);
assertThat(result.wasSuccess(), is(false));
assertThat(result.asConsoleAnsiStripped(),
is("{\n" +
" \"mismatch\": 1, //expected 3\n" +
"}\n")
);
}
@Test
public void handlesSuperfluousValues() throws Exception {
JsonDiffer differ = jsonDiffer().build();
DiffResult result = differ.diff(
jsnO(
"extra", jsn(2)
),
jsnO(
)
);
assertThat(result.asConsoleAnsiStripped(),
is("{\n" +
" \"extra\": 2, //not part of contract\n" +
"}\n")
);
}
@Test
public void handlesMissingValues() throws Exception {
JsonDiffer differ = jsonDiffer().build();
DiffResult result = differ.diff(
jsnO(
),
jsnO(
"missing", jsn(2)
)
);
assertThat(result.asConsoleAnsiStripped(),
is("{\n" +
" \"missing\": 2, //missing\n" +
"}\n")
);
}
@Test
public void handlesDynamicMatchers() throws Exception {
JsonDiffer differ = jsonDiffer().build();
DiffResult result = differ.diff(
jsnO(
"dynamicFail", jsn(1),
"dynamicSuccess", jsn("1")
),
jsnO(
"dynamicFail", jsn("/*STRING*/"),
"dynamicSuccess", jsn("/*STRING*/")
)
);
assertThat(result.asConsoleAnsiStripped(),
is("{\n" +
" \"dynamicSuccess\": \"1\", //is a string\n" +
" \"dynamicFail\": 1, //expected a string\n" +
"}\n")
);
}
@Test
public void handlesDynamicMatchersWithConfig() throws Exception {
JsonDiffer differ = jsonDiffer().build();
DiffResult result = differ.diff(
jsnO(
"some_array", jsnA(
jsn("foo"),
jsn(2)
)
),
jsnO(
"some_array", jsnO(
"custom-matcher", jsn("/*ALL_MATCH*/"),
"expected", jsn("/*STRING*/")
)
)
);
assertThat(result.asConsoleAnsiStripped(),
is("{\n" +
" \"some_array\": [\n" +
" \"foo\", //is a string\n" +
" 2, //expected a string\n" +
" ],\n" +
"}\n")
);
}
@Test
public void handlesNestedObjects() throws Exception {
JsonDiffer differ = jsonDiffer().build();
DiffResult result = differ.diff(
jsnO(
"a", jsnO(
"b", jsn(2),
"c", jsn("superfluous")
)
),
jsnO(
"a", jsnO(
"b", jsn(2)
)
)
);
assertThat(result.asConsoleAnsiStripped(),
is("{\n" +
" \"a\": {\n" +
" \"b\": 2, //is 2\n" +
" \"c\": \"superfluous\", //not part of contract\n" +
" },\n" +
"}\n")
);
}
}
| apache-2.0 |
abhishek-ch/incubator-ignite | modules/core/src/main/java/org/apache/ignite/internal/util/nio/GridCommunicationClient.java | 3338 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.util.nio;
import org.apache.ignite.*;
import org.apache.ignite.internal.util.lang.*;
import org.apache.ignite.plugin.extensions.communication.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.nio.*;
import java.util.*;
/**
*
*/
public interface GridCommunicationClient {
/**
* Executes the given handshake closure on opened client passing underlying IO streams.
* This method pulled to client interface a handshake is only operation requiring access
* to both output and input streams.
*
* @param handshakeC Handshake.
* @throws IgniteCheckedException If handshake failed.
*/
void doHandshake(IgniteInClosure2X<InputStream, OutputStream> handshakeC) throws IgniteCheckedException;
/**
* @return {@code True} if client has been closed by this call,
* {@code false} if failed to close client (due to concurrent reservation or concurrent close).
*/
boolean close();
/**
* Forces client close.
*/
void forceClose();
/**
* @return {@code True} if client is closed;
*/
boolean closed();
/**
* @return {@code True} if client was reserved, {@code false} otherwise.
*/
boolean reserve();
/**
* Releases this client by decreasing reservations.
*/
void release();
/**
* @return {@code True} if client was reserved.
*/
boolean reserved();
/**
* Gets idle time of this client.
*
* @return Idle time of this client.
*/
long getIdleTime();
/**
* @param data Data to send.
* @throws IgniteCheckedException If failed.
*/
void sendMessage(ByteBuffer data) throws IgniteCheckedException;
/**
* @param data Data to send.
* @param len Length.
* @throws IgniteCheckedException If failed.
*/
void sendMessage(byte[] data, int len) throws IgniteCheckedException;
/**
* @param nodeId Node ID (provided only if versions of local and remote nodes are different).
* @param msg Message to send.
* @throws IgniteCheckedException If failed.
* @return {@code True} if should try to resend message.
*/
boolean sendMessage(@Nullable UUID nodeId, Message msg) throws IgniteCheckedException;
/**
* @param timeout Timeout.
* @throws IOException If failed.
*/
void flushIfNeeded(long timeout) throws IOException;
/**
* @return {@code True} if send is asynchronous.
*/
boolean async();
}
| apache-2.0 |
Teradata/presto | presto-product-tests/src/main/java/com/facebook/presto/tests/JmxConnectorTests.java | 2471 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.tests;
import io.prestodb.tempto.ProductTest;
import org.testng.annotations.Test;
import java.sql.Connection;
import static com.facebook.presto.tests.TestGroups.JDBC;
import static com.facebook.presto.tests.TestGroups.JMX_CONNECTOR;
import static com.facebook.presto.tests.utils.JdbcDriverUtils.usingPrestoJdbcDriver;
import static com.facebook.presto.tests.utils.JdbcDriverUtils.usingTeradataJdbcDriver;
import static io.prestodb.tempto.assertions.QueryAssert.assertThat;
import static io.prestodb.tempto.query.QueryExecutor.defaultQueryExecutor;
import static io.prestodb.tempto.query.QueryExecutor.query;
import static java.sql.JDBCType.BIGINT;
import static java.sql.JDBCType.LONGNVARCHAR;
import static java.sql.JDBCType.VARCHAR;
public class JmxConnectorTests
extends ProductTest
{
@Test(groups = {JMX_CONNECTOR, JDBC})
public void selectFromJavaRuntimeJmxMBean()
{
Connection connection = defaultQueryExecutor().getConnection();
String sql = "SELECT node, vmname, vmversion FROM jmx.current.\"java.lang:type=runtime\"";
if (usingPrestoJdbcDriver(connection)) {
assertThat(query(sql))
.hasColumns(LONGNVARCHAR, LONGNVARCHAR, LONGNVARCHAR)
.hasAnyRows();
}
else if (usingTeradataJdbcDriver(connection)) {
assertThat(query(sql))
.hasColumns(VARCHAR, VARCHAR, VARCHAR)
.hasAnyRows();
}
else {
throw new IllegalStateException();
}
}
@Test(groups = JMX_CONNECTOR)
public void selectFromJavaOperatingSystemJmxMBean()
{
assertThat(query("SELECT openfiledescriptorcount, maxfiledescriptorcount " +
"FROM jmx.current.\"java.lang:type=operatingsystem\""))
.hasColumns(BIGINT, BIGINT)
.hasAnyRows();
}
}
| apache-2.0 |
apache/portals-pluto | pluto-portal-driver/src/main/java/org/apache/pluto/driver/portlets/AboutPortlet.java | 2677 | /*
* 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.pluto.driver.portlets;
import java.io.IOException;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
/**
* The pluto portal driver about portlet.
* @since 2006-02-09
*/
public class AboutPortlet extends GenericPortlet {
private static final String VIEW_PAGE = "/WEB-INF/fragments/about/view.jsp";
private static final String EDIT_PAGE = "/WEB-INF/fragments/about/edit.jsp";
private static final String HELP_PAGE = "/WEB-INF/fragments/about/help.jsp";
// GenericPortlet Impl -----------------------------------------------------
public void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
response.setContentType("text/html");
PortletContext context = getPortletContext();
PortletRequestDispatcher requestDispatcher =
context.getRequestDispatcher(VIEW_PAGE);
requestDispatcher.include(request, response);
}
protected void doEdit(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
response.setContentType("text/html");
PortletContext context = getPortletContext();
PortletRequestDispatcher requestDispatcher =
context.getRequestDispatcher(EDIT_PAGE);
requestDispatcher.include(request, response);
}
protected void doHelp(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
response.setContentType("text/html");
PortletContext context = getPortletContext();
PortletRequestDispatcher requestDispatcher =
context.getRequestDispatcher(HELP_PAGE);
requestDispatcher.include(request, response);
}
}
| apache-2.0 |
baldimir/optaplanner | optaplanner-core/src/test/java/org/optaplanner/core/impl/testdata/domain/immovable/chained/TestdataImmovableChainedEntity.java | 3424 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.impl.testdata.domain.immovable.chained;
import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.variable.PlanningVariable;
import org.optaplanner.core.api.domain.variable.PlanningVariableGraphType;
import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor;
import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor;
import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import org.optaplanner.core.impl.testdata.domain.TestdataObject;
import org.optaplanner.core.impl.testdata.domain.chained.TestdataChainedObject;
@PlanningEntity(movableEntitySelectionFilter = TestdataImmovableChainedEntityFilter.class)
public class TestdataImmovableChainedEntity extends TestdataObject implements TestdataChainedObject {
public static EntityDescriptor buildEntityDescriptor() {
SolutionDescriptor solutionDescriptor = TestdataImmovableChainedSolution.buildSolutionDescriptor();
return solutionDescriptor.findEntityDescriptorOrFail(TestdataImmovableChainedEntity.class);
}
public static GenuineVariableDescriptor buildVariableDescriptorForChainedObject() {
SolutionDescriptor solutionDescriptor = TestdataImmovableChainedSolution.buildSolutionDescriptor();
EntityDescriptor entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(TestdataImmovableChainedEntity.class);
return entityDescriptor.getGenuineVariableDescriptor("chainedObject");
}
private TestdataChainedObject chainedObject;
private boolean pinned;
public TestdataImmovableChainedEntity() {
}
public TestdataImmovableChainedEntity(String code) {
super(code);
}
public TestdataImmovableChainedEntity(String code, TestdataChainedObject chainedObject) {
this(code);
this.chainedObject = chainedObject;
}
public TestdataImmovableChainedEntity(String code, TestdataChainedObject chainedObject, boolean pinned) {
this(code, chainedObject);
this.pinned = pinned;
}
@PlanningVariable(valueRangeProviderRefs = {"chainedAnchorRange", "chainedEntityRange"},
graphType = PlanningVariableGraphType.CHAINED)
public TestdataChainedObject getChainedObject() {
return chainedObject;
}
public void setChainedObject(TestdataChainedObject chainedObject) {
this.chainedObject = chainedObject;
}
public boolean isPinned() {
return pinned;
}
public void setPinned(boolean pinned) {
this.pinned = pinned;
}
// ************************************************************************
// Complex methods
// ************************************************************************
}
| apache-2.0 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/util/ProcessEngineDetails.java | 1618 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.impl.util;
/**
* Holds process engine version and edition (enterprise or community)
* Used in retrieving the process engine details when sending telemetry data
*/
public class ProcessEngineDetails {
public static final String EDITION_ENTERPRISE = "enterprise";
public static final String EDITION_COMMUNITY = "community";
protected String version;
protected String edition;
public ProcessEngineDetails(String version, String edition) {
this.version = version;
this.edition = edition;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
}
| apache-2.0 |
hmunfru/fiware-paas | core/src/main/java/com/telefonica/euro_iaas/paasmanager/exception/InvalidEnvironmentInstanceException.java | 2148 | /**
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br>
* This file is part of FI-WARE project.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License.
* </p>
* <p>
* You may obtain a copy of the License at:<br>
* <br>
* http://www.apache.org/licenses/LICENSE-2.0
* </p>
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* </p>
* <p>
* See the License for the specific language governing permissions and limitations under the License.
* </p>
* <p>
* For those usages not covered by the Apache version 2.0 License please contact with opensource@tid.es
* </p>
*/
package com.telefonica.euro_iaas.paasmanager.exception;
import com.telefonica.euro_iaas.paasmanager.model.EnvironmentInstance;
/**
* Exception thrown when trying to insert a ProductRelease that does not have the right information
*
* @author Jesus M. Movilla
*/
@SuppressWarnings("serial")
public class InvalidEnvironmentInstanceException extends Exception {
private EnvironmentInstance environment;
public InvalidEnvironmentInstanceException() {
super();
}
public InvalidEnvironmentInstanceException(EnvironmentInstance environment) {
this.environment = environment;
}
public InvalidEnvironmentInstanceException(String msg) {
super(msg);
}
public InvalidEnvironmentInstanceException(String msg, Throwable e) {
super(msg, e);
}
public InvalidEnvironmentInstanceException(Throwable e) {
super(e);
}
/**
* @return the environmentInstance
*/
public EnvironmentInstance getEnvironment() {
return environment;
}
/**
* @param environmentInstance
* the environmentInstance to set
*/
public void setEnvironment(EnvironmentInstance environment) {
this.environment = environment;
}
}
| apache-2.0 |
ThiagoGarciaAlves/intellij-community | platform/platform-impl/src/com/intellij/execution/wsl/WSLUtil.java | 3074 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.wsl;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessListener;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import static com.intellij.execution.wsl.WSLDistributionLegacy.LEGACY_WSL;
/**
* Class for working with WSL after Fall Creators Update
* https://blogs.msdn.microsoft.com/commandline/2017/10/11/whats-new-in-wsl-in-windows-10-fall-creators-update/
* - multiple linuxes
* - file system is unavailable form windows (for now at least)
*/
public class WSLUtil {
/**
* this listener is a hack for https://github.com/Microsoft/BashOnWindows/issues/2592
* See RUBY-20358
*/
private static final ProcessListener INPUT_CLOSE_LISTENER = new ProcessAdapter() {
@Override
public void startNotified(@NotNull ProcessEvent event) {
OutputStream input = event.getProcessHandler().getProcessInput();
if (input != null) {
try {
input.flush();
input.close();
}
catch (IOException ignore) {
}
}
}
};
private static final List<WSLDistribution> DISTRIBUTIONS = Arrays.asList(
new WSLDistribution("UBUNTU", "Ubuntu", "ubuntu.exe", "Ubuntu"),
new WSLDistribution("OPENSUSE42", "openSUSE-42", "opensuse-42.exe", "openSUSE Leap 42"),
new WSLDistribution("SLES12", "SLES-12", "sles-12.exe", "SUSE Linux Enterprise Server 12"),
LEGACY_WSL
);
/**
* @return
*/
public static boolean hasAvailableDistributions() {
return getAvailableDistributions().size() > 0;
}
/**
* @return list of installed WSL distributions
*/
@NotNull
public static List<WSLDistribution> getAvailableDistributions() {
return ContainerUtil.filter(DISTRIBUTIONS, dist -> dist.isAvailable());
}
/**
* @return instance of WSL distribution or null if it's unavailable
*/
@Nullable
public static WSLDistribution getDistributionById(@Nullable String id) {
if (id == null) {
return null;
}
for (WSLDistribution distribution : getAvailableDistributions()) {
if (id.equals(distribution.getId())) {
return distribution;
}
}
return null;
}
/**
* Temporary hack method to fix <a href="https://github.com/Microsoft/BashOnWindows/issues/2592">WSL bug</a>
* Must be invoked just before execution, see RUBY-20358
*/
@NotNull
public static <T extends ProcessHandler> T addInputCloseListener(@NotNull T processHandler) {
processHandler.removeProcessListener(INPUT_CLOSE_LISTENER);
processHandler.addProcessListener(INPUT_CLOSE_LISTENER);
return processHandler;
}
}
| apache-2.0 |
routexl/graphhopper | core/src/main/java/com/graphhopper/routing/subnetwork/TarjanSCC.java | 12972 | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper.routing.subnetwork;
import com.carrotsearch.hppc.BitSet;
import com.carrotsearch.hppc.IntArrayDeque;
import com.carrotsearch.hppc.IntArrayList;
import com.carrotsearch.hppc.LongArrayDeque;
import com.graphhopper.routing.util.EdgeFilter;
import com.graphhopper.storage.Graph;
import com.graphhopper.util.BitUtil;
import com.graphhopper.util.EdgeExplorer;
import com.graphhopper.util.EdgeIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Tarjan's algorithm to find strongly connected components of a directed graph. Two nodes belong to the same connected
* component iff they are reachable from each other. Reachability from A to B is not necessarily equal to reachability
* from B to A because the graph is directed.
* <p>
* This class offers two ways to run the algorithm: Either using (function call) recursion {@link #findComponentsRecursive()}
* or recursion using an explicit stack {@link #findComponents()}. The first one is easier to implement and understand
* and the second one allows running the algorithm also on large graphs without having to deal with JVM stack size
* limits.
* <p>
* Tarjan's algorithm is explained for example here:
* - http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
* - http://www.timl.id.au/?p=327
* - http://homepages.ecs.vuw.ac.nz/~djp/files/P05.pdf
*
* @author easbar
*/
public class TarjanSCC {
private final Graph graph;
private final EdgeExplorer explorer;
private final EdgeFilter edgeFilter;
private final BitUtil bitUtil = BitUtil.LITTLE;
private final int[] nodeIndex;
private final int[] nodeLowLink;
private final BitSet nodeOnStack;
private final IntArrayDeque tarjanStack;
private final LongArrayDeque dfsStack;
private final ConnectedComponents components;
private final boolean excludeSingleNodeComponents;
private int currIndex = 0;
private int v;
private int w;
private State dfsState;
/**
* Runs Tarjan's algorithm using an explicit stack.
*
* @param excludeSingleNodeComponents if set to true components that only contain a single node will not be
* returned when calling {@link #findComponents} or {@link #findComponentsRecursive()},
* which can be useful to save some memory.
*/
public static ConnectedComponents findComponents(Graph graph, EdgeFilter edgeFilter, boolean excludeSingleNodeComponents) {
return new TarjanSCC(graph, edgeFilter, excludeSingleNodeComponents).findComponents();
}
/**
* Runs Tarjan's algorithm in a recursive way. Doing it like this requires a large stack size for large graphs,
* which can be set like `-Xss1024M`. Usually the version using an explicit stack ({@link #findComponents()}) should be
* preferred. However, this recursive implementation is easier to understand.
*
* @see #findComponents(Graph, EdgeFilter, boolean)
*/
public static ConnectedComponents findComponentsRecursive(Graph graph, EdgeFilter edgeFilter, boolean excludeSingleNodeComponents) {
return new TarjanSCC(graph, edgeFilter, excludeSingleNodeComponents).findComponentsRecursive();
}
private TarjanSCC(Graph graph, EdgeFilter edgeFilter, boolean excludeSingleNodeComponents) {
this.graph = graph;
this.edgeFilter = edgeFilter;
explorer = graph.createEdgeExplorer(edgeFilter);
nodeIndex = new int[graph.getNodes()];
nodeLowLink = new int[graph.getNodes()];
Arrays.fill(nodeIndex, -1);
Arrays.fill(nodeLowLink, -1);
nodeOnStack = new BitSet(graph.getNodes());
if (!nodeOnStack.getClass().getName().contains("hppc"))
throw new IllegalStateException("Was meant to be hppc BitSet");
tarjanStack = new IntArrayDeque();
dfsStack = new LongArrayDeque();
components = new ConnectedComponents(excludeSingleNodeComponents ? -1 : graph.getNodes());
this.excludeSingleNodeComponents = excludeSingleNodeComponents;
}
private enum State {
UPDATE,
HANDLE_NEIGHBOR,
FIND_COMPONENT,
BUILD_COMPONENT
}
private ConnectedComponents findComponentsRecursive() {
for (int node = 0; node < graph.getNodes(); node++) {
if (nodeIndex[node] == -1) {
findComponentForNode(node);
}
}
return components;
}
private void findComponentForNode(int v) {
setupNextNode(v);
// we have to create a new explorer on each iteration because of the nested edge iterations
EdgeExplorer explorer = graph.createEdgeExplorer(edgeFilter);
EdgeIterator iter = explorer.setBaseNode(v);
while (iter.next()) {
int w = iter.getAdjNode();
if (nodeIndex[w] == -1) {
findComponentForNode(w);
nodeLowLink[v] = Math.min(nodeLowLink[v], nodeLowLink[w]);
} else if (nodeOnStack.get(w))
nodeLowLink[v] = Math.min(nodeLowLink[v], nodeIndex[w]);
}
buildComponent(v);
}
private void setupNextNode(int v) {
nodeIndex[v] = currIndex;
nodeLowLink[v] = currIndex;
currIndex++;
tarjanStack.addLast(v);
nodeOnStack.set(v);
}
private void buildComponent(int v) {
if (nodeLowLink[v] == nodeIndex[v]) {
if (tarjanStack.getLast() == v) {
tarjanStack.removeLast();
nodeOnStack.clear(v);
components.numComponents++;
components.numNodes++;
if (!excludeSingleNodeComponents)
components.singleNodeComponents.set(v);
} else {
IntArrayList component = new IntArrayList();
while (true) {
int w = tarjanStack.removeLast();
component.add(w);
nodeOnStack.clear(w);
if (w == v)
break;
}
component.trimToSize();
assert component.size() > 1;
components.numComponents++;
components.numNodes += component.size();
components.components.add(component);
if (component.size() > components.biggestComponent.size())
components.biggestComponent = component;
}
}
}
private ConnectedComponents findComponents() {
for (int node = 0; node < graph.getNodes(); ++node) {
if (nodeIndex[node] != -1)
continue;
pushFindComponentForNode(node);
while (hasNext()) {
pop();
switch (dfsState) {
case BUILD_COMPONENT:
buildComponent(v);
break;
case UPDATE:
nodeLowLink[v] = Math.min(nodeLowLink[v], nodeLowLink[w]);
break;
case HANDLE_NEIGHBOR: {
if (nodeIndex[w] != -1 && nodeOnStack.get(w))
nodeLowLink[v] = Math.min(nodeLowLink[v], nodeIndex[w]);
if (nodeIndex[w] == -1) {
// we are pushing updateLowLinks first so it will run *after* findComponent finishes
pushUpdateLowLinks(v, w);
pushFindComponentForNode(w);
}
break;
}
case FIND_COMPONENT: {
setupNextNode(v);
// we push buildComponent first so it will run *after* we finished traversing the edges
pushBuildComponent(v);
EdgeIterator iter = explorer.setBaseNode(v);
while (iter.next()) {
pushHandleNeighbor(v, iter.getAdjNode());
}
break;
}
default:
throw new IllegalStateException("Unknown state: " + dfsState);
}
}
}
return components;
}
private boolean hasNext() {
return !dfsStack.isEmpty();
}
private void pop() {
long l = dfsStack.removeLast();
// We are maintaining a stack of longs to hold three kinds of information: two node indices (v&w) and the kind
// of code ('state') we want to execute for a given stack item. The following code combined with the pushXYZ
// methods does the fwd/bwd conversion between this information and a single long value.
int low = bitUtil.getIntLow(l);
int high = bitUtil.getIntHigh(l);
if (low > 0 && high > 0) {
dfsState = State.HANDLE_NEIGHBOR;
v = low - 1;
w = high - 1;
} else if (low > 0 && high < 0) {
dfsState = State.UPDATE;
v = low - 1;
w = -high - 1;
} else if (low == 0) {
dfsState = State.BUILD_COMPONENT;
v = high - 1;
w = -1;
} else {
dfsState = State.FIND_COMPONENT;
v = low - 1;
w = -1;
}
}
private void pushHandleNeighbor(int v, int w) {
assert v >= 0 && v < Integer.MAX_VALUE;
assert w >= 0 && w < Integer.MAX_VALUE;
dfsStack.addLast(bitUtil.combineIntsToLong(v + 1, w + 1));
}
private void pushUpdateLowLinks(int v, int w) {
assert v >= 0 && v < Integer.MAX_VALUE;
assert w >= 0 && w < Integer.MAX_VALUE;
dfsStack.addLast(bitUtil.combineIntsToLong(v + 1, -(w + 1)));
}
private void pushBuildComponent(int v) {
assert v >= 0 && v < Integer.MAX_VALUE;
dfsStack.addLast(bitUtil.combineIntsToLong(0, v + 1));
}
private void pushFindComponentForNode(int v) {
assert v >= 0 && v < Integer.MAX_VALUE;
dfsStack.addLast(bitUtil.combineIntsToLong(v + 1, 0));
}
public static class ConnectedComponents {
private final List<IntArrayList> components;
private final BitSet singleNodeComponents;
private IntArrayList biggestComponent;
private int numComponents;
private int numNodes;
ConnectedComponents(int nodes) {
components = new ArrayList<>();
singleNodeComponents = new BitSet(Math.max(nodes, 0));
if (!(singleNodeComponents.getClass().getName().contains("hppc")))
throw new IllegalStateException("Was meant to be hppc BitSet");
biggestComponent = new IntArrayList();
}
/**
* A list of arrays each containing the nodes of a strongly connected component. Components with only a single
* node are not included here, but need to be obtained using {@link #getSingleNodeComponents()}.
*/
public List<IntArrayList> getComponents() {
return components;
}
/**
* The set of nodes that form their own (single-node) component. If {@link TarjanSCC#excludeSingleNodeComponents}
* is enabled this set will be empty.
*/
public BitSet getSingleNodeComponents() {
return singleNodeComponents;
}
/**
* The total number of strongly connected components. This always includes single-node components.
*/
public int getTotalComponents() {
return numComponents;
}
/**
* A reference to the biggest component contained in {@link #getComponents()} or an empty list if there are
* either no components or the biggest component has only a single node (and hence {@link #getComponents()} is
* empty).
*/
public IntArrayList getBiggestComponent() {
return biggestComponent;
}
public int getNodes() {
return numNodes;
}
}
}
| apache-2.0 |
christophd/camel | components/camel-jetty-common/src/main/java/org/apache/camel/component/jetty/JettyHttpBinding.java | 4926 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.jetty;
import org.apache.camel.Exchange;
import org.apache.camel.spi.HeaderFilterStrategy;
/**
* Jetty specific binding to parse the request/response from Jetty and Camel.
*/
public interface JettyHttpBinding {
/**
* Parses the response from the Jetty client.
*
* @param exchange the Exchange which to populate with the response
* @param httpExchange the response from the Jetty client
* @throws Exception is thrown if error parsing response
*/
void populateResponse(Exchange exchange, JettyContentExchange httpExchange) throws Exception;
/**
* Gets the header filter strategy
*
* @return the strategy
*/
HeaderFilterStrategy getHeaderFilterStrategy();
/**
* Sets the header filter strategy to use.
* <p/>
* Will default use {@link org.apache.camel.http.common.HttpHeaderFilterStrategy}
*
* @param headerFilterStrategy the custom strategy
*/
void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy);
/**
* Whether to throw {@link org.apache.camel.http.base.HttpOperationFailedException} in case of response code != 200.
*
* @param throwExceptionOnFailure <tt>true</tt> to throw exception
*/
void setThrowExceptionOnFailure(boolean throwExceptionOnFailure);
/**
* Whether to throw {@link org.apache.camel.http.base.HttpOperationFailedException} in case of response code != 200.
*
* @return <tt>true</tt> to throw exception
*/
boolean isThrowExceptionOnFailure();
/**
* Whether to transfer exception back as a serialized java object if processing failed due to an exception
* <p/>
* This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from
* the request to Java and that can be a potential security risk.
*
* @param transferException <tt>true</tt> to transfer exception
*/
void setTransferException(boolean transferException);
/**
* Whether to transfer exception back as a serialized java object if processing failed due to an exception
* <p/>
* This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from
* the request to Java and that can be a potential security risk.
*
* @return <tt>true</tt> to transfer exception
*/
boolean isTransferException();
/**
* Whether to allow java serialization when a request uses context-type=application/x-java-serialized-object
* <p/>
* This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from
* the request to Java and that can be a potential security risk.
*
* @param allowJavaSerializedObject <tt>true</tt> to allow serializing java objects
*/
void setAllowJavaSerializedObject(boolean allowJavaSerializedObject);
/**
* Whether to allow java serialization when a request uses context-type=application/x-java-serialized-object
* <p/>
* This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from
* the request to Java and that can be a potential security risk.
*/
boolean isAllowJavaSerializedObject();
/**
* The status codes which are considered a success response. The values are inclusive. Multiple ranges can be
* defined, separated by comma, e.g. <tt>200-204,209,301-304</tt>. Each range must be a single number or from-to
* with the dash included.
* <p/>
* The default range is <tt>200-299</tt>
*/
String getOkStatusCodeRange();
/**
* The status codes which are considered a success response. The values are inclusive. Multiple ranges can be
* defined, separated by comma, e.g. <tt>200-204,209,301-304</tt>. Each range must be a single number or from-to
* with the dash included.
* <p/>
* The default range is <tt>200-299</tt>
*/
void setOkStatusCodeRange(String okStatusCodeRange);
}
| apache-2.0 |
vt09/bazel | src/test/java/com/google/devtools/build/lib/ideinfo/AndroidStudioInfoAspectTest.java | 23366 | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.ideinfo;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.BuildView.AnalysisResult;
import com.google.devtools.build.lib.analysis.actions.BinaryFileWriteAction;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.ArtifactLocation;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.JavaRuleIdeInfo;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.LibraryArtifact;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.RuleIdeInfo;
import com.google.devtools.build.lib.ideinfo.androidstudio.AndroidStudioIdeInfo.RuleIdeInfo.Kind;
import com.google.devtools.build.lib.skyframe.AspectValue;
import com.google.devtools.build.lib.vfs.Path;
import java.util.Collection;
import java.util.Map;
import javax.annotation.Nullable;
/**
* Tests for {@link AndroidStudioInfoAspect} validating proto's contents.
*/
public class AndroidStudioInfoAspectTest extends BuildViewTestCase {
public static final Function<ArtifactLocation, String> ARTIFACT_TO_RELATIVE_PATH =
new Function<ArtifactLocation, String>() {
@Nullable
@Override
public String apply(ArtifactLocation artifactLocation) {
return artifactLocation.getRelativePath();
}
};
public static final Function<LibraryArtifact, String> LIBRARY_ARTIFACT_TO_STRING =
new Function<LibraryArtifact, String>() {
@Override
public String apply(LibraryArtifact libraryArtifact) {
StringBuilder stringBuilder = new StringBuilder();
if (libraryArtifact.hasJar()) {
stringBuilder.append("<jar:");
stringBuilder.append(libraryArtifact.getJar().getRelativePath());
stringBuilder.append(">");
}
if (libraryArtifact.hasInterfaceJar()) {
stringBuilder.append("<ijar:");
stringBuilder.append(libraryArtifact.getInterfaceJar().getRelativePath());
stringBuilder.append(">");
}
if (libraryArtifact.hasSourceJar()) {
stringBuilder.append("<source:");
stringBuilder.append(libraryArtifact.getSourceJar().getRelativePath());
stringBuilder.append(">");
}
return stringBuilder.toString();
}
};
public void testSimpleJavaLibrary() throws Exception {
Path buildFilePath =
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'simple',",
" srcs = ['simple/Simple.java']",
")",
"java_library(",
" name = 'complex',",
" srcs = ['complex/Complex.java'],",
" deps = [':simple']",
")");
String target = "//com/google/example:simple";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
assertThat(ruleIdeInfos.size()).isEqualTo(1);
RuleIdeInfo ruleIdeInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(ruleIdeInfo.getBuildFile()).isEqualTo(buildFilePath.toString());
assertThat(ruleIdeInfo.getKind()).isEqualTo(Kind.JAVA_LIBRARY);
assertThat(ruleIdeInfo.getDependenciesCount()).isEqualTo(0);
assertThat(relativePathsForSourcesOf(ruleIdeInfo))
.containsExactly("com/google/example/simple/Simple.java");
assertThat(
transform(ruleIdeInfo.getJavaRuleIdeInfo().getJarsList(), LIBRARY_ARTIFACT_TO_STRING))
.containsExactly(
"<jar:com/google/example/libsimple.jar><source:com/google/example/libsimple-src.jar>");
}
private static Iterable<String> relativePathsForSourcesOf(RuleIdeInfo ruleIdeInfo) {
return transform(ruleIdeInfo.getJavaRuleIdeInfo().getSourcesList(), ARTIFACT_TO_RELATIVE_PATH);
}
private RuleIdeInfo getRuleInfoAndVerifyLabel(
String target, Map<String, RuleIdeInfo> ruleIdeInfos) {
RuleIdeInfo ruleIdeInfo = ruleIdeInfos.get(target);
assertThat(ruleIdeInfo.getLabel()).isEqualTo(target);
return ruleIdeInfo;
}
public void testJavaLibraryProtoWithDependencies() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'simple',",
" srcs = ['simple/Simple.java']",
")",
"java_library(",
" name = 'complex',",
" srcs = ['complex/Complex.java'],",
" deps = [':simple']",
")");
String target = "//com/google/example:complex";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
assertThat(ruleIdeInfos.size()).isEqualTo(2);
getRuleInfoAndVerifyLabel("//com/google/example:simple", ruleIdeInfos);
RuleIdeInfo complexRuleIdeInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(relativePathsForSourcesOf(complexRuleIdeInfo))
.containsExactly("com/google/example/complex/Complex.java");
assertThat(complexRuleIdeInfo.getDependenciesList())
.containsExactly("//com/google/example:simple");
assertThat(complexRuleIdeInfo.getTransitiveDependenciesList())
.containsExactly("//com/google/example:simple");
}
public void testJavaLibraryWithTransitiveDependencies() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'simple',",
" srcs = ['simple/Simple.java']",
")",
"java_library(",
" name = 'complex',",
" srcs = ['complex/Complex.java'],",
" deps = [':simple']",
")",
"java_library(",
" name = 'extracomplex',",
" srcs = ['extracomplex/ExtraComplex.java'],",
" deps = [':complex']",
")");
String target = "//com/google/example:extracomplex";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
assertThat(ruleIdeInfos.size()).isEqualTo(3);
getRuleInfoAndVerifyLabel("//com/google/example:simple", ruleIdeInfos);
getRuleInfoAndVerifyLabel("//com/google/example:complex", ruleIdeInfos);
RuleIdeInfo extraComplexRuleIdeInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(relativePathsForSourcesOf(extraComplexRuleIdeInfo))
.containsExactly("com/google/example/extracomplex/ExtraComplex.java");
assertThat(extraComplexRuleIdeInfo.getDependenciesList())
.containsExactly("//com/google/example:complex");
assertThat(extraComplexRuleIdeInfo.getTransitiveDependenciesList())
.containsExactly("//com/google/example:complex", "//com/google/example:simple");
}
public void testJavaLibraryWithDiamondDependencies() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'simple',",
" srcs = ['simple/Simple.java']",
")",
"java_library(",
" name = 'complex',",
" srcs = ['complex/Complex.java'],",
" deps = [':simple']",
")",
"java_library(",
" name = 'complex1',",
" srcs = ['complex1/Complex.java'],",
" deps = [':simple']",
")",
"java_library(",
" name = 'extracomplex',",
" srcs = ['extracomplex/ExtraComplex.java'],",
" deps = [':complex', ':complex1']",
")");
String target = "//com/google/example:extracomplex";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
assertThat(ruleIdeInfos.size()).isEqualTo(4);
getRuleInfoAndVerifyLabel("//com/google/example:simple", ruleIdeInfos);
getRuleInfoAndVerifyLabel("//com/google/example:complex", ruleIdeInfos);
getRuleInfoAndVerifyLabel("//com/google/example:complex1", ruleIdeInfos);
RuleIdeInfo extraComplexRuleIdeInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(relativePathsForSourcesOf(extraComplexRuleIdeInfo))
.containsExactly("com/google/example/extracomplex/ExtraComplex.java");
assertThat(extraComplexRuleIdeInfo.getDependenciesList())
.containsExactly("//com/google/example:complex", "//com/google/example:complex1");
assertThat(extraComplexRuleIdeInfo.getTransitiveDependenciesList())
.containsExactly(
"//com/google/example:complex",
"//com/google/example:complex1",
"//com/google/example:simple");
}
public void testJavaLibraryWithExports() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'simple',",
" srcs = ['simple/Simple.java']",
")",
"java_library(",
" name = 'complex',",
" srcs = ['complex/Complex.java'],",
" deps = [':simple'],",
" exports = [':simple'],",
")",
"java_library(",
" name = 'extracomplex',",
" srcs = ['extracomplex/ExtraComplex.java'],",
" deps = [':complex']",
")");
String target = "//com/google/example:extracomplex";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
assertThat(ruleIdeInfos.size()).isEqualTo(3);
getRuleInfoAndVerifyLabel("//com/google/example:simple", ruleIdeInfos);
getRuleInfoAndVerifyLabel("//com/google/example:complex", ruleIdeInfos);
RuleIdeInfo extraComplexRuleIdeInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(relativePathsForSourcesOf(extraComplexRuleIdeInfo))
.containsExactly("com/google/example/extracomplex/ExtraComplex.java");
assertThat(extraComplexRuleIdeInfo.getDependenciesList())
.containsExactly("//com/google/example:complex", "//com/google/example:simple");
assertThat(extraComplexRuleIdeInfo.getTransitiveDependenciesList())
.containsExactly(
"//com/google/example:complex",
"//com/google/example:simple");
}
public void testJavaLibraryWithTransitiveExports() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'simple',",
" srcs = ['simple/Simple.java']",
")",
"java_library(",
" name = 'complex',",
" srcs = ['complex/Complex.java'],",
" deps = [':simple'],",
" exports = [':simple'],",
")",
"java_library(",
" name = 'extracomplex',",
" srcs = ['extracomplex/ExtraComplex.java'],",
" deps = [':complex'],",
" exports = [':complex'],",
")",
"java_library(",
" name = 'megacomplex',",
" srcs = ['megacomplex/MegaComplex.java'],",
" deps = [':extracomplex'],",
")"
);
String target = "//com/google/example:megacomplex";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
assertThat(ruleIdeInfos.size()).isEqualTo(4);
getRuleInfoAndVerifyLabel("//com/google/example:simple", ruleIdeInfos);
getRuleInfoAndVerifyLabel("//com/google/example:complex", ruleIdeInfos);
getRuleInfoAndVerifyLabel("//com/google/example:extracomplex", ruleIdeInfos);
RuleIdeInfo megaComplexRuleIdeInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(relativePathsForSourcesOf(megaComplexRuleIdeInfo))
.containsExactly("com/google/example/megacomplex/MegaComplex.java");
assertThat(megaComplexRuleIdeInfo.getDependenciesList())
.containsExactly(
"//com/google/example:extracomplex",
"//com/google/example:complex",
"//com/google/example:simple");
assertThat(megaComplexRuleIdeInfo.getTransitiveDependenciesList())
.containsExactly(
"//com/google/example:extracomplex",
"//com/google/example:complex",
"//com/google/example:simple");
}
public void testJavaImport() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_import(",
" name = 'imp',",
" jars = ['a.jar', 'b.jar'],",
" srcjar = 'impsrc.jar',",
")",
"java_library(",
" name = 'lib',",
" srcs = ['Lib.java'],",
" deps = [':imp'],",
")");
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo("//com/google/example:lib");
final RuleIdeInfo libInfo = getRuleInfoAndVerifyLabel("//com/google/example:lib", ruleIdeInfos);
RuleIdeInfo impInfo = getRuleInfoAndVerifyLabel("//com/google/example:imp", ruleIdeInfos);
assertThat(impInfo.getKind()).isEqualTo(Kind.JAVA_IMPORT);
assertThat(libInfo.getDependenciesList()).containsExactly("//com/google/example:imp");
JavaRuleIdeInfo javaRuleIdeInfo = impInfo.getJavaRuleIdeInfo();
assertThat(javaRuleIdeInfo).isNotNull();
assertThat(transform(javaRuleIdeInfo.getJarsList(), LIBRARY_ARTIFACT_TO_STRING))
.containsExactly(
"<jar:com/google/example/a.jar><source:com/google/example/impsrc.jar>",
"<jar:com/google/example/b.jar><source:com/google/example/impsrc.jar>");
}
public void testJavaImportWithExports() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'foobar',",
" srcs = ['FooBar.java'],",
")",
"java_import(",
" name = 'imp',",
" jars = ['a.jar', 'b.jar'],",
" deps = [':foobar'],",
" exports = [':foobar'],",
")",
"java_library(",
" name = 'lib',",
" srcs = ['Lib.java'],",
" deps = [':imp'],",
")");
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo("//com/google/example:lib");
RuleIdeInfo libInfo = getRuleInfoAndVerifyLabel("//com/google/example:lib", ruleIdeInfos);
RuleIdeInfo impInfo = getRuleInfoAndVerifyLabel("//com/google/example:imp", ruleIdeInfos);
assertThat(impInfo.getKind()).isEqualTo(Kind.JAVA_IMPORT);
assertThat(impInfo.getDependenciesList()).containsExactly("//com/google/example:foobar");
assertThat(libInfo.getDependenciesList())
.containsExactly("//com/google/example:imp", "//com/google/example:foobar");
}
public void testJavaTest() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'foobar',",
" srcs = ['FooBar.java'],",
")",
"java_test(",
" name = 'foobar-test',",
" test_class = 'MyTestClass',",
" srcs = ['FooBarTest.java'],",
" deps = [':foobar'],",
")");
String target = "//com/google/example:foobar-test";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
RuleIdeInfo testInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(testInfo.getKind()).isEqualTo(Kind.JAVA_TEST);
assertThat(relativePathsForSourcesOf(testInfo))
.containsExactly("com/google/example/FooBarTest.java");
assertThat(testInfo.getDependenciesList()).containsExactly("//com/google/example:foobar");
assertThat(transform(testInfo.getJavaRuleIdeInfo().getJarsList(), LIBRARY_ARTIFACT_TO_STRING))
.containsExactly(
"<jar:com/google/example/foobar-test.jar><source:com/google/example/foobar-test-src.jar>");
}
public void testJavaBinary() throws Exception {
scratch.file(
"com/google/example/BUILD",
"java_library(",
" name = 'foobar',",
" srcs = ['FooBar.java'],",
")",
"java_binary(",
" name = 'foobar-exe',",
" main_class = 'MyMainClass',",
" srcs = ['FooBarMain.java'],",
" deps = [':foobar'],",
")");
String target = "//com/google/example:foobar-exe";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
RuleIdeInfo binaryInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(binaryInfo.getKind()).isEqualTo(Kind.JAVA_BINARY);
assertThat(relativePathsForSourcesOf(binaryInfo))
.containsExactly("com/google/example/FooBarMain.java");
assertThat(binaryInfo.getDependenciesList()).containsExactly("//com/google/example:foobar");
assertThat(transform(binaryInfo.getJavaRuleIdeInfo().getJarsList(), LIBRARY_ARTIFACT_TO_STRING))
.containsExactly(
"<jar:com/google/example/foobar-exe.jar><source:com/google/example/foobar-exe-src.jar>");
}
public void testAndroidLibrary() throws Exception {
scratch.file(
"com/google/example/BUILD",
"android_library(",
" name = 'l1',",
" manifest = 'Manifesto.xml',",
" custom_package = 'com.google.example',",
" resource_files = ['r1/values/a.xml'],",
")",
"android_library(",
" name = 'l',",
" srcs = ['Main.java'],",
" deps = [':l1'],",
" manifest = 'Abracadabra.xml',",
" custom_package = 'com.google.example',",
" resource_files = ['res/drawable/a.png', 'res/drawable/b.png'],",
")");
String target = "//com/google/example:l";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
RuleIdeInfo ruleInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(ruleInfo.getKind()).isEqualTo(Kind.ANDROID_LIBRARY);
assertThat(relativePathsForSourcesOf(ruleInfo)).containsExactly("com/google/example/Main.java");
assertThat(transform(ruleInfo.getJavaRuleIdeInfo().getJarsList(), LIBRARY_ARTIFACT_TO_STRING))
.containsExactly("<jar:com/google/example/libl.jar>");
assertThat(
transform(
ruleInfo.getAndroidRuleIdeInfo().getResourcesList(), ARTIFACT_TO_RELATIVE_PATH))
.containsExactly("com/google/example/res");
assertThat(ruleInfo.getAndroidRuleIdeInfo().getManifest().getRelativePath())
.isEqualTo("com/google/example/Abracadabra.xml");
assertThat(ruleInfo.getAndroidRuleIdeInfo().getJavaPackage()).isEqualTo("com.google.example");
assertThat(ruleInfo.getDependenciesList()).containsExactly("//com/google/example:l1");
assertThat(
transform(
ruleInfo.getAndroidRuleIdeInfo().getTransitiveResourcesList(),
ARTIFACT_TO_RELATIVE_PATH))
.containsExactly("com/google/example/res", "com/google/example/r1");
}
public void testAndroidBinary() throws Exception {
scratch.file(
"com/google/example/BUILD",
"android_library(",
" name = 'l1',",
" manifest = 'Manifesto.xml',",
" custom_package = 'com.google.example',",
" resource_files = ['r1/values/a.xml'],",
")",
"android_binary(",
" name = 'b',",
" srcs = ['Main.java'],",
" deps = [':l1'],",
" manifest = 'Abracadabra.xml',",
" custom_package = 'com.google.example',",
" resource_files = ['res/drawable/a.png', 'res/drawable/b.png'],",
")");
String target = "//com/google/example:b";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
RuleIdeInfo ruleInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(ruleInfo.getKind()).isEqualTo(Kind.ANDROID_BINARY);
assertThat(relativePathsForSourcesOf(ruleInfo)).containsExactly("com/google/example/Main.java");
assertThat(transform(ruleInfo.getJavaRuleIdeInfo().getJarsList(), LIBRARY_ARTIFACT_TO_STRING))
.containsExactly(
"<jar:com/google/example/libb.jar><source:com/google/example/libb-src.jar>");
assertThat(
transform(
ruleInfo.getAndroidRuleIdeInfo().getResourcesList(), ARTIFACT_TO_RELATIVE_PATH))
.containsExactly("com/google/example/res");
assertThat(ruleInfo.getAndroidRuleIdeInfo().getManifest().getRelativePath())
.isEqualTo("com/google/example/Abracadabra.xml");
assertThat(ruleInfo.getAndroidRuleIdeInfo().getJavaPackage()).isEqualTo("com.google.example");
assertThat(ruleInfo.getDependenciesList()).containsExactly("//com/google/example:l1");
assertThat(
transform(
ruleInfo.getAndroidRuleIdeInfo().getTransitiveResourcesList(),
ARTIFACT_TO_RELATIVE_PATH))
.containsExactly("com/google/example/res", "com/google/example/r1");
}
public void testAndroidInferredPackage() throws Exception {
scratch.file(
"java/com/google/example/BUILD",
"android_library(",
" name = 'l',",
" manifest = 'Manifesto.xml',",
")",
"android_binary(",
" name = 'b',",
" srcs = ['Main.java'],",
" deps = [':l'],",
" manifest = 'Abracadabra.xml',",
")");
String target = "//java/com/google/example:b";
Map<String, RuleIdeInfo> ruleIdeInfos = buildRuleIdeInfo(target);
RuleIdeInfo lRuleInfo = getRuleInfoAndVerifyLabel("//java/com/google/example:l", ruleIdeInfos);
RuleIdeInfo bRuleInfo = getRuleInfoAndVerifyLabel(target, ruleIdeInfos);
assertThat(bRuleInfo.getAndroidRuleIdeInfo().getJavaPackage()).isEqualTo("com.google.example");
assertThat(lRuleInfo.getAndroidRuleIdeInfo().getJavaPackage()).isEqualTo("com.google.example");
}
private Map<String, RuleIdeInfo> buildRuleIdeInfo(String target) throws Exception {
AnalysisResult analysisResult =
update(
ImmutableList.of(target),
ImmutableList.of(AndroidStudioInfoAspect.NAME),
false,
LOADING_PHASE_THREADS,
true,
new EventBus());
Collection<AspectValue> aspects = analysisResult.getAspects();
assertThat(aspects.size()).isEqualTo(1);
AspectValue value = aspects.iterator().next();
assertThat(value.getAspect().getName()).isEqualTo(AndroidStudioInfoAspect.NAME);
AndroidStudioInfoFilesProvider provider =
value.getAspect().getProvider(AndroidStudioInfoFilesProvider.class);
Iterable<Artifact> artifacts = provider.getIdeBuildFiles();
ImmutableMap.Builder<String, RuleIdeInfo> builder = ImmutableMap.builder();
for (Artifact artifact : artifacts) {
BinaryFileWriteAction generatingAction =
(BinaryFileWriteAction) getGeneratingAction(artifact);
RuleIdeInfo ruleIdeInfo = RuleIdeInfo.parseFrom(generatingAction.getSource().openStream());
builder.put(ruleIdeInfo.getLabel(), ruleIdeInfo);
}
return builder.build();
}
}
| apache-2.0 |
zstackorg/zstack | plugin/eip/src/main/java/org/zstack/network/service/eip/WorkOutEipStructureExtensionPoint.java | 274 | package org.zstack.network.service.eip;
import org.zstack.header.vm.VmInstanceSpec;
import java.util.List;
import java.util.Map;
public interface WorkOutEipStructureExtensionPoint {
void afterWorkOutEipStruct(VmInstanceSpec spec, Map<String, List<EipStruct>> map);
}
| apache-2.0 |
Bizyroth/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/balancer/TestBalancerWithMultipleNameNodes.java | 13597 | /**
* 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.hdfs.server.balancer;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeoutException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSNNTopology;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.log4j.Level;
import org.junit.Assert;
import org.junit.Test;
/**
* Test balancer with multiple NameNodes
*/
public class TestBalancerWithMultipleNameNodes {
static final Log LOG = Balancer.LOG;
{
((Log4JLogger)LOG).getLogger().setLevel(Level.ALL);
DFSTestUtil.setNameNodeLogLevel(Level.ALL);
}
private static final long CAPACITY = 500L;
private static final String RACK0 = "/rack0";
private static final String RACK1 = "/rack1";
private static final String FILE_NAME = "/tmp.txt";
private static final Path FILE_PATH = new Path(FILE_NAME);
private static final Random RANDOM = new Random();
static {
TestBalancer.initTestSetup();
}
/** Common objects used in various methods. */
private static class Suite {
final Configuration conf;
final MiniDFSCluster cluster;
final ClientProtocol[] clients;
final short replication;
Suite(MiniDFSCluster cluster, final int nNameNodes, final int nDataNodes,
Configuration conf) throws IOException {
this.conf = conf;
this.cluster = cluster;
clients = new ClientProtocol[nNameNodes];
for(int i = 0; i < nNameNodes; i++) {
clients[i] = cluster.getNameNode(i).getRpcServer();
}
replication = (short)Math.max(1, nDataNodes - 1);
}
}
/* create a file with a length of <code>fileLen</code> */
private static void createFile(Suite s, int index, long len
) throws IOException, InterruptedException, TimeoutException {
final FileSystem fs = s.cluster.getFileSystem(index);
DFSTestUtil.createFile(fs, FILE_PATH, len, s.replication, RANDOM.nextLong());
DFSTestUtil.waitReplication(fs, FILE_PATH, s.replication);
}
/* fill up a cluster with <code>numNodes</code> datanodes
* whose used space to be <code>size</code>
*/
private static ExtendedBlock[][] generateBlocks(Suite s, long size
) throws IOException, InterruptedException, TimeoutException {
final ExtendedBlock[][] blocks = new ExtendedBlock[s.clients.length][];
for(int n = 0; n < s.clients.length; n++) {
final long fileLen = size/s.replication;
createFile(s, n, fileLen);
final List<LocatedBlock> locatedBlocks = s.clients[n].getBlockLocations(
FILE_NAME, 0, fileLen).getLocatedBlocks();
final int numOfBlocks = locatedBlocks.size();
blocks[n] = new ExtendedBlock[numOfBlocks];
for(int i = 0; i < numOfBlocks; i++) {
final ExtendedBlock b = locatedBlocks.get(i).getBlock();
blocks[n][i] = new ExtendedBlock(b.getBlockPoolId(), b.getBlockId(),
b.getNumBytes(), b.getGenerationStamp());
}
}
return blocks;
}
/* wait for one heartbeat */
static void wait(final ClientProtocol[] clients,
long expectedUsedSpace, long expectedTotalSpace) throws IOException {
LOG.info("WAIT expectedUsedSpace=" + expectedUsedSpace
+ ", expectedTotalSpace=" + expectedTotalSpace);
for(int n = 0; n < clients.length; n++) {
int i = 0;
for(boolean done = false; !done; ) {
final long[] s = clients[n].getStats();
done = s[0] == expectedTotalSpace && s[1] == expectedUsedSpace;
if (!done) {
sleep(100L);
if (++i % 100 == 0) {
LOG.warn("WAIT i=" + i + ", s=[" + s[0] + ", " + s[1] + "]");
}
}
}
}
}
static void runBalancer(Suite s,
final long totalUsed, final long totalCapacity) throws Exception {
final double avg = totalUsed*100.0/totalCapacity;
LOG.info("BALANCER 0: totalUsed=" + totalUsed
+ ", totalCapacity=" + totalCapacity
+ ", avg=" + avg);
wait(s.clients, totalUsed, totalCapacity);
LOG.info("BALANCER 1");
// start rebalancing
final Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(s.conf);
final int r = Balancer.run(namenodes, Balancer.Parameters.DEFAULT, s.conf);
Assert.assertEquals(ExitStatus.SUCCESS.getExitCode(), r);
LOG.info("BALANCER 2");
wait(s.clients, totalUsed, totalCapacity);
LOG.info("BALANCER 3");
int i = 0;
for(boolean balanced = false; !balanced; i++) {
final long[] used = new long[s.cluster.getDataNodes().size()];
final long[] cap = new long[used.length];
for(int n = 0; n < s.clients.length; n++) {
final DatanodeInfo[] datanodes = s.clients[n].getDatanodeReport(
DatanodeReportType.ALL);
Assert.assertEquals(datanodes.length, used.length);
for(int d = 0; d < datanodes.length; d++) {
if (n == 0) {
used[d] = datanodes[d].getDfsUsed();
cap[d] = datanodes[d].getCapacity();
if (i % 100 == 0) {
LOG.warn("datanodes[" + d
+ "]: getDfsUsed()=" + datanodes[d].getDfsUsed()
+ ", getCapacity()=" + datanodes[d].getCapacity());
}
} else {
Assert.assertEquals(used[d], datanodes[d].getDfsUsed());
Assert.assertEquals(cap[d], datanodes[d].getCapacity());
}
}
}
balanced = true;
for(int d = 0; d < used.length; d++) {
final double p = used[d]*100.0/cap[d];
balanced = p <= avg + Balancer.Parameters.DEFAULT.threshold;
if (!balanced) {
if (i % 100 == 0) {
LOG.warn("datanodes " + d + " is not yet balanced: "
+ "used=" + used[d] + ", cap=" + cap[d] + ", avg=" + avg);
LOG.warn("TestBalancer.sum(used)=" + TestBalancer.sum(used)
+ ", TestBalancer.sum(cap)=" + TestBalancer.sum(cap));
}
sleep(100);
break;
}
}
}
LOG.info("BALANCER 6");
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch(InterruptedException e) {
LOG.error(e);
}
}
private static Configuration createConf() {
final Configuration conf = new HdfsConfiguration();
TestBalancer.initConf(conf);
return conf;
}
/**
* First start a cluster and fill the cluster up to a certain size.
* Then redistribute blocks according the required distribution.
* Finally, balance the cluster.
*
* @param nNameNodes Number of NameNodes
* @param distributionPerNN The distribution for each NameNode.
* @param capacities Capacities of the datanodes
* @param racks Rack names
* @param conf Configuration
*/
private void unevenDistribution(final int nNameNodes,
long distributionPerNN[], long capacities[], String[] racks,
Configuration conf) throws Exception {
LOG.info("UNEVEN 0");
final int nDataNodes = distributionPerNN.length;
if (capacities.length != nDataNodes || racks.length != nDataNodes) {
throw new IllegalArgumentException("Array length is not the same");
}
// calculate total space that need to be filled
final long usedSpacePerNN = TestBalancer.sum(distributionPerNN);
// fill the cluster
final ExtendedBlock[][] blocks;
{
LOG.info("UNEVEN 1");
final MiniDFSCluster cluster = new MiniDFSCluster
.Builder(new Configuration(conf))
.nnTopology(MiniDFSNNTopology.simpleFederatedTopology(2))
.numDataNodes(nDataNodes)
.racks(racks)
.simulatedCapacities(capacities)
.build();
LOG.info("UNEVEN 2");
try {
cluster.waitActive();
DFSTestUtil.setFederatedConfiguration(cluster, conf);
LOG.info("UNEVEN 3");
final Suite s = new Suite(cluster, nNameNodes, nDataNodes, conf);
blocks = generateBlocks(s, usedSpacePerNN);
LOG.info("UNEVEN 4");
} finally {
cluster.shutdown();
}
}
conf.set(DFSConfigKeys.DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY, "0.0f");
{
LOG.info("UNEVEN 10");
final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.nnTopology(MiniDFSNNTopology.simpleFederatedTopology(nNameNodes))
.numDataNodes(nDataNodes)
.racks(racks)
.simulatedCapacities(capacities)
.format(false)
.build();
LOG.info("UNEVEN 11");
try {
cluster.waitActive();
LOG.info("UNEVEN 12");
final Suite s = new Suite(cluster, nNameNodes, nDataNodes, conf);
for(int n = 0; n < nNameNodes; n++) {
// redistribute blocks
final Block[][] blocksDN = TestBalancer.distributeBlocks(
blocks[n], s.replication, distributionPerNN);
for(int d = 0; d < blocksDN.length; d++)
cluster.injectBlocks(n, d, Arrays.asList(blocksDN[d]));
LOG.info("UNEVEN 13: n=" + n);
}
final long totalCapacity = TestBalancer.sum(capacities);
final long totalUsed = nNameNodes*usedSpacePerNN;
LOG.info("UNEVEN 14");
runBalancer(s, totalUsed, totalCapacity);
LOG.info("UNEVEN 15");
} finally {
cluster.shutdown();
}
LOG.info("UNEVEN 16");
}
}
/**
* This test start a cluster, fill the DataNodes to be 30% full;
* It then adds an empty node and start balancing.
*
* @param nNameNodes Number of NameNodes
* @param capacities Capacities of the datanodes
* @param racks Rack names
* @param newCapacity the capacity of the new DataNode
* @param newRack the rack for the new DataNode
* @param conf Configuration
*/
private void runTest(final int nNameNodes, long[] capacities, String[] racks,
long newCapacity, String newRack, Configuration conf) throws Exception {
final int nDataNodes = capacities.length;
LOG.info("nNameNodes=" + nNameNodes + ", nDataNodes=" + nDataNodes);
Assert.assertEquals(nDataNodes, racks.length);
LOG.info("RUN_TEST -1");
final MiniDFSCluster cluster = new MiniDFSCluster
.Builder(new Configuration(conf))
.nnTopology(MiniDFSNNTopology.simpleFederatedTopology(nNameNodes))
.numDataNodes(nDataNodes)
.racks(racks)
.simulatedCapacities(capacities)
.build();
LOG.info("RUN_TEST 0");
DFSTestUtil.setFederatedConfiguration(cluster, conf);
try {
cluster.waitActive();
LOG.info("RUN_TEST 1");
final Suite s = new Suite(cluster, nNameNodes, nDataNodes, conf);
long totalCapacity = TestBalancer.sum(capacities);
LOG.info("RUN_TEST 2");
// fill up the cluster to be 30% full
final long totalUsed = totalCapacity*3/10;
final long size = (totalUsed/nNameNodes)/s.replication;
for(int n = 0; n < nNameNodes; n++) {
createFile(s, n, size);
}
LOG.info("RUN_TEST 3");
// start up an empty node with the same capacity and on the same rack
cluster.startDataNodes(conf, 1, true, null,
new String[]{newRack}, new long[]{newCapacity});
totalCapacity += newCapacity;
LOG.info("RUN_TEST 4");
// run RUN_TEST and validate results
runBalancer(s, totalUsed, totalCapacity);
LOG.info("RUN_TEST 5");
} finally {
cluster.shutdown();
}
LOG.info("RUN_TEST 6");
}
/** Test a cluster with even distribution,
* then a new empty node is added to the cluster
*/
@Test
public void testBalancer() throws Exception {
final Configuration conf = createConf();
runTest(2, new long[]{CAPACITY}, new String[]{RACK0},
CAPACITY/2, RACK0, conf);
}
/** Test unevenly distributed cluster */
@Test
public void testUnevenDistribution() throws Exception {
final Configuration conf = createConf();
unevenDistribution(2,
new long[] {30*CAPACITY/100, 5*CAPACITY/100},
new long[]{CAPACITY, CAPACITY},
new String[] {RACK0, RACK1},
conf);
}
}
| apache-2.0 |
aehlig/bazel | src/main/java/com/google/devtools/build/lib/skyframe/ConfiguredTargetAndData.java | 5672 | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A container class for a {@link ConfiguredTarget} and associated data, {@link Target} and {@link
* BuildConfiguration}. In the future, {@link ConfiguredTarget} objects will no longer contain their
* associated {@link BuildConfiguration}. Consumers that need the {@link Target} or {@link
* BuildConfiguration} must therefore have access to one of these objects.
*
* <p>These objects are intended to be short-lived, never stored in Skyframe, since they pair three
* heavyweight objects, a {@link ConfiguredTarget}, a {@link Target} (which holds a {@link
* Package}), and a {@link BuildConfiguration}.
*/
public class ConfiguredTargetAndData {
private final ConfiguredTarget configuredTarget;
private final Target target;
private final BuildConfiguration configuration;
@VisibleForTesting
public ConfiguredTargetAndData(
ConfiguredTarget configuredTarget, Target target, BuildConfiguration configuration) {
this.configuredTarget = configuredTarget;
this.target = target;
this.configuration = configuration;
Preconditions.checkState(
configuredTarget.getLabel().equals(target.getLabel()),
"Unable to construct ConfiguredTargetAndData:"
+ " ConfiguredTarget's label %s is not equal to Target's label %s",
configuredTarget.getLabel(),
target.getLabel());
BuildConfigurationValue.Key innerConfigurationKey = configuredTarget.getConfigurationKey();
if (configuration == null) {
Preconditions.checkState(
innerConfigurationKey == null,
"Non-null configuration key for %s but configuration is null (%s)",
configuredTarget,
target);
} else {
BuildConfigurationValue.Key configurationKey = BuildConfigurationValue.key(configuration);
Preconditions.checkState(
innerConfigurationKey.equals(configurationKey),
"Configurations don't match: %s %s %s (%s %s)",
configurationKey,
innerConfigurationKey,
configuration,
configuredTarget,
target);
}
}
@Nullable
static ConfiguredTargetAndData fromConfiguredTargetInSkyframe(
ConfiguredTarget ct, SkyFunction.Environment env) throws InterruptedException {
BuildConfiguration configuration = null;
ImmutableSet<SkyKey> packageAndMaybeConfiguration;
PackageValue.Key packageKey = PackageValue.key(ct.getLabel().getPackageIdentifier());
BuildConfigurationValue.Key configurationKeyMaybe = ct.getConfigurationKey();
if (configurationKeyMaybe == null) {
packageAndMaybeConfiguration = ImmutableSet.of(packageKey);
} else {
packageAndMaybeConfiguration = ImmutableSet.of(packageKey, configurationKeyMaybe);
}
Map<SkyKey, SkyValue> packageAndMaybeConfigurationValues =
env.getValues(packageAndMaybeConfiguration);
// Don't test env.valuesMissing(), because values may already be missing from the caller.
PackageValue packageValue = (PackageValue) packageAndMaybeConfigurationValues.get(packageKey);
if (packageValue == null) {
return null;
}
if (configurationKeyMaybe != null) {
BuildConfigurationValue buildConfigurationValue =
(BuildConfigurationValue) packageAndMaybeConfigurationValues.get(configurationKeyMaybe);
if (buildConfigurationValue == null) {
return null;
}
configuration = buildConfigurationValue.getConfiguration();
}
try {
return new ConfiguredTargetAndData(
ct, packageValue.getPackage().getTarget(ct.getLabel().getName()), configuration);
} catch (NoSuchTargetException e) {
throw new IllegalStateException("Failed to retrieve target for " + ct, e);
}
}
/**
* For use with {@code MergedConfiguredTarget} and similar, where we create a virtual {@link
* ConfiguredTarget} corresponding to the same {@link Target}.
*/
public ConfiguredTargetAndData fromConfiguredTarget(ConfiguredTarget maybeNew) {
if (configuredTarget.equals(maybeNew)) {
return this;
}
return new ConfiguredTargetAndData(maybeNew, this.target, configuration);
}
public Target getTarget() {
return target;
}
public BuildConfiguration getConfiguration() {
return configuration;
}
public ConfiguredTarget getConfiguredTarget() {
return configuredTarget;
}
}
| apache-2.0 |
apache/kylin | cache/src/main/java/org/apache/kylin/cache/memcached/MemcachedConnectionFactoryBuilder.java | 6035 | /*
* 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.kylin.cache.memcached;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import net.spy.memcached.ArrayModNodeLocator;
import net.spy.memcached.ConnectionFactory;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionObserver;
import net.spy.memcached.DefaultConnectionFactory;
import net.spy.memcached.FailureMode;
import net.spy.memcached.HashAlgorithm;
import net.spy.memcached.MemcachedNode;
import net.spy.memcached.NodeLocator;
import net.spy.memcached.OperationFactory;
import net.spy.memcached.RefinedKetamaNodeLocator;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.metrics.MetricCollector;
import net.spy.memcached.metrics.MetricType;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.transcoders.Transcoder;
public class MemcachedConnectionFactoryBuilder extends ConnectionFactoryBuilder {
/**
* Get the ConnectionFactory set up with the provided parameters.
*/
public ConnectionFactory build() {
return new DefaultConnectionFactory() {
@Override
public BlockingQueue<Operation> createOperationQueue() {
return opQueueFactory == null ? super.createOperationQueue() : opQueueFactory.create();
}
@Override
public BlockingQueue<Operation> createReadOperationQueue() {
return readQueueFactory == null ? super.createReadOperationQueue() : readQueueFactory.create();
}
@Override
public BlockingQueue<Operation> createWriteOperationQueue() {
return writeQueueFactory == null ? super.createReadOperationQueue() : writeQueueFactory.create();
}
@Override
public NodeLocator createLocator(List<MemcachedNode> nodes) {
switch (locator) {
case ARRAY_MOD:
return new ArrayModNodeLocator(nodes, getHashAlg());
case CONSISTENT:
return new RefinedKetamaNodeLocator(nodes, getHashAlg());
default:
throw new IllegalStateException("Unhandled locator type: " + locator);
}
}
@Override
public Transcoder<Object> getDefaultTranscoder() {
return transcoder == null ? super.getDefaultTranscoder() : transcoder;
}
@Override
public FailureMode getFailureMode() {
return failureMode == null ? super.getFailureMode() : failureMode;
}
@Override
public HashAlgorithm getHashAlg() {
return hashAlg == null ? super.getHashAlg() : hashAlg;
}
public Collection<ConnectionObserver> getInitialObservers() {
return initialObservers;
}
@Override
public OperationFactory getOperationFactory() {
return opFact == null ? super.getOperationFactory() : opFact;
}
@Override
public long getOperationTimeout() {
return opTimeout == -1 ? super.getOperationTimeout() : opTimeout;
}
@Override
public int getReadBufSize() {
return readBufSize == -1 ? super.getReadBufSize() : readBufSize;
}
@Override
public boolean isDaemon() {
return isDaemon;
}
@Override
public boolean shouldOptimize() {
return shouldOptimize;
}
@Override
public boolean useNagleAlgorithm() {
return useNagle;
}
@Override
public long getMaxReconnectDelay() {
return maxReconnectDelay;
}
@Override
public AuthDescriptor getAuthDescriptor() {
return authDescriptor;
}
@Override
public long getOpQueueMaxBlockTime() {
return opQueueMaxBlockTime > -1 ? opQueueMaxBlockTime : super.getOpQueueMaxBlockTime();
}
@Override
public int getTimeoutExceptionThreshold() {
return timeoutExceptionThreshold;
}
@Override
public MetricType enableMetrics() {
return metricType == null ? super.enableMetrics() : metricType;
}
@Override
public MetricCollector getMetricCollector() {
return collector == null ? super.getMetricCollector() : collector;
}
@Override
public ExecutorService getListenerExecutorService() {
return executorService == null ? super.getListenerExecutorService() : executorService;
}
@Override
public boolean isDefaultExecutorService() {
return executorService == null;
}
@Override
public long getAuthWaitTime() {
return authWaitTime;
}
};
}
} | apache-2.0 |
howepeng/isis | core/applib/src/main/java/org/apache/isis/applib/marker/ImmutableOncePersisted.java | 1130 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.applib.marker;
import org.apache.isis.applib.annotation.Immutable;
/**
* Marker interface to show that an object cannot be changed once persisted.
*
* Use {@link Immutable} annotation in preference to this marker interface.
*/
public interface ImmutableOncePersisted {
}
| apache-2.0 |
robertandrewbain/querydsl | querydsl-jpa/src/main/java/com/querydsl/jpa/hibernate/AbstractHibernateQuery.java | 11376 | /*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.querydsl.jpa.hibernate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.hibernate.*;
import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import com.mysema.commons.lang.CloseableIterator;
import com.querydsl.core.*;
import com.querydsl.core.NonUniqueResultException;
import com.querydsl.core.QueryException;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.FactoryExpression;
import com.querydsl.core.types.Path;
import com.querydsl.jpa.*;
/**
* Abstract base class for Hibernate API based implementations of the JPQL interface
*
* @param <T> result type
* @param <Q> concrete subtype
*
* @author tiwe
*/
public abstract class AbstractHibernateQuery<T, Q extends AbstractHibernateQuery<T, Q>> extends JPAQueryBase<T, Q> {
private static final Logger logger = LoggerFactory.getLogger(HibernateQuery.class);
@Nullable
protected Boolean cacheable, readOnly;
@Nullable
protected String cacheRegion, comment;
protected int fetchSize = 0;
protected final Map<Path<?>,LockMode> lockModes = new HashMap<Path<?>,LockMode>();
@Nullable
protected FlushMode flushMode;
private final SessionHolder session;
protected int timeout = 0;
public AbstractHibernateQuery(Session session) {
this(new DefaultSessionHolder(session), HQLTemplates.DEFAULT, new DefaultQueryMetadata());
}
public AbstractHibernateQuery(SessionHolder session, JPQLTemplates patterns, QueryMetadata metadata) {
super(metadata, patterns);
this.session = session;
}
@Override
public long fetchCount() {
QueryModifiers modifiers = getMetadata().getModifiers();
try {
Query query = createQuery(modifiers, true);
Long rv = (Long) query.uniqueResult();
if (rv != null) {
return rv;
} else {
throw new QueryException("Query returned null");
}
} finally {
reset();
}
}
/**
* Expose the original Hibernate query for the given projection
*
* @return query
*/
public Query createQuery() {
return createQuery(getMetadata().getModifiers(), false);
}
private Query createQuery(@Nullable QueryModifiers modifiers, boolean forCount) {
JPQLSerializer serializer = serialize(forCount);
String queryString = serializer.toString();
logQuery(queryString, serializer.getConstantToLabel());
Query query = session.createQuery(queryString);
HibernateUtil.setConstants(query, serializer.getConstantToLabel(), getMetadata().getParams());
if (fetchSize > 0) {
query.setFetchSize(fetchSize);
}
if (timeout > 0) {
query.setTimeout(timeout);
}
if (cacheable != null) {
query.setCacheable(cacheable);
}
if (cacheRegion != null) {
query.setCacheRegion(cacheRegion);
}
if (comment != null) {
query.setComment(comment);
}
if (readOnly != null) {
query.setReadOnly(readOnly);
}
for (Map.Entry<Path<?>, LockMode> entry : lockModes.entrySet()) {
query.setLockMode(entry.getKey().toString(), entry.getValue());
}
if (flushMode != null) {
query.setFlushMode(flushMode);
}
if (modifiers != null && modifiers.isRestricting()) {
Integer limit = modifiers.getLimitAsInteger();
Integer offset = modifiers.getOffsetAsInteger();
if (limit != null) {
query.setMaxResults(limit);
}
if (offset != null) {
query.setFirstResult(offset);
}
}
// set transformer, if necessary
Expression<?> projection = getMetadata().getProjection();
if (!forCount && projection instanceof FactoryExpression) {
query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) projection));
}
return query;
}
/**
* Return the query results as an <tt>Iterator</tt>. If the query
* contains multiple results pre row, the results are returned in
* an instance of <tt>Object[]</tt>.<br>
* <br>
* Entities returned as results are initialized on demand. The first
* SQL query returns identifiers only.<br>
*/
@Override
public CloseableIterator<T> iterate() {
try {
Query query = createQuery();
ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
return new ScrollableResultsIterator<T>(results);
} finally {
reset();
}
}
@Override
@SuppressWarnings("unchecked")
public List<T> fetch() {
try {
return createQuery().list();
} finally {
reset();
}
}
@Override
public QueryResults<T> fetchResults() {
try {
Query countQuery = createQuery(null, true);
long total = (Long) countQuery.uniqueResult();
if (total > 0) {
QueryModifiers modifiers = getMetadata().getModifiers();
Query query = createQuery(modifiers, false);
@SuppressWarnings("unchecked")
List<T> list = query.list();
return new QueryResults<T>(list, modifiers, total);
} else {
return QueryResults.emptyResults();
}
} finally {
reset();
}
}
protected void logQuery(String queryString, Map<Object, String> parameters) {
String normalizedQuery = queryString.replace('\n', ' ');
MDC.put(MDC_QUERY, normalizedQuery);
MDC.put(MDC_PARAMETERS, String.valueOf(parameters));
if (logger.isDebugEnabled()) {
logger.debug(normalizedQuery);
}
}
protected void cleanupMDC() {
MDC.remove(MDC_QUERY);
MDC.remove(MDC_PARAMETERS);
}
@Override
protected void reset() {
cleanupMDC();
}
/**
* Return the query results as <tt>ScrollableResults</tt>. The
* scrollability of the returned results depends upon JDBC driver
* support for scrollable <tt>ResultSet</tt>s.<br>
*
* @param mode scroll mode
* @return scrollable results
*/
public ScrollableResults scroll(ScrollMode mode) {
try {
return createQuery().scroll(mode);
} finally {
reset();
}
}
/**
* Enable caching of this query result set.
* @param cacheable Should the query results be cacheable?
*/
@SuppressWarnings("unchecked")
public Q setCacheable(boolean cacheable) {
this.cacheable = cacheable;
return (Q) this;
}
/**
* Set the name of the cache region.
* @param cacheRegion the name of a query cache region, or <tt>null</tt>
* for the default query cache
*/
@SuppressWarnings("unchecked")
public Q setCacheRegion(String cacheRegion) {
this.cacheRegion = cacheRegion;
return (Q) this;
}
/**
* Add a comment to the generated SQL.
* @param comment comment
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setComment(String comment) {
this.comment = comment;
return (Q) this;
}
/**
* Set a fetchJoin size for the underlying JDBC query.
* @param fetchSize the fetchJoin size
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
return (Q) this;
}
/**
* Set the lock mode for the given path.
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setLockMode(Path<?> path, LockMode lockMode) {
lockModes.put(path, lockMode);
return (Q) this;
}
/**
* Override the current session flush mode, just for this query.
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setFlushMode(FlushMode flushMode) {
this.flushMode = flushMode;
return (Q) this;
}
/**
* Entities retrieved by this query will be loaded in
* a read-only mode where Hibernate will never dirty-check
* them or make changes persistent.
*
* @return the current object
*
*/
@SuppressWarnings("unchecked")
public Q setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
return (Q) this;
}
/**
* Set a timeout for the underlying JDBC query.
* @param timeout the timeout in seconds
* @return the current object
*/
@SuppressWarnings("unchecked")
public Q setTimeout(int timeout) {
this.timeout = timeout;
return (Q) this;
}
@SuppressWarnings("unchecked")
@Override
public T fetchOne() {
try {
QueryModifiers modifiers = getMetadata().getModifiers();
Query query = createQuery(modifiers, false);
try {
return (T) query.uniqueResult();
} catch (org.hibernate.NonUniqueResultException e) {
throw new NonUniqueResultException();
}
} finally {
reset();
}
}
@Override
protected JPQLSerializer createSerializer() {
return new JPQLSerializer(getTemplates());
}
protected void clone(Q query) {
cacheable = query.cacheable;
cacheRegion = query.cacheRegion;
fetchSize = query.fetchSize;
flushMode = query.flushMode;
lockModes.putAll(query.lockModes);
readOnly = query.readOnly;
timeout = query.timeout;
}
protected abstract Q clone(SessionHolder sessionHolder);
/**
* Clone the state of this query to a new instance with the given Session
*
* @param session session
* @return cloned query
*/
public Q clone(Session session) {
return this.clone(new DefaultSessionHolder(session));
}
/**
* Clone the state of this query to a new instance with the given StatelessSession
*
* @param session session
* @return cloned query
*/
public Q clone(StatelessSession session) {
return this.clone(new StatelessSessionHolder(session));
}
/**
* Clone the state of this query to a new instance
*
* @return closed query
*/
@Override
public Q clone() {
return this.clone(this.session);
}
}
| apache-2.0 |
liuyuanyuan/dbeaver | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/struct/AbstractProcedure.java | 3035 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.model.impl.struct;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedure;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureType;
/**
* AbstractProcedure
*/
public abstract class AbstractProcedure<
DATASOURCE extends DBPDataSource,
CONTAINER extends DBSObjectContainer>
implements DBSProcedure, DBPSaveableObject, DBPImageProvider
{
protected CONTAINER container;
protected String name;
protected String description;
protected boolean persisted;
protected AbstractProcedure(CONTAINER container, boolean persisted)
{
this.container = container;
this.persisted = persisted;
}
protected AbstractProcedure(CONTAINER container, boolean persisted, String name, String description)
{
this(container, persisted);
this.name = name;
this.description = description;
}
@Override
public CONTAINER getContainer()
{
return container;
}
@NotNull
@Override
@Property(viewable = true, order = 1)
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@Nullable
@Override
@Property(viewable = true, multiline = true, order = 100)
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
@NotNull
@Override
public DATASOURCE getDataSource()
{
return (DATASOURCE) container.getDataSource();
}
@Override
public boolean isPersisted()
{
return persisted;
}
@Override
public void setPersisted(boolean persisted)
{
this.persisted = persisted;
}
@Override
public DBSObject getParentObject()
{
return container;
}
@Nullable
@Override
public DBPImage getObjectImage() {
if (getProcedureType() == DBSProcedureType.FUNCTION) {
return DBIcon.TREE_FUNCTION;
} else {
return DBIcon.TREE_PROCEDURE;
}
}
}
| apache-2.0 |
chtyim/cdap | cdap-app-templates/cdap-etl/cdap-etl-batch/src/main/java/co/cask/cdap/etl/batch/spark/ETLSparkProgram.java | 8655 | /*
* Copyright © 2015 Cask Data, 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 co.cask.cdap.etl.batch.spark;
import co.cask.cdap.api.dataset.lib.KeyValue;
import co.cask.cdap.api.metrics.Metrics;
import co.cask.cdap.api.plugin.PluginContext;
import co.cask.cdap.api.spark.JavaSparkProgram;
import co.cask.cdap.api.spark.SparkContext;
import co.cask.cdap.etl.api.Transform;
import co.cask.cdap.etl.api.batch.BatchRuntimeContext;
import co.cask.cdap.etl.api.batch.BatchSink;
import co.cask.cdap.etl.api.batch.BatchSource;
import co.cask.cdap.etl.common.Constants;
import co.cask.cdap.etl.common.DefaultStageMetrics;
import co.cask.cdap.etl.common.Pipeline;
import co.cask.cdap.etl.common.SinkInfo;
import co.cask.cdap.etl.common.TransformDetail;
import co.cask.cdap.etl.common.TransformExecutor;
import co.cask.cdap.etl.common.TransformInfo;
import co.cask.cdap.etl.common.TransformResponse;
import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Tuple2;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Spark program to run an ETL pipeline.
*/
public class ETLSparkProgram implements JavaSparkProgram {
private static final Logger LOG = LoggerFactory.getLogger(ETLSparkProgram.class);
private static final Gson GSON = new Gson();
@Override
public void run(SparkContext context) throws Exception {
SparkBatchSourceFactory sourceFactory;
SparkBatchSinkFactory sinkFactory;
try (InputStream is = new FileInputStream(context.getTaskLocalizationContext().getLocalFile("ETLSpark.config"))) {
sourceFactory = SparkBatchSourceFactory.deserialize(is);
sinkFactory = SparkBatchSinkFactory.deserialize(is);
}
JavaPairRDD<Object, Object> rdd = sourceFactory.createRDD(context, Object.class, Object.class);
JavaPairRDD<String, Object> resultRDD = rdd.flatMapToPair(new MapFunction(context)).cache();
Pipeline pipeline = GSON.fromJson(context.getSpecification().getProperty(Constants.PIPELINEID), Pipeline.class);
for (SinkInfo sinkInfo : pipeline.getSinks()) {
final String sinkId = sinkInfo.getSinkId();
JavaPairRDD<Object, Object> sinkRDD = resultRDD
.filter(new Function<Tuple2<String, Object>, Boolean>() {
@Override
public Boolean call(Tuple2<String, Object> v1) throws Exception {
return v1._1().equals(sinkId);
}
})
.flatMapToPair(new PairFlatMapFunction<Tuple2<String, Object>, Object, Object>() {
@Override
public Iterable<Tuple2<Object, Object>> call(Tuple2<String, Object> input) throws Exception {
List<Tuple2<Object, Object>> result = new ArrayList<>();
KeyValue<Object, Object> keyValue = (KeyValue<Object, Object>) input._2();
result.add(new Tuple2<>(keyValue.getKey(), keyValue.getValue()));
return result;
}
});
sinkFactory.writeFromRDD(sinkRDD, context, sinkId, Object.class, Object.class);
}
}
/**
* Performs all transforms, and returns tuples where the first item is the sink to write to, and the second item
* is the KeyValue to write.
*/
public static final class MapFunction
implements PairFlatMapFunction<Tuple2<Object, Object>, String, Object> {
private final PluginContext pluginContext;
private final Metrics metrics;
private final long logicalStartTime;
private final String pipelineStr;
private final Map<String, String> runtimeArgs;
private transient TransformExecutor<KeyValue<Object, Object>> transformExecutor;
public MapFunction(SparkContext sparkContext) {
this.pluginContext = sparkContext.getPluginContext();
this.metrics = sparkContext.getMetrics();
this.logicalStartTime = sparkContext.getLogicalStartTime();
this.pipelineStr = sparkContext.getSpecification().getProperty(Constants.PIPELINEID);
this.runtimeArgs = sparkContext.getRuntimeArguments();
}
@Override
public Iterable<Tuple2<String, Object>> call(Tuple2<Object, Object> tuple) throws Exception {
if (transformExecutor == null) {
// TODO: There is no way to call destroy() method on Transform
// In fact, we can structure transform in a way that it doesn't need destroy
// All current usage of destroy() in transform is actually for Source/Sink, which is actually
// better do it in prepareRun and onRunFinish, which happen outside of the Job execution (true for both
// Spark and MapReduce).
transformExecutor = initialize();
}
TransformResponse response = transformExecutor.runOneIteration(new KeyValue<>(tuple._1(), tuple._2()));
List<Tuple2<String, Object>> result = new ArrayList<>();
for (Map.Entry<String, Collection<Object>> transformedEntry : response.getSinksResults().entrySet()) {
String sinkName = transformedEntry.getKey();
for (Object outputRecord : transformedEntry.getValue()) {
result.add(new Tuple2<>(sinkName, outputRecord));
}
}
return result;
}
private TransformExecutor<KeyValue<Object, Object>> initialize() throws Exception {
Pipeline pipeline = GSON.fromJson(pipelineStr, Pipeline.class);
Map<String, List<String>> connections = pipeline.getConnections();
// get source, transform, sink ids from program properties
String sourcePluginId = pipeline.getSource();
BatchSource source = pluginContext.newPluginInstance(sourcePluginId);
BatchRuntimeContext runtimeContext = new SparkBatchRuntimeContext(pluginContext, metrics, logicalStartTime,
runtimeArgs, sourcePluginId);
source.initialize(runtimeContext);
Map<String, TransformDetail> transformations = new HashMap<>();
transformations.put(sourcePluginId, new TransformDetail(
source, new DefaultStageMetrics(metrics, sourcePluginId), connections.get(sourcePluginId)));
addTransforms(transformations, pipeline.getTransforms(), connections);
List<SinkInfo> sinkInfos = pipeline.getSinks();
for (SinkInfo sinkInfo : sinkInfos) {
String sinkId = sinkInfo.getSinkId();
BatchSink<Object, Object, Object> batchSink = pluginContext.newPluginInstance(sinkId);
BatchRuntimeContext sinkContext = new SparkBatchRuntimeContext(pluginContext, metrics, logicalStartTime,
runtimeArgs, sinkId);
batchSink.initialize(sinkContext);
transformations.put(sinkInfo.getSinkId(), new TransformDetail(
batchSink, new DefaultStageMetrics(metrics, sinkInfo.getSinkId()), new ArrayList<String>()));
}
return new TransformExecutor<>(transformations, ImmutableList.of(sourcePluginId));
}
private void addTransforms(Map<String, TransformDetail> transformations,
List<TransformInfo> transformInfos,
Map<String, List<String>> connections) throws Exception {
for (TransformInfo transformInfo : transformInfos) {
String transformId = transformInfo.getTransformId();
Transform transform = pluginContext.newPluginInstance(transformId);
BatchRuntimeContext transformContext = new SparkBatchRuntimeContext(pluginContext, metrics,
logicalStartTime, runtimeArgs, transformId);
LOG.debug("Transform Class : {}", transform.getClass().getName());
transform.initialize(transformContext);
transformations.put(transformId, new TransformDetail(
transform, new DefaultStageMetrics(metrics, transformId), connections.get(transformId)));
}
}
}
}
| apache-2.0 |
bsa01/qbit | qbit/boon/src/test/java/io/advantageous/qbit/service/rest/endpoint/tests/services/HRService.java | 3594 | package io.advantageous.qbit.service.rest.endpoint.tests.services;
import io.advantageous.qbit.annotation.PathVariable;
import io.advantageous.qbit.annotation.RequestMapping;
import io.advantageous.qbit.annotation.RequestMethod;
import io.advantageous.qbit.service.rest.endpoint.tests.model.Department;
import io.advantageous.qbit.service.rest.endpoint.tests.model.Employee;
import io.advantageous.qbit.service.rest.endpoint.tests.model.PhoneNumber;
import java.util.*;
import java.util.function.Predicate;
@RequestMapping("/hr")
public class HRService {
final Map<Integer, Department> departmentMap = new HashMap<>();
@RequestMapping("/department/")
public List<Department> getDepartments() {
return new ArrayList<>(departmentMap.values());
}
@RequestMapping(value = "/department/{departmentId}/", method = RequestMethod.POST)
public boolean addDepartments(@PathVariable("departmentId") Integer departmentId,
final Department department) {
departmentMap.put(departmentId, department);
return true;
}
@RequestMapping(value = "/department/{departmentId}/employee/", method = RequestMethod.POST)
public boolean addEmployee(@PathVariable("departmentId") Integer departmentId,
final Employee employee) {
final Department department = departmentMap.get(departmentId);
if (department == null) {
throw new IllegalArgumentException("Department " + departmentId + " does not exist");
}
department.addEmployee(employee);
return true;
}
@RequestMapping(value = "/department/{departmentId}/employee/{employeeId}", method = RequestMethod.GET)
public Employee getEmployee(@PathVariable("departmentId") Integer departmentId,
@PathVariable("employeeId") Long employeeId) {
final Department department = departmentMap.get(departmentId);
if (department == null) {
throw new IllegalArgumentException("Department " + departmentId + " does not exist");
}
Optional<Employee> employee = department.getEmployeeList().stream().filter(new Predicate<Employee>() {
@Override
public boolean test(Employee employee) {
return employee.getId() == employeeId;
}
}).findFirst();
if (employee.isPresent()){
return employee.get();
} else {
throw new IllegalArgumentException("Employee with id " + employeeId + " Not found ");
}
}
public Map<Integer, Department> getDepartmentMap() {
return departmentMap;
}
@RequestMapping(value = "/department/{departmentId}/employee/{employeeId}/phoneNumber/",
method = RequestMethod.POST)
public boolean addPhoneNumber(@PathVariable("departmentId") Integer departmentId,
@PathVariable("employeeId") Long employeeId,
PhoneNumber phoneNumber) {
Employee employee = getEmployee(departmentId, employeeId);
employee.addPhoneNumber(phoneNumber);
return true;
}
@RequestMapping(value = "/department/{departmentId}/employee/{employeeId}/phoneNumber/")
public List<PhoneNumber> getPhoneNumbers(@PathVariable("departmentId") Integer departmentId,
@PathVariable("employeeId") Long employeeId) {
Employee employee = getEmployee(departmentId, employeeId);
return employee.getPhoneNumbers();
}
}
| apache-2.0 |
kierarad/gocd | server/src/main/java/com/thoughtworks/go/server/service/dd/FanInEventListener.java | 810 | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.service.dd;
import java.util.List;
public interface FanInEventListener {
void iterationComplete(int iterationCount, List<DependencyFanInNode> dependencyFanInNodes);
}
| apache-2.0 |
WillJiang/WillJiang | src/xwork-core/src/main/java/com/opensymphony/xwork2/validator/annotations/RequiredFieldValidator.java | 4164 | /*
* Copyright 2002-2006,2009 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 com.opensymphony.xwork2.validator.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <!-- START SNIPPET: description -->
* This validator checks that a field is non-null.
* <!-- END SNIPPET: description -->
*
* <p/> <u>Annotation usage:</u>
*
* <!-- START SNIPPET: usage -->
* <p/>The annotation must be applied at method level.
* <!-- END SNIPPET: usage -->
*
* <p/> <u>Annotation parameters:</u>
*
* <!-- START SNIPPET: parameters -->
* <table class='confluenceTable'>
* <tr>
* <th class='confluenceTh'> Parameter </th>
* <th class='confluenceTh'> Required </th>
* <th class='confluenceTh'> Default </th>
* <th class='confluenceTh'> Notes </th>
* </tr>
* <tr>
* <td class='confluenceTd'>message</td>
* <td class='confluenceTd'>yes</td>
* <td class='confluenceTd'> </td>
* <td class='confluenceTd'>field error message</td>
* </tr>
* <tr>
* <td class='confluenceTd'>key</td>
* <td class='confluenceTd'>no</td>
* <td class='confluenceTd'> </td>
* <td class='confluenceTd'>i18n key from language specific properties file.</td>
* </tr>
* <tr>
* <td class='confluenceTd'>messageParams</td>
* <td class='confluenceTd'>no</td>
* <td class='confluenceTd'> </td>
* <td class='confluenceTd'>Additional params to be used to customize message - will be evaluated against the Value Stack</td>
* </tr>
* <tr>
* <td class='confluenceTd'>fieldName</td>
* <td class='confluenceTd'>no</td>
* <td class='confluenceTd'> </td>
* <td class='confluenceTd'> </td>
* </tr>
* <tr>
* <td class='confluenceTd'>shortCircuit</td>
* <td class='confluenceTd'>no</td>
* <td class='confluenceTd'>false</td>
* <td class='confluenceTd'>If this validator should be used as shortCircuit.</td>
* </tr>
* <tr>
* <td class='confluenceTd'>type</td>
* <td class='confluenceTd'>yes</td>
* <td class='confluenceTd'>ValidatorType.FIELD</td>
* <td class='confluenceTd'>Enum value from ValidatorType. Either FIELD or SIMPLE can be used here.</td>
* </tr>
* </table>
* <!-- END SNIPPET: parameters -->
*
* <p/> <u>Example code:</u>
*
* <pre>
* <!-- START SNIPPET: example -->
* @RequiredFieldValidator(message = "Default message", key = "i18n.key", shortCircuit = true)
* <!-- END SNIPPET: example -->
* </pre>
*
*
* @author Rainer Hermanns
* @version $Id: RequiredFieldValidator.java 1457722 2013-03-18 12:00:22Z lukaszlenart $
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredFieldValidator {
/**
* The default error message for this validator.
* NOTE: It is required to set a message, if you are not using the message key for 18n lookup!
*/
String message() default "";
/**
* The message key to lookup for i18n.
*/
String key() default "";
/**
* Additional params to be used to customize message - will be evaluated against the Value Stack
*/
String[] messageParams() default {};
/**
* The optional fieldName for SIMPLE validator types.
*/
String fieldName() default "";
/**
* If this is activated, the validator will be used as short-circuit.
*
* Adds the short-circuit="true" attribute value if <tt>true</tt>.
*
*/
boolean shortCircuit() default false;
/**
* The validation type for this field/method.
*/
ValidatorType type() default ValidatorType.FIELD;
}
| apache-2.0 |
joshualitt/DataflowJavaSDK | contrib/firebaseio/src/main/java/com/google/cloud/dataflow/contrib/firebase/events/ChildAdded.java | 1492 | /**
* Copyright (c) 2015 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.cloud.dataflow.contrib.firebase.events;
import com.google.cloud.dataflow.contrib.firebase.io.FirebaseSource;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
/**
* Created by {@link ChildEventListener#onChildRemoved } triggered in {@link FirebaseSource}.
* @param <T> type that {@link DataSnapshot} is parsed as.
*/
public class ChildAdded<T> extends FirebaseChildEvent<T> {
@JsonCreator
public ChildAdded(
@JsonProperty("key") String key,
@JsonProperty("data") T data,
@JsonProperty("previousChildName") String previousChildName) {
super(key, data, previousChildName);
}
public ChildAdded(DataSnapshot snapshot, String previousChildName){
super(snapshot, previousChildName);
}
}
| apache-2.0 |
jinhyukchang/gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/SpecCatalogListener.java | 3173 | /*
* 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.gobblin.runtime.api;
import java.net.URI;
import com.google.common.base.Objects;
import org.apache.gobblin.util.callbacks.Callback;
public interface SpecCatalogListener {
/** Invoked when a new {@link Spec} is added to the catalog and for all pre-existing specs on registration
* of the listener.*/
void onAddSpec(Spec addedSpec);
/**
* Invoked when a {@link Spec} gets removed from the catalog.
*/
public void onDeleteSpec(URI deletedSpecURI, String deletedSpecVersion);
/**
* Invoked when the contents of a {@link Spec} gets updated in the catalog.
*/
public void onUpdateSpec(Spec updatedSpec);
/** A standard implementation of onAddSpec as a functional object */
public static class AddSpecCallback extends Callback<SpecCatalogListener, Void> {
private final Spec _addedSpec;
public AddSpecCallback(Spec addedSpec) {
super(Objects.toStringHelper("onAddSpec").add("addedSpec", addedSpec).toString());
_addedSpec = addedSpec;
}
@Override public Void apply(SpecCatalogListener listener) {
listener.onAddSpec(_addedSpec);
return null;
}
}
/** A standard implementation of onDeleteSpec as a functional object */
public static class DeleteSpecCallback extends Callback<SpecCatalogListener, Void> {
private final URI _deletedSpecURI;
private final String _deletedSpecVersion;
public DeleteSpecCallback(URI deletedSpecURI, String deletedSpecVersion) {
super(Objects.toStringHelper("onDeleteSpec")
.add("deletedSpecURI", deletedSpecURI)
.add("deletedSpecVersion", deletedSpecVersion)
.toString());
_deletedSpecURI = deletedSpecURI;
_deletedSpecVersion = deletedSpecVersion;
}
@Override public Void apply(SpecCatalogListener listener) {
listener.onDeleteSpec(_deletedSpecURI, _deletedSpecVersion);
return null;
}
}
public static class UpdateSpecCallback extends Callback<SpecCatalogListener, Void> {
private final Spec _updatedSpec;
public UpdateSpecCallback(Spec updatedSpec) {
super(Objects.toStringHelper("onUpdateSpec")
.add("updatedSpec", updatedSpec).toString());
_updatedSpec = updatedSpec;
}
@Override
public Void apply(SpecCatalogListener listener) {
listener.onUpdateSpec(_updatedSpec);
return null;
}
}
}
| apache-2.0 |
datametica/calcite | file/src/test/java/org/apache/calcite/adapter/file/FileAdapterTest.java | 37422 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.adapter.file;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.sql2rel.SqlToRelConverter;
import org.apache.calcite.util.TestUtil;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static org.apache.calcite.adapter.file.FileAdapterTests.sql;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.isA;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* System test of the Calcite file adapter, which can read and parse
* HTML tables over HTTP, and also read CSV and JSON files from the filesystem.
*/
@ExtendWith(RequiresNetworkExtension.class)
class FileAdapterTest {
static Stream<String> explainFormats() {
return Stream.of("text", "dot");
}
/** Reads from a local file and checks the result. */
@Test void testFileSelect() {
final String sql = "select H1 from T1 where H0 = 'R1C0'";
sql("testModel", sql).returns("H1=R1C1").ok();
}
/** Reads from a local file without table headers <TH> and checks the
* result. */
@Test @RequiresNetwork void testNoThSelect() {
final String sql = "select \"col1\" from T1_NO_TH where \"col0\" like 'R0%'";
sql("testModel", sql).returns("col1=R0C1").ok();
}
/** Reads from a local file - finds larger table even without <TH>
* elements. */
@Test void testFindBiggerNoTh() {
final String sql = "select \"col4\" from TABLEX2 where \"col0\" like 'R1%'";
sql("testModel", sql).returns("col4=R1C4").ok();
}
/** Reads from a URL and checks the result. */
@Disabled("[CALCITE-1789] Wikipedia format change breaks file adapter test")
@Test @RequiresNetwork void testUrlSelect() {
final String sql = "select \"State\", \"Statehood\" from \"States_as_of\"\n"
+ "where \"State\" = 'California'";
sql("wiki", sql).returns("State=California; Statehood=1850-09-09").ok();
}
/** Reads the EMPS table. */
@Test void testSalesEmps() {
final String sql = "select * from sales.emps";
sql("sales", sql)
.returns("EMPNO=100; NAME=Fred; DEPTNO=30",
"EMPNO=110; NAME=Eric; DEPTNO=20",
"EMPNO=110; NAME=John; DEPTNO=40",
"EMPNO=120; NAME=Wilma; DEPTNO=20",
"EMPNO=130; NAME=Alice; DEPTNO=40")
.ok();
}
/** Reads the DEPTS table. */
@Test void testSalesDepts() {
final String sql = "select * from sales.depts";
sql("sales", sql)
.returns("DEPTNO=10; NAME=Sales",
"DEPTNO=20; NAME=Marketing",
"DEPTNO=30; NAME=Accounts")
.ok();
}
/** Reads the DEPTS table from the CSV schema. */
@Test void testCsvSalesDepts() {
final String sql = "select * from sales.depts";
sql("sales-csv", sql)
.returns("DEPTNO=10; NAME=Sales",
"DEPTNO=20; NAME=Marketing",
"DEPTNO=30; NAME=Accounts")
.ok();
}
/** Reads the EMPS table from the CSV schema. */
@Test void testCsvSalesEmps() {
final String sql = "select * from sales.emps";
final String[] lines = {
"EMPNO=100; NAME=Fred; DEPTNO=10; GENDER=; CITY=; EMPID=30; AGE=25; SLACKER=true; MANAGER=false; JOINEDAT=1996-08-03",
"EMPNO=110; NAME=Eric; DEPTNO=20; GENDER=M; CITY=San Francisco; EMPID=3; AGE=80; SLACKER=null; MANAGER=false; JOINEDAT=2001-01-01",
"EMPNO=110; NAME=John; DEPTNO=40; GENDER=M; CITY=Vancouver; EMPID=2; AGE=null; SLACKER=false; MANAGER=true; JOINEDAT=2002-05-03",
"EMPNO=120; NAME=Wilma; DEPTNO=20; GENDER=F; CITY=; EMPID=1; AGE=5; SLACKER=null; MANAGER=true; JOINEDAT=2005-09-07",
"EMPNO=130; NAME=Alice; DEPTNO=40; GENDER=F; CITY=Vancouver; EMPID=2; AGE=null; SLACKER=false; MANAGER=true; JOINEDAT=2007-01-01",
};
sql("sales-csv", sql).returns(lines).ok();
}
/** Reads the HEADER_ONLY table from the CSV schema. The CSV file has one
* line - the column headers - but no rows of data. */
@Test void testCsvSalesHeaderOnly() {
final String sql = "select * from sales.header_only";
sql("sales-csv", sql).returns().ok();
}
/** Reads the EMPTY table from the CSV schema. The CSV file has no lines,
* therefore the table has a system-generated column called
* "EmptyFileHasNoColumns". */
@Test void testCsvSalesEmpty() {
final String sql = "select * from sales.\"EMPTY\"";
sql("sales-csv", sql)
.checking(FileAdapterTest::checkEmpty)
.ok();
}
private static void checkEmpty(ResultSet resultSet) {
try {
final ResultSetMetaData metaData = resultSet.getMetaData();
assertThat(metaData.getColumnCount(), is(1));
assertThat(metaData.getColumnName(1), is("EmptyFileHasNoColumns"));
assertThat(metaData.getColumnType(1), is(Types.BOOLEAN));
String actual = FileAdapterTests.toString(resultSet);
assertThat(actual, is(""));
} catch (SQLException e) {
throw TestUtil.rethrow(e);
}
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1754">[CALCITE-1754]
* In Csv adapter, convert DATE and TIME values to int, and TIMESTAMP values
* to long</a>. */
@Test void testCsvGroupByTimestampAdd() {
final String sql = "select count(*) as c,\n"
+ " {fn timestampadd(SQL_TSI_DAY, 1, JOINEDAT) } as t\n"
+ "from EMPS group by {fn timestampadd(SQL_TSI_DAY, 1, JOINEDAT ) } ";
sql("sales-csv", sql)
.returnsUnordered("C=1; T=1996-08-04",
"C=1; T=2002-05-04",
"C=1; T=2005-09-08",
"C=1; T=2007-01-02",
"C=1; T=2001-01-02")
.ok();
final String sql2 = "select count(*) as c,\n"
+ " {fn timestampadd(SQL_TSI_MONTH, 1, JOINEDAT) } as t\n"
+ "from EMPS group by {fn timestampadd(SQL_TSI_MONTH, 1, JOINEDAT ) } ";
sql("sales-csv", sql2)
.returnsUnordered("C=1; T=2002-06-03",
"C=1; T=2005-10-07",
"C=1; T=2007-02-01",
"C=1; T=2001-02-01",
"C=1; T=1996-09-03").ok();
final String sql3 = "select\n"
+ " distinct {fn timestampadd(SQL_TSI_MONTH, 1, JOINEDAT) } as t\n"
+ "from EMPS";
sql("sales-csv", sql3)
.returnsUnordered("T=2002-06-03",
"T=2005-10-07",
"T=2007-02-01",
"T=2001-02-01",
"T=1996-09-03").ok();
}
/** Reads the DEPTS table from the JSON schema. */
@Test void testJsonSalesDepts() {
final String sql = "select * from sales.depts";
sql("sales-json", sql)
.returns("DEPTNO=10; NAME=Sales",
"DEPTNO=20; NAME=Marketing",
"DEPTNO=30; NAME=Accounts")
.ok();
}
/** Reads the EMPS table from the JSON schema. */
@Test void testJsonSalesEmps() {
final String sql = "select * from sales.emps";
final String[] lines = {
"EMPNO=100; NAME=Fred; DEPTNO=10; GENDER=; CITY=; EMPID=30; AGE=25; SLACKER=true; MANAGER=false; JOINEDAT=1996-08-03",
"EMPNO=110; NAME=Eric; DEPTNO=20; GENDER=M; CITY=San Francisco; EMPID=3; AGE=80; SLACKER=null; MANAGER=false; JOINEDAT=2001-01-01",
"EMPNO=110; NAME=John; DEPTNO=40; GENDER=M; CITY=Vancouver; EMPID=2; AGE=null; SLACKER=false; MANAGER=true; JOINEDAT=2002-05-03",
"EMPNO=120; NAME=Wilma; DEPTNO=20; GENDER=F; CITY=; EMPID=1; AGE=5; SLACKER=null; MANAGER=true; JOINEDAT=2005-09-07",
"EMPNO=130; NAME=Alice; DEPTNO=40; GENDER=F; CITY=Vancouver; EMPID=2; AGE=null; SLACKER=false; MANAGER=true; JOINEDAT=2007-01-01",
};
sql("sales-json", sql).returns(lines).ok();
}
/** Reads the EMPTY table from the JSON schema. The JSON file has no lines,
* therefore the table has a system-generated column called
* "EmptyFileHasNoColumns". */
@Test void testJsonSalesEmpty() {
final String sql = "select * from sales.\"EMPTY\"";
sql("sales-json", sql)
.checking(FileAdapterTest::checkEmpty)
.ok();
}
/** Test returns the result of two json file joins. */
@Test void testJsonJoinOnString() {
final String sql = "select emps.EMPNO, emps.NAME, depts.deptno from emps\n"
+ "join depts on emps.deptno = depts.deptno";
final String[] lines = {
"EMPNO=100; NAME=Fred; DEPTNO=10",
"EMPNO=110; NAME=Eric; DEPTNO=20",
"EMPNO=120; NAME=Wilma; DEPTNO=20",
};
sql("sales-json", sql).returns(lines).ok();
}
/** The folder contains both JSON files and CSV files joins. */
@Test void testJsonWithCsvJoin() {
final String sql = "select emps.empno,\n"
+ " NAME,\n"
+ " \"DATE\".JOINEDAT\n"
+ " from \"DATE\"\n"
+ "join emps on emps.empno = \"DATE\".EMPNO\n"
+ "order by empno, name, joinedat limit 3";
final String[] lines = {
"EMPNO=100; NAME=Fred; JOINEDAT=1996-08-03",
"EMPNO=110; NAME=Eric; JOINEDAT=2001-01-01",
"EMPNO=110; NAME=Eric; JOINEDAT=2002-05-03",
};
sql("sales-json", sql)
.returns(lines)
.ok();
}
/** Tests an inline schema with a non-existent directory. */
@Test void testBadDirectory() throws SQLException {
Properties info = new Properties();
info.put("model",
"inline:"
+ "{\n"
+ " version: '1.0',\n"
+ " schemas: [\n"
+ " {\n"
+ " type: 'custom',\n"
+ " name: 'bad',\n"
+ " factory: 'org.apache.calcite.adapter.file.FileSchemaFactory',\n"
+ " operand: {\n"
+ " directory: '/does/not/exist'\n"
+ " }\n"
+ " }\n"
+ " ]\n"
+ "}");
Connection connection =
DriverManager.getConnection("jdbc:calcite:", info);
// must print "directory ... not found" to stdout, but not fail
ResultSet tables =
connection.getMetaData().getTables(null, null, null, null);
tables.next();
tables.close();
connection.close();
}
/**
* Reads from a table.
*/
@Test void testSelect() {
sql("model", "select * from EMPS").ok();
}
@Test void testSelectSingleProjectGz() {
sql("smart", "select name from EMPS").ok();
}
@Test void testSelectSingleProject() {
sql("smart", "select name from DEPTS").ok();
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-898">[CALCITE-898]
* Type inference multiplying Java long by SQL INTEGER</a>. */
@Test void testSelectLongMultiplyInteger() {
final String sql = "select empno * 3 as e3\n"
+ "from long_emps where empno = 100";
sql("bug", sql).checking(resultSet -> {
try {
assertThat(resultSet.next(), is(true));
Long o = (Long) resultSet.getObject(1);
assertThat(o, is(300L));
assertThat(resultSet.next(), is(false));
} catch (SQLException e) {
throw TestUtil.rethrow(e);
}
}).ok();
}
@Test void testCustomTable() {
sql("model-with-custom-table", "select * from CUSTOM_TABLE.EMPS").ok();
}
@Test void testPushDownProject() {
final String sql = "explain plan for select * from EMPS";
final String expected = "PLAN=CsvTableScan(table=[[SALES, EMPS]], "
+ "fields=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])\n";
sql("smart", sql).returns(expected).ok();
}
@Test void testPushDownProject2() {
sql("smart", "explain plan for select name, empno from EMPS")
.returns("PLAN=CsvTableScan(table=[[SALES, EMPS]], fields=[[1, 0]])\n")
.ok();
// make sure that it works...
sql("smart", "select name, empno from EMPS")
.returns("NAME=Fred; EMPNO=100",
"NAME=Eric; EMPNO=110",
"NAME=John; EMPNO=110",
"NAME=Wilma; EMPNO=120",
"NAME=Alice; EMPNO=130")
.ok();
}
@ParameterizedTest
@MethodSource("explainFormats")
void testPushDownProjectAggregate(String format) {
String expected = null;
String extra = null;
switch (format) {
case "dot":
expected = "PLAN=digraph {\n"
+ "\"CsvTableScan\\ntable = [SALES, EMPS\\n]\\nfields = [3]\\n\" -> "
+ "\"EnumerableAggregate\\ngroup = {0}\\nEXPR$1 = COUNT()\\n\" [label=\"0\"]\n"
+ "}\n";
extra = " as dot ";
break;
case "text":
expected = "PLAN="
+ "EnumerableAggregate(group=[{0}], EXPR$1=[COUNT()])\n"
+ " CsvTableScan(table=[[SALES, EMPS]], fields=[[3]])\n";
extra = "";
break;
}
final String sql = "explain plan " + extra + " for\n"
+ "select gender, count(*) from EMPS group by gender";
sql("smart", sql).returns(expected).ok();
}
@ParameterizedTest
@MethodSource("explainFormats")
void testPushDownProjectAggregateWithFilter(String format) {
String expected = null;
String extra = null;
switch (format) {
case "dot":
expected = "PLAN=digraph {\n"
+ "\"EnumerableCalc\\nexpr#0..1 = {inputs}\\nexpr#2 = 'F':VARCHAR\\nexpr#3 = =($t1, $t2)"
+ "\\nproj#0..1 = {exprs}\\n$condition = $t3\" -> \"EnumerableAggregate\\ngroup = "
+ "{}\\nEXPR$0 = MAX($0)\\n\" [label=\"0\"]\n"
+ "\"CsvTableScan\\ntable = [SALES, EMPS\\n]\\nfields = [0, 3]\\n\" -> "
+ "\"EnumerableCalc\\nexpr#0..1 = {inputs}\\nexpr#2 = 'F':VARCHAR\\nexpr#3 = =($t1, $t2)"
+ "\\nproj#0..1 = {exprs}\\n$condition = $t3\" [label=\"0\"]\n"
+ "}\n";
extra = " as dot ";
break;
case "text":
expected = "PLAN="
+ "EnumerableAggregate(group=[{}], EXPR$0=[MAX($0)])\n"
+ " EnumerableCalc(expr#0..1=[{inputs}], expr#2=['F':VARCHAR], "
+ "expr#3=[=($t1, $t2)], proj#0..1=[{exprs}], $condition=[$t3])\n"
+ " CsvTableScan(table=[[SALES, EMPS]], fields=[[0, 3]])\n";
extra = "";
break;
}
final String sql = "explain plan " + extra + " for\n"
+ "select max(empno) from EMPS where gender='F'";
sql("smart", sql).returns(expected).ok();
}
@ParameterizedTest
@MethodSource("explainFormats")
void testPushDownProjectAggregateNested(String format) {
String expected = null;
String extra = null;
switch (format) {
case "dot":
expected = "PLAN=digraph {\n"
+ "\"EnumerableAggregate\\ngroup = {0, 1}\\nQTY = COUNT()\\n\" -> "
+ "\"EnumerableAggregate\\ngroup = {1}\\nEXPR$1 = MAX($2)\\n\" [label=\"0\"]\n"
+ "\"CsvTableScan\\ntable = [SALES, EMPS\\n]\\nfields = [1, 3]\\n\" -> "
+ "\"EnumerableAggregate\\ngroup = {0, 1}\\nQTY = COUNT()\\n\" [label=\"0\"]\n"
+ "}\n";
extra = " as dot ";
break;
case "text":
expected = "PLAN="
+ "EnumerableAggregate(group=[{1}], EXPR$1=[MAX($2)])\n"
+ " EnumerableAggregate(group=[{0, 1}], QTY=[COUNT()])\n"
+ " CsvTableScan(table=[[SALES, EMPS]], fields=[[1, 3]])\n";
extra = "";
break;
}
final String sql = "explain plan " + extra + " for\n"
+ "select gender, max(qty)\n"
+ "from (\n"
+ " select name, gender, count(*) qty\n"
+ " from EMPS\n"
+ " group by name, gender) t\n"
+ "group by gender";
sql("smart", sql).returns(expected).ok();
}
@Test void testFilterableSelect() {
sql("filterable-model", "select name from EMPS").ok();
}
@Test void testFilterableSelectStar() {
sql("filterable-model", "select * from EMPS").ok();
}
/** Filter that can be fully handled by CsvFilterableTable. */
@Test void testFilterableWhere() {
final String sql =
"select empno, gender, name from EMPS where name = 'John'";
sql("filterable-model", sql)
.returns("EMPNO=110; GENDER=M; NAME=John").ok();
}
/** Filter that can be partly handled by CsvFilterableTable. */
@Test void testFilterableWhere2() {
final String sql = "select empno, gender, name from EMPS\n"
+ " where gender = 'F' and empno > 125";
sql("filterable-model", sql)
.returns("EMPNO=130; GENDER=F; NAME=Alice").ok();
}
/** Filter that can be slightly handled by CsvFilterableTable. */
@Test void testFilterableWhere3() {
final String sql = "select empno, gender, name from EMPS\n"
+ " where gender <> 'M' and empno > 125";
sql("filterable-model", sql)
.returns("EMPNO=130; GENDER=F; NAME=Alice")
.ok();
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-2272">[CALCITE-2272]
* Incorrect result for {@code name like '%E%' and city not like '%W%'}</a>.
*/
@Test void testFilterableWhereWithNot1() {
sql("filterable-model",
"select name, empno from EMPS "
+ "where name like '%E%' and city not like '%W%' ")
.returns("NAME=Eric; EMPNO=110")
.ok();
}
/** Similar to {@link #testFilterableWhereWithNot1()};
* But use the same column. */
@Test void testFilterableWhereWithNot2() {
sql("filterable-model",
"select name, empno from EMPS "
+ "where name like '%i%' and name not like '%W%' ")
.returns("NAME=Eric; EMPNO=110",
"NAME=Alice; EMPNO=130")
.ok();
}
@Test void testJson() {
final String sql = "select * from archers\n";
final String[] lines = {
"id=19990101; dow=Friday; longDate=New Years Day; title=Tractor trouble.; "
+ "characters=[Alice, Bob, Xavier]; script=Julian Hyde; summary=; "
+ "lines=[Bob's tractor got stuck in a field., "
+ "Alice and Xavier hatch a plan to surprise Charlie.]",
"id=19990103; dow=Sunday; longDate=Sunday 3rd January; "
+ "title=Charlie's surprise.; characters=[Alice, Zebedee, Charlie, Xavier]; "
+ "script=William Shakespeare; summary=; "
+ "lines=[Charlie is very surprised by Alice and Xavier's surprise plan.]",
};
sql("bug", sql)
.returns(lines)
.ok();
}
@Test void testJoinOnString() {
final String sql = "select * from emps\n"
+ "join depts on emps.name = depts.name";
sql("smart", sql).ok();
}
@Test void testWackyColumns() {
final String sql = "select * from wacky_column_names where false";
sql("bug", sql).returns().ok();
final String sql2 = "select \"joined at\", \"naME\"\n"
+ "from wacky_column_names\n"
+ "where \"2gender\" = 'F'";
sql("bug", sql2)
.returns("joined at=2005-09-07; naME=Wilma",
"joined at=2007-01-01; naME=Alice")
.ok();
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1754">[CALCITE-1754]
* In Csv adapter, convert DATE and TIME values to int, and TIMESTAMP values
* to long</a>. */
@Test void testGroupByTimestampAdd() {
final String sql = "select count(*) as c,\n"
+ " {fn timestampadd(SQL_TSI_DAY, 1, JOINEDAT) } as t\n"
+ "from EMPS group by {fn timestampadd(SQL_TSI_DAY, 1, JOINEDAT ) } ";
sql("model", sql)
.returnsUnordered("C=1; T=1996-08-04",
"C=1; T=2002-05-04",
"C=1; T=2005-09-08",
"C=1; T=2007-01-02",
"C=1; T=2001-01-02")
.ok();
final String sql2 = "select count(*) as c,\n"
+ " {fn timestampadd(SQL_TSI_MONTH, 1, JOINEDAT) } as t\n"
+ "from EMPS group by {fn timestampadd(SQL_TSI_MONTH, 1, JOINEDAT ) } ";
sql("model", sql2)
.returnsUnordered("C=1; T=2002-06-03",
"C=1; T=2005-10-07",
"C=1; T=2007-02-01",
"C=1; T=2001-02-01",
"C=1; T=1996-09-03")
.ok();
}
@Test void testUnionGroupByWithoutGroupKey() {
final String sql = "select count(*) as c1 from EMPS group by NAME\n"
+ "union\n"
+ "select count(*) as c1 from EMPS group by NAME";
sql("model", sql).ok();
}
@Test void testBoolean() {
sql("smart", "select empno, slacker from emps where slacker")
.returns("EMPNO=100; SLACKER=true").ok();
}
@Test void testReadme() {
final String sql = "SELECT d.name, COUNT(*) cnt"
+ " FROM emps AS e"
+ " JOIN depts AS d ON e.deptno = d.deptno"
+ " GROUP BY d.name";
sql("smart", sql)
.returns("NAME=Sales; CNT=1", "NAME=Marketing; CNT=2").ok();
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-824">[CALCITE-824]
* Type inference when converting IN clause to semijoin</a>. */
@Test void testInToSemiJoinWithCast() {
// Note that the IN list needs at least 20 values to trigger the rewrite
// to a semijoin. Try it both ways.
final String sql = "SELECT e.name\n"
+ "FROM emps AS e\n"
+ "WHERE cast(e.empno as bigint) in ";
final int threshold = SqlToRelConverter.DEFAULT_IN_SUB_QUERY_THRESHOLD;
sql("smart", sql + range(130, threshold - 5))
.returns("NAME=Alice").ok();
sql("smart", sql + range(130, threshold))
.returns("NAME=Alice").ok();
sql("smart", sql + range(130, threshold + 1000))
.returns("NAME=Alice").ok();
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1051">[CALCITE-1051]
* Underflow exception due to scaling IN clause literals</a>. */
@Test void testInToSemiJoinWithoutCast() {
final String sql = "SELECT e.name\n"
+ "FROM emps AS e\n"
+ "WHERE e.empno in "
+ range(130, SqlToRelConverter.DEFAULT_IN_SUB_QUERY_THRESHOLD);
sql("smart", sql).returns("NAME=Alice").ok();
}
private String range(int first, int count) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(i == 0 ? "(" : ", ").append(first + i);
}
return sb.append(')').toString();
}
@Test void testDateType() throws SQLException {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info)) {
ResultSet res = connection.getMetaData().getColumns(null, null,
"DATE", "JOINEDAT");
res.next();
assertEquals(res.getInt("DATA_TYPE"), Types.DATE);
res = connection.getMetaData().getColumns(null, null,
"DATE", "JOINTIME");
res.next();
assertEquals(res.getInt("DATA_TYPE"), Types.TIME);
res = connection.getMetaData().getColumns(null, null,
"DATE", "JOINTIMES");
res.next();
assertEquals(res.getInt("DATA_TYPE"), Types.TIMESTAMP);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(
"select \"JOINEDAT\", \"JOINTIME\", \"JOINTIMES\" from \"DATE\" where EMPNO = 100");
resultSet.next();
// date
assertEquals(Date.class, resultSet.getDate(1).getClass());
assertEquals(Date.valueOf("1996-08-03"), resultSet.getDate(1));
// time
assertEquals(Time.class, resultSet.getTime(2).getClass());
assertEquals(Time.valueOf("00:01:02"), resultSet.getTime(2));
// timestamp
assertEquals(Timestamp.class, resultSet.getTimestamp(3).getClass());
assertEquals(Timestamp.valueOf("1996-08-03 00:01:02"),
resultSet.getTimestamp(3));
}
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1072">[CALCITE-1072]
* CSV adapter incorrectly parses TIMESTAMP values after noon</a>. */
@Test void testDateType2() throws SQLException {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info)) {
Statement statement = connection.createStatement();
final String sql = "select * from \"DATE\"\n"
+ "where EMPNO >= 140 and EMPNO < 200";
ResultSet resultSet = statement.executeQuery(sql);
int n = 0;
while (resultSet.next()) {
++n;
final int empId = resultSet.getInt(1);
final String date = resultSet.getString(2);
final String time = resultSet.getString(3);
final String timestamp = resultSet.getString(4);
assertThat(date, is("2015-12-31"));
switch (empId) {
case 140:
assertThat(time, is("07:15:56"));
assertThat(timestamp, is("2015-12-31 07:15:56"));
break;
case 150:
assertThat(time, is("13:31:21"));
assertThat(timestamp, is("2015-12-31 13:31:21"));
break;
default:
throw new AssertionError();
}
}
assertThat(n, is(2));
resultSet.close();
statement.close();
}
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1673">[CALCITE-1673]
* Query with ORDER BY or GROUP BY on TIMESTAMP column throws
* CompileException</a>. */
@Test void testTimestampGroupBy() throws SQLException {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
// Use LIMIT to ensure that results are deterministic without ORDER BY
final String sql = "select \"EMPNO\", \"JOINTIMES\"\n"
+ "from (select * from \"DATE\" limit 1)\n"
+ "group by \"EMPNO\",\"JOINTIMES\"";
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
assertThat(resultSet.next(), is(true));
final Timestamp timestamp = resultSet.getTimestamp(2);
assertThat(timestamp, isA(Timestamp.class));
// Note: This logic is time zone specific, but the same time zone is
// used in the CSV adapter and this test, so they should cancel out.
assertThat(timestamp, is(Timestamp.valueOf("1996-08-03 00:01:02.0")));
}
}
/** As {@link #testTimestampGroupBy()} but with ORDER BY. */
@Test void testTimestampOrderBy() throws SQLException {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
final String sql = "select \"EMPNO\",\"JOINTIMES\" from \"DATE\"\n"
+ "order by \"JOINTIMES\"";
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
assertThat(resultSet.next(), is(true));
final Timestamp timestamp = resultSet.getTimestamp(2);
assertThat(timestamp, is(Timestamp.valueOf("1996-08-03 00:01:02")));
}
}
/** As {@link #testTimestampGroupBy()} but with ORDER BY as well as GROUP
* BY. */
@Test void testTimestampGroupByAndOrderBy() throws SQLException {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
final String sql = "select \"EMPNO\", \"JOINTIMES\" from \"DATE\"\n"
+ "group by \"EMPNO\",\"JOINTIMES\" order by \"JOINTIMES\"";
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
assertThat(resultSet.next(), is(true));
final Timestamp timestamp = resultSet.getTimestamp(2);
assertThat(timestamp, is(Timestamp.valueOf("1996-08-03 00:01:02")));
}
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1031">[CALCITE-1031]
* In prepared statement, CsvScannableTable.scan is called twice</a>. To see
* the bug, place a breakpoint in CsvScannableTable.scan, and note that it is
* called twice. It should only be called once. */
@Test void testPrepared() throws SQLException {
final Properties properties = new Properties();
properties.setProperty("caseSensitive", "true");
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", properties)) {
final CalciteConnection calciteConnection = connection.unwrap(
CalciteConnection.class);
final Schema schema =
FileSchemaFactory.INSTANCE
.create(calciteConnection.getRootSchema(), null,
ImmutableMap.of("directory",
FileAdapterTests.resourcePath("sales-csv"), "flavor", "scannable"));
calciteConnection.getRootSchema().add("TEST", schema);
final String sql = "select * from \"TEST\".\"DEPTS\" where \"NAME\" = ?";
final PreparedStatement statement2 =
calciteConnection.prepareStatement(sql);
statement2.setString(1, "Sales");
final ResultSet resultSet1 = statement2.executeQuery();
Consumer<ResultSet> expect = FileAdapterTests.expect("DEPTNO=10; NAME=Sales");
expect.accept(resultSet1);
}
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1054">[CALCITE-1054]
* NPE caused by wrong code generation for Timestamp fields</a>. */
@Test void testFilterOnNullableTimestamp() throws Exception {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info)) {
final Statement statement = connection.createStatement();
// date
final String sql1 = "select JOINEDAT from \"DATE\"\n"
+ "where JOINEDAT < {d '2000-01-01'}\n"
+ "or JOINEDAT >= {d '2017-01-01'}";
final ResultSet joinedAt = statement.executeQuery(sql1);
assertThat(joinedAt.next(), is(true));
assertThat(joinedAt.getDate(1), is(Date.valueOf("1996-08-03")));
// time
final String sql2 = "select JOINTIME from \"DATE\"\n"
+ "where JOINTIME >= {t '07:00:00'}\n"
+ "and JOINTIME < {t '08:00:00'}";
final ResultSet joinTime = statement.executeQuery(sql2);
assertThat(joinTime.next(), is(true));
assertThat(joinTime.getTime(1), is(Time.valueOf("07:15:56")));
// timestamp
final String sql3 = "select JOINTIMES,\n"
+ " {fn timestampadd(SQL_TSI_DAY, 1, JOINTIMES)}\n"
+ "from \"DATE\"\n"
+ "where (JOINTIMES >= {ts '2003-01-01 00:00:00'}\n"
+ "and JOINTIMES < {ts '2006-01-01 00:00:00'})\n"
+ "or (JOINTIMES >= {ts '2003-01-01 00:00:00'}\n"
+ "and JOINTIMES < {ts '2007-01-01 00:00:00'})";
final ResultSet joinTimes = statement.executeQuery(sql3);
assertThat(joinTimes.next(), is(true));
assertThat(joinTimes.getTimestamp(1),
is(Timestamp.valueOf("2005-09-07 00:00:00")));
assertThat(joinTimes.getTimestamp(2),
is(Timestamp.valueOf("2005-09-08 00:00:00")));
final String sql4 = "select JOINTIMES, extract(year from JOINTIMES)\n"
+ "from \"DATE\"";
final ResultSet joinTimes2 = statement.executeQuery(sql4);
assertThat(joinTimes2.next(), is(true));
assertThat(joinTimes2.getTimestamp(1),
is(Timestamp.valueOf("1996-08-03 00:01:02")));
}
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1118">[CALCITE-1118]
* NullPointerException in EXTRACT with WHERE ... IN clause if field has null
* value</a>. */
@Test void testFilterOnNullableTimestamp2() throws Exception {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info)) {
final Statement statement = connection.createStatement();
final String sql1 = "select extract(year from JOINTIMES)\n"
+ "from \"DATE\"\n"
+ "where extract(year from JOINTIMES) in (2006, 2007)";
final ResultSet joinTimes = statement.executeQuery(sql1);
assertThat(joinTimes.next(), is(true));
assertThat(joinTimes.getInt(1), is(2007));
final String sql2 = "select extract(year from JOINTIMES),\n"
+ " count(0) from \"DATE\"\n"
+ "where extract(year from JOINTIMES) between 2007 and 2016\n"
+ "group by extract(year from JOINTIMES)";
final ResultSet joinTimes2 = statement.executeQuery(sql2);
assertThat(joinTimes2.next(), is(true));
assertThat(joinTimes2.getInt(1), is(2007));
assertThat(joinTimes2.getLong(2), is(1L));
assertThat(joinTimes2.next(), is(true));
assertThat(joinTimes2.getInt(1), is(2015));
assertThat(joinTimes2.getLong(2), is(2L));
}
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1427">[CALCITE-1427]
* Code generation incorrect (does not compile) for DATE, TIME and TIMESTAMP
* fields</a>. */
@Test void testNonNullFilterOnDateType() throws SQLException {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info)) {
final Statement statement = connection.createStatement();
// date
final String sql1 = "select JOINEDAT from \"DATE\"\n"
+ "where JOINEDAT is not null";
final ResultSet joinedAt = statement.executeQuery(sql1);
assertThat(joinedAt.next(), is(true));
assertThat(joinedAt.getDate(1).getClass(), equalTo(Date.class));
assertThat(joinedAt.getDate(1), is(Date.valueOf("1996-08-03")));
// time
final String sql2 = "select JOINTIME from \"DATE\"\n"
+ "where JOINTIME is not null";
final ResultSet joinTime = statement.executeQuery(sql2);
assertThat(joinTime.next(), is(true));
assertThat(joinTime.getTime(1).getClass(), equalTo(Time.class));
assertThat(joinTime.getTime(1), is(Time.valueOf("00:01:02")));
// timestamp
final String sql3 = "select JOINTIMES from \"DATE\"\n"
+ "where JOINTIMES is not null";
final ResultSet joinTimes = statement.executeQuery(sql3);
assertThat(joinTimes.next(), is(true));
assertThat(joinTimes.getTimestamp(1).getClass(),
equalTo(Timestamp.class));
assertThat(joinTimes.getTimestamp(1),
is(Timestamp.valueOf("1996-08-03 00:01:02")));
}
}
/** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1427">[CALCITE-1427]
* Code generation incorrect (does not compile) for DATE, TIME and TIMESTAMP
* fields</a>. */
@Test void testGreaterThanFilterOnDateType() throws SQLException {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info)) {
final Statement statement = connection.createStatement();
// date
final String sql1 = "select JOINEDAT from \"DATE\"\n"
+ "where JOINEDAT > {d '1990-01-01'}";
final ResultSet joinedAt = statement.executeQuery(sql1);
assertThat(joinedAt.next(), is(true));
assertThat(joinedAt.getDate(1).getClass(), equalTo(Date.class));
assertThat(joinedAt.getDate(1), is(Date.valueOf("1996-08-03")));
// time
final String sql2 = "select JOINTIME from \"DATE\"\n"
+ "where JOINTIME > {t '00:00:00'}";
final ResultSet joinTime = statement.executeQuery(sql2);
assertThat(joinTime.next(), is(true));
assertThat(joinTime.getTime(1).getClass(), equalTo(Time.class));
assertThat(joinTime.getTime(1), is(Time.valueOf("00:01:02")));
// timestamp
final String sql3 = "select JOINTIMES from \"DATE\"\n"
+ "where JOINTIMES > {ts '1990-01-01 00:00:00'}";
final ResultSet joinTimes = statement.executeQuery(sql3);
assertThat(joinTimes.next(), is(true));
assertThat(joinTimes.getTimestamp(1).getClass(),
equalTo(Timestamp.class));
assertThat(joinTimes.getTimestamp(1),
is(Timestamp.valueOf("1996-08-03 00:01:02")));
}
}
}
| apache-2.0 |
dain/presto | plugin/trino-memory/src/main/java/io/trino/plugin/memory/MemoryMetadata.java | 17172 | /*
* 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.memory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import io.airlift.slice.Slice;
import io.trino.spi.HostAddress;
import io.trino.spi.Node;
import io.trino.spi.NodeManager;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.ColumnHandle;
import io.trino.spi.connector.ColumnMetadata;
import io.trino.spi.connector.ConnectorInsertTableHandle;
import io.trino.spi.connector.ConnectorMetadata;
import io.trino.spi.connector.ConnectorNewTableLayout;
import io.trino.spi.connector.ConnectorOutputMetadata;
import io.trino.spi.connector.ConnectorOutputTableHandle;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableHandle;
import io.trino.spi.connector.ConnectorTableMetadata;
import io.trino.spi.connector.ConnectorTableProperties;
import io.trino.spi.connector.ConnectorViewDefinition;
import io.trino.spi.connector.Constraint;
import io.trino.spi.connector.LimitApplicationResult;
import io.trino.spi.connector.SampleApplicationResult;
import io.trino.spi.connector.SampleType;
import io.trino.spi.connector.SchemaNotFoundException;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.connector.SchemaTablePrefix;
import io.trino.spi.connector.ViewNotFoundException;
import io.trino.spi.security.TrinoPrincipal;
import io.trino.spi.statistics.ComputedStatistics;
import io.trino.spi.statistics.Estimate;
import io.trino.spi.statistics.TableStatistics;
import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static io.trino.spi.StandardErrorCode.ALREADY_EXISTS;
import static io.trino.spi.StandardErrorCode.NOT_FOUND;
import static io.trino.spi.StandardErrorCode.SCHEMA_NOT_EMPTY;
import static io.trino.spi.connector.SampleType.SYSTEM;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
@ThreadSafe
public class MemoryMetadata
implements ConnectorMetadata
{
public static final String SCHEMA_NAME = "default";
private final NodeManager nodeManager;
private final List<String> schemas = new ArrayList<>();
private final AtomicLong nextTableId = new AtomicLong();
private final Map<SchemaTableName, Long> tableIds = new HashMap<>();
private final Map<Long, TableInfo> tables = new HashMap<>();
private final Map<SchemaTableName, ConnectorViewDefinition> views = new HashMap<>();
@Inject
public MemoryMetadata(NodeManager nodeManager)
{
this.nodeManager = requireNonNull(nodeManager, "nodeManager is null");
this.schemas.add(SCHEMA_NAME);
}
@Override
public synchronized List<String> listSchemaNames(ConnectorSession session)
{
return ImmutableList.copyOf(schemas);
}
@Override
public synchronized void createSchema(ConnectorSession session, String schemaName, Map<String, Object> properties, TrinoPrincipal owner)
{
if (schemas.contains(schemaName)) {
throw new TrinoException(ALREADY_EXISTS, format("Schema [%s] already exists", schemaName));
}
schemas.add(schemaName);
}
@Override
public synchronized void dropSchema(ConnectorSession session, String schemaName)
{
if (!schemas.contains(schemaName)) {
throw new TrinoException(NOT_FOUND, format("Schema [%s] does not exist", schemaName));
}
boolean tablesExist = tables.values().stream()
.anyMatch(table -> table.getSchemaName().equals(schemaName));
if (tablesExist) {
throw new TrinoException(SCHEMA_NOT_EMPTY, "Schema not empty: " + schemaName);
}
verify(schemas.remove(schemaName));
}
@Override
public synchronized ConnectorTableHandle getTableHandle(ConnectorSession session, SchemaTableName schemaTableName)
{
Long id = tableIds.get(schemaTableName);
if (id == null) {
return null;
}
return new MemoryTableHandle(id);
}
@Override
public synchronized ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle tableHandle)
{
MemoryTableHandle handle = (MemoryTableHandle) tableHandle;
return tables.get(handle.getId()).getMetadata();
}
@Override
public synchronized List<SchemaTableName> listTables(ConnectorSession session, Optional<String> schemaName)
{
ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder();
views.keySet().stream()
.filter(table -> schemaName.map(table.getSchemaName()::contentEquals).orElse(true))
.forEach(builder::add);
tables.values().stream()
.filter(table -> schemaName.map(table.getSchemaName()::contentEquals).orElse(true))
.map(TableInfo::getSchemaTableName)
.forEach(builder::add);
return builder.build();
}
@Override
public synchronized Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle)
{
MemoryTableHandle handle = (MemoryTableHandle) tableHandle;
return tables.get(handle.getId())
.getColumns().stream()
.collect(toImmutableMap(ColumnInfo::getName, ColumnInfo::getHandle));
}
@Override
public synchronized ColumnMetadata getColumnMetadata(ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle)
{
MemoryTableHandle handle = (MemoryTableHandle) tableHandle;
return tables.get(handle.getId())
.getColumn(columnHandle)
.getMetadata();
}
@Override
public synchronized Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix)
{
return tables.values().stream()
.filter(table -> prefix.matches(table.getSchemaTableName()))
.collect(toImmutableMap(TableInfo::getSchemaTableName, handle -> handle.getMetadata().getColumns()));
}
@Override
public synchronized void dropTable(ConnectorSession session, ConnectorTableHandle tableHandle)
{
MemoryTableHandle handle = (MemoryTableHandle) tableHandle;
TableInfo info = tables.remove(handle.getId());
if (info != null) {
tableIds.remove(info.getSchemaTableName());
}
}
@Override
public synchronized void renameTable(ConnectorSession session, ConnectorTableHandle tableHandle, SchemaTableName newTableName)
{
checkSchemaExists(newTableName.getSchemaName());
checkTableNotExists(newTableName);
MemoryTableHandle handle = (MemoryTableHandle) tableHandle;
long tableId = handle.getId();
TableInfo oldInfo = tables.get(tableId);
tables.put(tableId, new TableInfo(tableId, newTableName.getSchemaName(), newTableName.getTableName(), oldInfo.getColumns(), oldInfo.getDataFragments()));
tableIds.remove(oldInfo.getSchemaTableName());
tableIds.put(newTableName, tableId);
}
@Override
public synchronized void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, boolean ignoreExisting)
{
ConnectorOutputTableHandle outputTableHandle = beginCreateTable(session, tableMetadata, Optional.empty());
finishCreateTable(session, outputTableHandle, ImmutableList.of(), ImmutableList.of());
}
@Override
public synchronized MemoryOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata, Optional<ConnectorNewTableLayout> layout)
{
checkSchemaExists(tableMetadata.getTable().getSchemaName());
checkTableNotExists(tableMetadata.getTable());
long tableId = nextTableId.getAndIncrement();
Set<Node> nodes = nodeManager.getRequiredWorkerNodes();
checkState(!nodes.isEmpty(), "No Memory nodes available");
ImmutableList.Builder<ColumnInfo> columns = ImmutableList.builder();
for (int i = 0; i < tableMetadata.getColumns().size(); i++) {
ColumnMetadata column = tableMetadata.getColumns().get(i);
columns.add(new ColumnInfo(new MemoryColumnHandle(i), column.getName(), column.getType()));
}
tableIds.put(tableMetadata.getTable(), tableId);
tables.put(tableId, new TableInfo(
tableId,
tableMetadata.getTable().getSchemaName(),
tableMetadata.getTable().getTableName(),
columns.build(),
new HashMap<>()));
return new MemoryOutputTableHandle(tableId, ImmutableSet.copyOf(tableIds.values()));
}
private void checkSchemaExists(String schemaName)
{
if (!schemas.contains(schemaName)) {
throw new SchemaNotFoundException(schemaName);
}
}
private void checkTableNotExists(SchemaTableName tableName)
{
if (tableIds.containsKey(tableName)) {
throw new TrinoException(ALREADY_EXISTS, format("Table [%s] already exists", tableName.toString()));
}
if (views.containsKey(tableName)) {
throw new TrinoException(ALREADY_EXISTS, format("View [%s] already exists", tableName.toString()));
}
}
@Override
public synchronized Optional<ConnectorOutputMetadata> finishCreateTable(ConnectorSession session, ConnectorOutputTableHandle tableHandle, Collection<Slice> fragments, Collection<ComputedStatistics> computedStatistics)
{
requireNonNull(tableHandle, "tableHandle is null");
MemoryOutputTableHandle memoryOutputHandle = (MemoryOutputTableHandle) tableHandle;
updateRowsOnHosts(memoryOutputHandle.getTable(), fragments);
return Optional.empty();
}
@Override
public synchronized MemoryInsertTableHandle beginInsert(ConnectorSession session, ConnectorTableHandle tableHandle, List<ColumnHandle> columns)
{
MemoryTableHandle memoryTableHandle = (MemoryTableHandle) tableHandle;
return new MemoryInsertTableHandle(memoryTableHandle.getId(), ImmutableSet.copyOf(tableIds.values()));
}
@Override
public synchronized Optional<ConnectorOutputMetadata> finishInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments, Collection<ComputedStatistics> computedStatistics)
{
requireNonNull(insertHandle, "insertHandle is null");
MemoryInsertTableHandle memoryInsertHandle = (MemoryInsertTableHandle) insertHandle;
updateRowsOnHosts(memoryInsertHandle.getTable(), fragments);
return Optional.empty();
}
@Override
public synchronized void createView(ConnectorSession session, SchemaTableName viewName, ConnectorViewDefinition definition, boolean replace)
{
checkSchemaExists(viewName.getSchemaName());
if (tableIds.containsKey(viewName)) {
throw new TrinoException(ALREADY_EXISTS, "Table already exists: " + viewName);
}
if (replace) {
views.put(viewName, definition);
}
else if (views.putIfAbsent(viewName, definition) != null) {
throw new TrinoException(ALREADY_EXISTS, "View already exists: " + viewName);
}
}
@Override
public synchronized void renameView(ConnectorSession session, SchemaTableName viewName, SchemaTableName newViewName)
{
checkSchemaExists(newViewName.getSchemaName());
if (tableIds.containsKey(newViewName)) {
throw new TrinoException(ALREADY_EXISTS, "Table already exists: " + newViewName);
}
if (views.containsKey(newViewName)) {
throw new TrinoException(ALREADY_EXISTS, "View already exists: " + newViewName);
}
views.put(newViewName, views.remove(viewName));
}
@Override
public synchronized void dropView(ConnectorSession session, SchemaTableName viewName)
{
if (views.remove(viewName) == null) {
throw new ViewNotFoundException(viewName);
}
}
@Override
public synchronized List<SchemaTableName> listViews(ConnectorSession session, Optional<String> schemaName)
{
return views.keySet().stream()
.filter(viewName -> schemaName.map(viewName.getSchemaName()::equals).orElse(true))
.collect(toImmutableList());
}
@Override
public synchronized Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, Optional<String> schemaName)
{
SchemaTablePrefix prefix = schemaName.map(SchemaTablePrefix::new).orElseGet(SchemaTablePrefix::new);
return ImmutableMap.copyOf(Maps.filterKeys(views, prefix::matches));
}
@Override
public synchronized Optional<ConnectorViewDefinition> getView(ConnectorSession session, SchemaTableName viewName)
{
return Optional.ofNullable(views.get(viewName));
}
private void updateRowsOnHosts(long tableId, Collection<Slice> fragments)
{
TableInfo info = tables.get(tableId);
checkState(
info != null,
"Uninitialized tableId [%s.%s]",
info.getSchemaName(),
info.getTableName());
Map<HostAddress, MemoryDataFragment> dataFragments = new HashMap<>(info.getDataFragments());
for (Slice fragment : fragments) {
MemoryDataFragment memoryDataFragment = MemoryDataFragment.fromSlice(fragment);
dataFragments.merge(memoryDataFragment.getHostAddress(), memoryDataFragment, MemoryDataFragment::merge);
}
tables.put(tableId, new TableInfo(tableId, info.getSchemaName(), info.getTableName(), info.getColumns(), dataFragments));
}
@Override
public boolean usesLegacyTableLayouts()
{
return false;
}
@Override
public ConnectorTableProperties getTableProperties(ConnectorSession session, ConnectorTableHandle table)
{
return new ConnectorTableProperties();
}
public List<MemoryDataFragment> getDataFragments(long tableId)
{
return ImmutableList.copyOf(tables.get(tableId).getDataFragments().values());
}
@Override
public TableStatistics getTableStatistics(ConnectorSession session, ConnectorTableHandle tableHandle, Constraint constraint)
{
List<MemoryDataFragment> dataFragments = getDataFragments(((MemoryTableHandle) tableHandle).getId());
long rows = dataFragments.stream()
.mapToLong(MemoryDataFragment::getRows)
.sum();
return TableStatistics.builder()
.setRowCount(Estimate.of(rows))
.build();
}
@Override
public Optional<LimitApplicationResult<ConnectorTableHandle>> applyLimit(ConnectorSession session, ConnectorTableHandle handle, long limit)
{
MemoryTableHandle table = (MemoryTableHandle) handle;
if (table.getLimit().isPresent() && table.getLimit().getAsLong() <= limit) {
return Optional.empty();
}
return Optional.of(new LimitApplicationResult<>(
new MemoryTableHandle(table.getId(), OptionalLong.of(limit), OptionalDouble.empty()),
true,
true));
}
@Override
public Optional<SampleApplicationResult<ConnectorTableHandle>> applySample(ConnectorSession session, ConnectorTableHandle handle, SampleType sampleType, double sampleRatio)
{
MemoryTableHandle table = (MemoryTableHandle) handle;
if ((table.getSampleRatio().isPresent() && table.getSampleRatio().getAsDouble() == sampleRatio) || sampleType != SYSTEM || table.getLimit().isPresent()) {
return Optional.empty();
}
return Optional.of(new SampleApplicationResult<>(
new MemoryTableHandle(table.getId(), table.getLimit(), OptionalDouble.of(table.getSampleRatio().orElse(1) * sampleRatio)),
true));
}
}
| apache-2.0 |
kalaspuffar/pdfbox | pdfbox/src/test/java/org/apache/pdfbox/pdfparser/TestPDFParser.java | 10807 | /*
* 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.pdfbox.pdfparser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.util.DateConverter;
import org.junit.jupiter.api.Test;
class TestPDFParser
{
private static final File TARGETPDFDIR = new File("target/pdfs");
@Test
void testPDFParserMissingCatalog() throws URISyntaxException
{
// PDFBOX-3060
try
{
Loader.loadPDF(new File(TestPDFParser.class.getResource("MissingCatalog.pdf").toURI()))
.close();
}
catch (Exception exception)
{
fail("Unexpected Exception");
}
}
/**
* Test whether /Info dictionary is retrieved correctly when rebuilding the trailer of a corrupt
* file. An incorrect algorithm would result in an outline dictionary being mistaken for an
* /Info.
*
* @throws IOException
*/
@Test
void testPDFBox3208() throws IOException
{
try (PDDocument doc = Loader
.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3208-L33MUTT2SVCWGCS6UIYL5TH3PNPXHIS6.pdf")))
{
PDDocumentInformation di = doc.getDocumentInformation();
assertEquals("Liquent Enterprise Services", di.getAuthor());
assertEquals("Liquent services server", di.getCreator());
assertEquals("Amyuni PDF Converter version 4.0.0.9", di.getProducer());
assertEquals("", di.getKeywords());
assertEquals("", di.getSubject());
assertEquals("892B77DE781B4E71A1BEFB81A51A5ABC_20140326022424.docx", di.getTitle());
assertEquals(DateConverter.toCalendar("D:20140326142505-02'00'"), di.getCreationDate());
assertEquals(DateConverter.toCalendar("20140326172513Z"), di.getModificationDate());
}
}
/**
* Test whether the /Info is retrieved correctly when rebuilding the trailer of a corrupt file,
* despite the /Info dictionary not having a modification date.
*
* @throws IOException
*/
@Test
void testPDFBox3940() throws IOException
{
try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3940-079977.pdf")))
{
PDDocumentInformation di = doc.getDocumentInformation();
assertEquals("Unknown", di.getAuthor());
assertEquals("C:REGULA~1IREGSFR_EQ_EM.WP", di.getCreator());
assertEquals("Acrobat PDFWriter 3.02 for Windows", di.getProducer());
assertEquals("", di.getKeywords());
assertEquals("", di.getSubject());
assertEquals("C:REGULA~1IREGSFR_EQ_EM.PDF", di.getTitle());
assertEquals(DateConverter.toCalendar("Tuesday, July 28, 1998 4:00:09 PM"), di.getCreationDate());
}
}
/**
* PDFBOX-3783: test parsing of file with trash after %%EOF.
*/
@Test
void testPDFBox3783()
{
try
{
Loader.loadPDF(
new File(TARGETPDFDIR, "PDFBOX-3783-72GLBIGUC6LB46ELZFBARRJTLN4RBSQM.pdf"))
.close();
}
catch (Exception exception)
{
fail("Unexpected IOException");
}
}
/**
* PDFBOX-3785, PDFBOX-3957:
* Test whether truncated file with several revisions has correct page count.
*
* @throws IOException
*/
@Test
void testPDFBox3785() throws IOException
{
try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3785-202097.pdf")))
{
assertEquals(11, doc.getNumberOfPages());
}
}
/**
* PDFBOX-3947: test parsing of file with broken object stream.
*/
@Test
void testPDFBox3947()
{
try
{
Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3947-670064.pdf")).close();
}
catch (Exception exception)
{
fail("Unexpected Exception");
}
}
/**
* PDFBOX-3948: test parsing of file with object stream containing some unexpected newlines.
*/
@Test
void testPDFBox3948()
{
try
{
Loader.loadPDF(
new File(TARGETPDFDIR, "PDFBOX-3948-EUWO6SQS5TM4VGOMRD3FLXZHU35V2CP2.pdf"))
.close();
}
catch (Exception exception)
{
fail("Unexpected Exception");
}
}
/**
* PDFBOX-3949: test parsing of file with incomplete object stream.
*/
@Test
void testPDFBox3949()
{
try
{
Loader.loadPDF(
new File(TARGETPDFDIR, "PDFBOX-3949-MKFYUGZWS3OPXLLVU2Z4LWCTVA5WNOGF.pdf"))
.close();
}
catch (Exception exception)
{
fail("Unexpected Exception");
}
}
/**
* PDFBOX-3950: test parsing and rendering of truncated file with missing pages.
*
* @throws IOException
*/
@Test
void testPDFBox3950() throws IOException
{
try (PDDocument doc = Loader
.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3950-23EGDHXSBBYQLKYOKGZUOVYVNE675PRD.pdf")))
{
assertEquals(4, doc.getNumberOfPages());
PDFRenderer renderer = new PDFRenderer(doc);
for (int i = 0; i < doc.getNumberOfPages(); ++i)
{
try
{
renderer.renderImage(i);
}
catch (IOException ex)
{
if (i == 3 && ex.getMessage().equals("Missing descendant font array"))
{
continue;
}
throw ex;
}
}
}
}
/**
* PDFBOX-3951: test parsing of truncated file.
*
* @throws IOException
*/
@Test
void testPDFBox3951() throws IOException
{
try (PDDocument doc = Loader
.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3951-FIHUZWDDL2VGPOE34N6YHWSIGSH5LVGZ.pdf")))
{
assertEquals(143, doc.getNumberOfPages());
}
}
/**
* PDFBOX-3964: test parsing of broken file.
*
* @throws IOException
*/
@Test
void testPDFBox3964() throws IOException
{
try (PDDocument doc = Loader
.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3964-c687766d68ac766be3f02aaec5e0d713_2.pdf")))
{
assertEquals(10, doc.getNumberOfPages());
}
}
/**
* Test whether /Info dictionary is retrieved correctly in brute force search for the
* Info/Catalog dictionaries.
*
* @throws IOException
*/
@Test
void testPDFBox3977() throws IOException
{
try (PDDocument doc = Loader
.loadPDF(new File(TARGETPDFDIR, "PDFBOX-3977-63NGFQRI44HQNPIPEJH5W2TBM6DJZWMI.pdf")))
{
PDDocumentInformation di = doc.getDocumentInformation();
assertEquals("QuarkXPress(tm) 6.52", di.getCreator());
assertEquals("Acrobat Distiller 7.0 pour Macintosh", di.getProducer());
assertEquals("Fich sal Fabr corr1 (Page 6)", di.getTitle());
assertEquals(DateConverter.toCalendar("D:20070608151915+02'00'"), di.getCreationDate());
assertEquals(DateConverter.toCalendar("D:20080604152122+02'00'"), di.getModificationDate());
}
}
/**
* Test parsing the "genko_oc_shiryo1.pdf" file, which is susceptible to regression.
*/
@Test
void testParseGenko()
{
try
{
Loader.loadPDF(new File(TARGETPDFDIR, "genko_oc_shiryo1.pdf")).close();
}
catch (Exception exception)
{
fail("Unexpected Exception");
}
}
/**
* Test parsing the file from PDFBOX-4338, which brought an
* ArrayIndexOutOfBoundsException before the bug was fixed.
*/
@Test
void testPDFBox4338()
{
try
{
Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4338.pdf")).close();
}
catch (Exception exception)
{
fail("Unexpected Exception");
}
}
/**
* Test parsing the file from PDFBOX-4339, which brought a
* NullPointerException before the bug was fixed.
*/
@Test
void testPDFBox4339()
{
try
{
Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4339.pdf")).close();
}
catch (Exception exception)
{
fail("Unexpected Exception");
}
}
/**
* Test parsing the "WXMDXCYRWFDCMOSFQJ5OAJIAFXYRZ5OA.pdf" file, which is susceptible to
* regression.
*
* @throws IOException
*/
@Test
void testPDFBox4153() throws IOException
{
try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4153-WXMDXCYRWFDCMOSFQJ5OAJIAFXYRZ5OA.pdf")))
{
PDDocumentOutline documentOutline = doc.getDocumentCatalog().getDocumentOutline();
PDOutlineItem firstChild = documentOutline.getFirstChild();
assertEquals("Main Menu", firstChild.getTitle());
}
}
/**
* Test that PDFBOX-4490 has 3 pages.
*
* @throws IOException
*/
@Test
void testPDFBox4490() throws IOException
{
try (PDDocument doc = Loader.loadPDF(new File(TARGETPDFDIR, "PDFBOX-4490.pdf")))
{
assertEquals(3, doc.getNumberOfPages());
}
}
}
| apache-2.0 |
kinbod/deeplearning4j | deeplearning4j-nn/src/main/java/org/deeplearning4j/eval/curves/BaseCurve.java | 3236 | package org.deeplearning4j.eval.curves;
import org.deeplearning4j.eval.BaseEvaluation;
import org.nd4j.shade.jackson.annotation.JsonTypeInfo;
import org.nd4j.shade.jackson.core.JsonProcessingException;
import java.io.IOException;
/**
* Abstract class for ROC and Precision recall curves
*
* @author Alex Black
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
public abstract class BaseCurve {
public static final int DEFAULT_FORMAT_PREC = 4;
/**
* @return The number of points in the curve
*/
public abstract int numPoints();
/**
* @return X axis values
*/
public abstract double[] getX();
/**
* @return Y-axis values
*/
public abstract double[] getY();
/**
* @return Title for the curve
*/
public abstract String getTitle();
/**
* @return Area under the curve
*/
protected double calculateArea() {
return calculateArea(getX(), getY());
}
protected double calculateArea(double[] x, double[] y) {
int nPoints = x.length;
double area = 0.0;
for (int i = 0; i < nPoints - 1; i++) {
double xLeft = x[i];
double yLeft = y[i];
double xRight = x[i + 1];
double yRight = y[i + 1];
//y axis: TPR
//x axis: FPR
double deltaX = Math.abs(xRight - xLeft); //Iterating in threshold order, so FPR decreases as threshold increases
double avg = (yRight + yLeft) / 2.0;
area += deltaX * avg;
}
return area;
}
protected String format(double d, int precision) {
return String.format("%." + precision + "f", d);
}
/**
* @return JSON representation of the curve
*/
public String toJson() {
try {
return BaseEvaluation.getObjectMapper().writeValueAsString(this);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
* @return YAML representation of the curve
*/
public String toYaml() {
try {
return BaseEvaluation.getYamlMapper().writeValueAsString(this);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
*
* @param json JSON representation
* @param curveClass Class for the curve
* @param <T> Type
* @return Instance of the curve
*/
public static <T extends BaseCurve> T fromJson(String json, Class<T> curveClass) {
try {
return BaseEvaluation.getObjectMapper().readValue(json, curveClass);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
*
* @param yaml YAML representation
* @param curveClass Class for the curve
* @param <T> Type
* @return Instance of the curve
*/
public static <T extends BaseCurve> T fromYaml(String yaml, Class<T> curveClass) {
try {
return BaseEvaluation.getYamlMapper().readValue(yaml, curveClass);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
DislabNJU/Hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/ResourceRequest.java | 12108 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.api.records;
import java.io.Serializable;
import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.classification.InterfaceStability.Stable;
import org.apache.hadoop.yarn.api.ApplicationMasterProtocol;
import org.apache.hadoop.yarn.util.Records;
/**
* <p><code>ResourceRequest</code> represents the request made by an
* application to the <code>ResourceManager</code> to obtain various
* <code>Container</code> allocations.</p>
*
* <p>It includes:
* <ul>
* <li>{@link Priority} of the request.</li>
* <li>
* The <em>name</em> of the machine or rack on which the allocation is
* desired. A special value of <em>*</em> signifies that
* <em>any</em> host/rack is acceptable to the application.
* </li>
* <li>{@link Resource} required for each request.</li>
* <li>
* Number of containers, of above specifications, which are required
* by the application.
* </li>
* <li>
* A boolean <em>relaxLocality</em> flag, defaulting to <code>true</code>,
* which tells the <code>ResourceManager</code> if the application wants
* locality to be loose (i.e. allows fall-through to rack or <em>any</em>)
* or strict (i.e. specify hard constraint on resource allocation).
* </li>
* </ul>
* </p>
*
* @see Resource
* @see ApplicationMasterProtocol#allocate(org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest)
*/
@Public
@Stable
public abstract class ResourceRequest implements Comparable<ResourceRequest> {
@Public
@Stable
public static ResourceRequest newInstance(Priority priority, String hostName,
Resource capability, int numContainers) {
return newInstance(priority, hostName, capability, numContainers, true);
}
@Public
@Stable
public static ResourceRequest newInstance(Priority priority, String hostName,
Resource capability, int numContainers, boolean relaxLocality) {
return newInstance(priority, hostName, capability, numContainers,
relaxLocality, null);
}
@Public
@Stable
public static ResourceRequest newInstance(Priority priority, String hostName,
Resource capability, int numContainers, boolean relaxLocality,
String labelExpression) {
ResourceRequest request = Records.newRecord(ResourceRequest.class);
request.setPriority(priority);
request.setResourceName(hostName);
request.setCapability(capability);
request.setNumContainers(numContainers);
request.setRelaxLocality(relaxLocality);
request.setNodeLabelExpression(labelExpression);
return request;
}
@Public
@Stable
public static class ResourceRequestComparator implements
java.util.Comparator<ResourceRequest>, Serializable {
private static final long serialVersionUID = 1L;
@Override
public int compare(ResourceRequest r1, ResourceRequest r2) {
// Compare priority, host and capability
int ret = r1.getPriority().compareTo(r2.getPriority());
if (ret == 0) {
String h1 = r1.getResourceName();
String h2 = r2.getResourceName();
ret = h1.compareTo(h2);
}
if (ret == 0) {
ret = r1.getCapability().compareTo(r2.getCapability());
}
return ret;
}
}
/**
* The constant string representing no locality.
* It should be used by all references that want to pass an arbitrary host
* name in.
*/
public static final String ANY = "*";
/**
* Check whether the given <em>host/rack</em> string represents an arbitrary
* host name.
*
* @param hostName <em>host/rack</em> on which the allocation is desired
* @return whether the given <em>host/rack</em> string represents an arbitrary
* host name
*/
@Public
@Stable
public static boolean isAnyLocation(String hostName) {
return ANY.equals(hostName);
}
/**
* Get the <code>Priority</code> of the request.
* @return <code>Priority</code> of the request
*/
@Public
@Stable
public abstract Priority getPriority();
/**
* Set the <code>Priority</code> of the request
* @param priority <code>Priority</code> of the request
*/
@Public
@Stable
public abstract void setPriority(Priority priority);
/**
* Get the resource (e.g. <em>host/rack</em>) on which the allocation
* is desired.
*
* A special value of <em>*</em> signifies that <em>any</em> resource
* (host/rack) is acceptable.
*
* @return resource (e.g. <em>host/rack</em>) on which the allocation
* is desired
*/
@Public
@Stable
public abstract String getResourceName();
/**
* Set the resource name (e.g. <em>host/rack</em>) on which the allocation
* is desired.
*
* A special value of <em>*</em> signifies that <em>any</em> resource name
* (e.g. host/rack) is acceptable.
*
* @param resourceName (e.g. <em>host/rack</em>) on which the
* allocation is desired
*/
@Public
@Stable
public abstract void setResourceName(String resourceName);
/**
* Get the <code>Resource</code> capability of the request.
* @return <code>Resource</code> capability of the request
*/
@Public
@Stable
public abstract Resource getCapability();
/**
* Set the <code>Resource</code> capability of the request
* @param capability <code>Resource</code> capability of the request
*/
@Public
@Stable
public abstract void setCapability(Resource capability);
/**
* Get the number of containers required with the given specifications.
* @return number of containers required with the given specifications
*/
@Public
@Stable
public abstract int getNumContainers();
/**
* Set the number of containers required with the given specifications
* @param numContainers number of containers required with the given
* specifications
*/
@Public
@Stable
public abstract void setNumContainers(int numContainers);
/**
* Get whether locality relaxation is enabled with this
* <code>ResourceRequest</code>. Defaults to true.
*
* @return whether locality relaxation is enabled with this
* <code>ResourceRequest</code>.
*/
@Public
@Stable
public abstract boolean getRelaxLocality();
/**
* <p>For a request at a network hierarchy level, set whether locality can be relaxed
* to that level and beyond.<p>
*
* <p>If the flag is off on a rack-level <code>ResourceRequest</code>,
* containers at that request's priority will not be assigned to nodes on that
* request's rack unless requests specifically for those nodes have also been
* submitted.<p>
*
* <p>If the flag is off on an {@link ResourceRequest#ANY}-level
* <code>ResourceRequest</code>, containers at that request's priority will
* only be assigned on racks for which specific requests have also been
* submitted.<p>
*
* <p>For example, to request a container strictly on a specific node, the
* corresponding rack-level and any-level requests should have locality
* relaxation set to false. Similarly, to request a container strictly on a
* specific rack, the corresponding any-level request should have locality
* relaxation set to false.<p>
*
* @param relaxLocality whether locality relaxation is enabled with this
* <code>ResourceRequest</code>.
*/
@Public
@Stable
public abstract void setRelaxLocality(boolean relaxLocality);
/**
* Get node-label-expression for this Resource Request. If this is set, all
* containers allocated to satisfy this resource-request will be only on those
* nodes that satisfy this node-label-expression.
*
* Please note that node label expression now can only take effect when the
* resource request has resourceName = ANY
*
* @return node-label-expression
*/
@Public
@Evolving
public abstract String getNodeLabelExpression();
/**
* Set node label expression of this resource request. Now only support
* specifying a single node label. In the future we will support more complex
* node label expression specification like AND(&&), OR(||), etc.
*
* Any please note that node label expression now can only take effect when
* the resource request has resourceName = ANY
*
* @param nodelabelExpression
* node-label-expression of this ResourceRequest
*/
@Public
@Evolving
public abstract void setNodeLabelExpression(String nodelabelExpression);
@Override
public int hashCode() {
final int prime = 2153;
int result = 2459;
Resource capability = getCapability();
String hostName = getResourceName();
Priority priority = getPriority();
result =
prime * result + ((capability == null) ? 0 : capability.hashCode());
result = prime * result + ((hostName == null) ? 0 : hostName.hashCode());
result = prime * result + getNumContainers();
result = prime * result + ((priority == null) ? 0 : priority.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResourceRequest other = (ResourceRequest) obj;
Resource capability = getCapability();
if (capability == null) {
if (other.getCapability() != null)
return false;
} else if (!capability.equals(other.getCapability()))
return false;
String hostName = getResourceName();
if (hostName == null) {
if (other.getResourceName() != null)
return false;
} else if (!hostName.equals(other.getResourceName()))
return false;
if (getNumContainers() != other.getNumContainers())
return false;
Priority priority = getPriority();
if (priority == null) {
if (other.getPriority() != null)
return false;
} else if (!priority.equals(other.getPriority()))
return false;
if (getNodeLabelExpression() == null) {
if (other.getNodeLabelExpression() != null) {
return false;
}
} else {
// do normalize on label expression before compare
String label1 = getNodeLabelExpression().replaceAll("[\\t ]", "");
String label2 =
other.getNodeLabelExpression() == null ? null : other
.getNodeLabelExpression().replaceAll("[\\t ]", "");
if (!label1.equals(label2)) {
return false;
}
}
return true;
}
@Override
public int compareTo(ResourceRequest other) {
int priorityComparison = this.getPriority().compareTo(other.getPriority());
if (priorityComparison == 0) {
int hostNameComparison =
this.getResourceName().compareTo(other.getResourceName());
if (hostNameComparison == 0) {
int capabilityComparison =
this.getCapability().compareTo(other.getCapability());
if (capabilityComparison == 0) {
return this.getNumContainers() - other.getNumContainers();
} else {
return capabilityComparison;
}
} else {
return hostNameComparison;
}
} else {
return priorityComparison;
}
}
}
| apache-2.0 |
fnp/pylucene | lucene-java-3.5.0/lucene/contrib/analyzers/common/src/java/org/apache/lucene/analysis/fa/PersianCharFilter.java | 1528 | package org.apache.lucene.analysis.fa;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import org.apache.lucene.analysis.CharStream;
import org.apache.lucene.analysis.CharFilter;
/**
* CharFilter that replaces instances of Zero-width non-joiner with an
* ordinary space.
*/
public class PersianCharFilter extends CharFilter {
public PersianCharFilter(CharStream in) {
super(in);
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
final int charsRead = super.read(cbuf, off, len);
if (charsRead > 0) {
final int end = off + charsRead;
while (off < end) {
if (cbuf[off] == '\u200C')
cbuf[off] = ' ';
off++;
}
}
return charsRead;
}
}
| apache-2.0 |