file_id
int64 1
215k
| content
stringlengths 7
454k
| repo
stringlengths 6
113
| path
stringlengths 6
251
|
---|---|---|---|
2,786 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
PdeKeywords - handles text coloring and links to html reference
Part of the Processing project - http://processing.org
Copyright (c) 2004-06 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app.syntax;
import org.apache.commons.compress.utils.IOUtils;
import org.fife.ui.rsyntaxtextarea.TokenMap;
import org.fife.ui.rsyntaxtextarea.TokenTypes;
import processing.app.Base;
import processing.app.BaseNoGui;
import processing.app.packages.UserLibrary;
import processing.app.debug.TargetPlatform;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
public class PdeKeywords {
private static final Map<String, Integer> KNOWN_TOKEN_TYPES = new HashMap<>();
private static final Pattern ALPHA = Pattern.compile("\\w");
static {
KNOWN_TOKEN_TYPES.put("RESERVED_WORD", TokenTypes.RESERVED_WORD);
KNOWN_TOKEN_TYPES.put("RESERVED_WORD_2", TokenTypes.RESERVED_WORD_2);
KNOWN_TOKEN_TYPES.put("VARIABLE", TokenTypes.VARIABLE);
KNOWN_TOKEN_TYPES.put("OPERATOR", TokenTypes.OPERATOR);
KNOWN_TOKEN_TYPES.put("DATA_TYPE", TokenTypes.DATA_TYPE);
KNOWN_TOKEN_TYPES.put("LITERAL_BOOLEAN", TokenTypes.LITERAL_BOOLEAN);
KNOWN_TOKEN_TYPES.put("LITERAL_CHAR", TokenTypes.LITERAL_CHAR);
KNOWN_TOKEN_TYPES.put("PREPROCESSOR", TokenTypes.PREPROCESSOR);
}
// lookup table for the TokenMarker subclass, handles coloring
private final TokenMap keywordTokenType;
private final Map<String, String> keywordOldToken;
private final Map<String, String> keywordTokenTypeAsString;
// lookup table that maps keywords to their html reference pages
private final Map<String, String> keywordToReference;
public PdeKeywords() {
this.keywordTokenType = new TokenMap();
this.keywordOldToken = new HashMap<>();
this.keywordTokenTypeAsString = new HashMap<>();
this.keywordToReference = new HashMap<>();
}
/**
* Handles loading of keywords file.
* <p/>
* Uses getKeywords() method because that's part of the
* TokenMarker classes.
* <p/>
* It is recommended that a # sign be used for comments
* inside keywords.txt.
*/
public void reload() {
try {
parseKeywordsTxt(new File(BaseNoGui.getContentFile("lib"), "keywords.txt"));
TargetPlatform tp = BaseNoGui.getTargetPlatform();
if (tp != null) {
File platformKeywords = new File(tp.getFolder(), "keywords.txt");
if (platformKeywords.exists()) parseKeywordsTxt(platformKeywords);
}
for (UserLibrary lib : BaseNoGui.librariesIndexer.getInstalledLibraries()) {
File keywords = new File(lib.getInstalledFolder(), "keywords.txt");
if (keywords.exists()) {
parseKeywordsTxt(keywords);
}
}
} catch (Exception e) {
Base.showError("Problem loading keywords", "Could not load keywords.txt,\nplease re-install Arduino.", e);
System.exit(1);
}
}
private void parseKeywordsTxt(File input) throws Exception {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
String line;
while ((line = reader.readLine()) != null) {
//System.out.println("line is " + line);
// in case there's any garbage on the line
line = line.trim();
if (line.length() == 0 || line.startsWith("#")) {
continue;
}
String pieces[] = line.split("\t");
String keyword = pieces[0].trim();
if (keyword.startsWith("\\#")) {
keyword = keyword.replace("\\#", "#");
}
if (pieces.length >= 2) {
keywordOldToken.put(keyword, pieces[1]);
}
if (pieces.length >= 3) {
parseHTMLReferenceFileName(pieces[2], keyword);
}
if (pieces.length >= 4) {
parseRSyntaxTextAreaTokenType(pieces[3], keyword);
}
}
fillMissingTokenType();
} finally {
IOUtils.closeQuietly(reader);
}
}
private void fillMissingTokenType() {
for (Map.Entry<String, String> oldTokenEntry : keywordOldToken.entrySet()) {
String keyword = oldTokenEntry.getKey();
if (!keywordTokenTypeAsString.containsKey(keyword)) {
if ("KEYWORD1".equals(oldTokenEntry.getValue())) {
parseRSyntaxTextAreaTokenType("DATA_TYPE", keyword);
}
else if ("LITERAL1".equals(oldTokenEntry.getValue())) {
parseRSyntaxTextAreaTokenType("RESERVED_WORD_2", keyword);
}
else {
parseRSyntaxTextAreaTokenType("FUNCTION", keyword);
}
}
}
}
private void parseRSyntaxTextAreaTokenType(String tokenTypeAsString, String keyword) {
if (!ALPHA.matcher(keyword).find()) {
return;
}
if (KNOWN_TOKEN_TYPES.containsKey(tokenTypeAsString)) {
keywordTokenType.put(keyword, KNOWN_TOKEN_TYPES.get(tokenTypeAsString));
keywordTokenTypeAsString.put(keyword, tokenTypeAsString);
} else {
keywordTokenType.put(keyword, TokenTypes.FUNCTION);
keywordTokenTypeAsString.put(keyword, "FUNCTION");
}
}
private void parseHTMLReferenceFileName(String piece, String keyword) {
String htmlFilename = piece.trim();
if (htmlFilename.length() > 0) {
keywordToReference.put(keyword, htmlFilename);
}
}
public String getReference(String keyword) {
return keywordToReference.get(keyword);
}
public String getTokenTypeAsString(String keyword) {
return keywordTokenTypeAsString.get(keyword);
}
public int getTokenType(char[] array, int start, int end) {
return keywordTokenType.get(array, start, end);
}
}
| roboard/86Duino | app/src/processing/app/syntax/PdeKeywords.java |
2,787 | /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Tool - interface implementation for the Processing tools menu
Part of the Processing project - http://processing.org
Copyright (c) 2008 Ben Fry and Casey Reas
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app.tools;
import processing.app.Editor;
/**
* Interface for items to be shown in the Tools menu.
*/
public interface Tool extends Runnable {
void init(Editor editor);
void run();
String getMenuTitle();
}
| roboard/86Duino | app/src/processing/app/tools/Tool.java |
2,788 | /**
* Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
* This source code is licensed under both the GPLv2 (found in the
* COPYING file in the root directory) and Apache 2.0 License
* (found in the LICENSE.Apache file in the root directory).
*/
package org.rocksdb.jmh;
import org.openjdk.jmh.annotations.*;
import org.rocksdb.*;
import org.rocksdb.util.FileUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.rocksdb.util.KVUtils.ba;
import static org.rocksdb.util.KVUtils.keys;
@State(Scope.Benchmark)
public class MultiGetBenchmarks {
@Param({
"no_column_family",
"1_column_family",
"20_column_families",
"100_column_families"
})
String columnFamilyTestType;
@Param("100000")
int keyCount;
@Param({
"10",
"100",
"1000",
"10000",
})
int multiGetSize;
Path dbDir;
DBOptions options;
int cfs = 0; // number of column families
private AtomicInteger cfHandlesIdx;
ColumnFamilyHandle[] cfHandles;
RocksDB db;
private final AtomicInteger keyIndex = new AtomicInteger();
@Setup(Level.Trial)
public void setup() throws IOException, RocksDBException {
RocksDB.loadLibrary();
dbDir = Files.createTempDirectory("rocksjava-multiget-benchmarks");
options = new DBOptions()
.setCreateIfMissing(true)
.setCreateMissingColumnFamilies(true);
final List<ColumnFamilyDescriptor> cfDescriptors = new ArrayList<>();
cfDescriptors.add(new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY));
if ("1_column_family".equals(columnFamilyTestType)) {
cfs = 1;
} else if ("20_column_families".equals(columnFamilyTestType)) {
cfs = 20;
} else if ("100_column_families".equals(columnFamilyTestType)) {
cfs = 100;
}
if (cfs > 0) {
cfHandlesIdx = new AtomicInteger(1);
for (int i = 1; i <= cfs; i++) {
cfDescriptors.add(new ColumnFamilyDescriptor(ba("cf" + i)));
}
}
final List<ColumnFamilyHandle> cfHandlesList = new ArrayList<>(cfDescriptors.size());
db = RocksDB.open(options, dbDir.toAbsolutePath().toString(), cfDescriptors, cfHandlesList);
cfHandles = cfHandlesList.toArray(new ColumnFamilyHandle[0]);
// store initial data for retrieving via get
for (int i = 0; i < cfs; i++) {
for (int j = 0; j < keyCount; j++) {
db.put(cfHandles[i], ba("key" + j), ba("value" + j));
}
}
try (final FlushOptions flushOptions = new FlushOptions()
.setWaitForFlush(true)) {
db.flush(flushOptions);
}
}
@TearDown(Level.Trial)
public void cleanup() throws IOException {
for (final ColumnFamilyHandle cfHandle : cfHandles) {
cfHandle.close();
}
db.close();
options.close();
FileUtils.delete(dbDir);
}
private ColumnFamilyHandle getColumnFamily() {
if (cfs == 0) {
return cfHandles[0];
} else if (cfs == 1) {
return cfHandles[1];
} else {
int idx = cfHandlesIdx.getAndIncrement();
if (idx > cfs) {
cfHandlesIdx.set(1); // doesn't ensure a perfect distribution, but it's ok
idx = 0;
}
return cfHandles[idx];
}
}
/**
* Reserves the next {@inc} positions in the index.
*
* @param inc the number by which to increment the index
* @param limit the limit for the index
* @return the index before {@code inc} is added
*/
private int next(final int inc, final int limit) {
int idx;
int nextIdx;
while (true) {
idx = keyIndex.get();
nextIdx = idx + inc;
if (nextIdx >= limit) {
nextIdx = inc;
}
if (keyIndex.compareAndSet(idx, nextIdx)) {
break;
}
}
if (nextIdx >= limit) {
return -1;
} else {
return idx;
}
}
@Benchmark
public List<byte[]> multiGet10() throws RocksDBException {
final int fromKeyIdx = next(multiGetSize, keyCount);
final List<byte[]> keys = keys(fromKeyIdx, fromKeyIdx + multiGetSize);
return db.multiGetAsList(keys);
}
}
| facebook/rocksdb | java/jmh/src/main/java/org/rocksdb/jmh/MultiGetBenchmarks.java |
2,789 | /*
* 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.jasper.compiler;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jakarta.el.MethodExpression;
import jakarta.el.ValueExpression;
import jakarta.servlet.jsp.tagext.TagAttributeInfo;
import jakarta.servlet.jsp.tagext.TagInfo;
import jakarta.servlet.jsp.tagext.TagVariableInfo;
import jakarta.servlet.jsp.tagext.VariableInfo;
import org.apache.jasper.JasperException;
import org.apache.jasper.JspCompilationContext;
import org.apache.jasper.TrimSpacesOption;
import org.apache.jasper.compiler.Node.ChildInfoBase;
import org.apache.jasper.compiler.Node.NamedAttribute;
import org.apache.jasper.runtime.JspRuntimeLibrary;
import org.xml.sax.Attributes;
/**
* Generate Java source from Nodes
*
* @author Anil K. Vijendran
* @author Danno Ferrin
* @author Mandar Raje
* @author Rajiv Mordani
* @author Pierre Delisle
*
* Tomcat 4.1.x and Tomcat 5:
* @author Kin-man Chung
* @author Jan Luehe
* @author Shawn Bayern
* @author Mark Roth
* @author Denis Benoit
*
* Tomcat 6.x
* @author Jacob Hookom
* @author Remy Maucherat
*/
class Generator {
private static final Class<?>[] OBJECT_CLASS = { Object.class };
private static final Pattern PRE_TAG_PATTERN = Pattern.compile("(?s).*(<pre>|</pre>).*");
private static final Pattern BLANK_LINE_PATTERN = Pattern.compile("(\\s*(\\n|\\r)+\\s*)");
private final ServletWriter out;
private final ArrayList<GenBuffer> methodsBuffered;
private final FragmentHelperClass fragmentHelperClass;
private final ErrorDispatcher err;
private final BeanRepository beanInfo;
private final Set<String> varInfoNames;
private final JspCompilationContext ctxt;
private final boolean isPoolingEnabled;
private final boolean breakAtLF;
private String jspIdPrefix;
private int jspId;
private final PageInfo pageInfo;
private final List<String> tagHandlerPoolNames;
private GenBuffer charArrayBuffer;
private final DateFormat timestampFormat;
private final ELInterpreter elInterpreter;
private final StringInterpreter stringInterpreter;
/**
* @param s
* the input string
* @return quoted and escaped string, per Java rule
*/
static String quote(String s) {
if (s == null) {
return "null";
}
return '"' + escape(s) + '"';
}
/**
* @param s the input string - must not be {@code null}
*
* @return escaped string, per Java rule
*/
static String escape(String s) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '"') {
b.append('\\').append('"');
} else if (c == '\\') {
b.append('\\').append('\\');
} else if (c == '\n') {
b.append('\\').append('n');
} else if (c == '\r') {
b.append('\\').append('r');
} else {
b.append(c);
}
}
return b.toString();
}
/**
* Single quote and escape a character
*/
static String quote(char c) {
StringBuilder b = new StringBuilder();
b.append('\'');
if (c == '\'') {
b.append('\\').append('\'');
} else if (c == '\\') {
b.append('\\').append('\\');
} else if (c == '\n') {
b.append('\\').append('n');
} else if (c == '\r') {
b.append('\\').append('r');
} else {
b.append(c);
}
b.append('\'');
return b.toString();
}
private String createJspId() {
if (this.jspIdPrefix == null) {
StringBuilder sb = new StringBuilder(32);
String name = ctxt.getServletJavaFileName();
sb.append("jsp_");
// Cast to long to avoid issue with Integer.MIN_VALUE
sb.append(Math.abs((long) name.hashCode()));
sb.append('_');
this.jspIdPrefix = sb.toString();
}
return this.jspIdPrefix + (this.jspId++);
}
/**
* Generates declarations. This includes "info" of the page directive, and
* scriptlet declarations.
*/
private void generateDeclarations(Node.Nodes page) throws JasperException {
class DeclarationVisitor extends Node.Visitor {
private boolean getServletInfoGenerated = false;
/*
* Generates getServletInfo() method that returns the value of the
* page directive's 'info' attribute, if present.
*
* The Validator has already ensured that if the translation unit
* contains more than one page directive with an 'info' attribute,
* their values match.
*/
@Override
public void visit(Node.PageDirective n) throws JasperException {
if (getServletInfoGenerated) {
return;
}
String info = n.getAttributeValue("info");
if (info == null) {
return;
}
getServletInfoGenerated = true;
out.printil("public java.lang.String getServletInfo() {");
out.pushIndent();
out.printin("return ");
out.print(quote(info));
out.println(";");
out.popIndent();
out.printil("}");
out.println();
}
@Override
public void visit(Node.Declaration n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
out.printMultiLn(n.getText());
out.println();
n.setEndJavaLine(out.getJavaLine());
}
// Custom Tags may contain declarations from tag plugins.
@Override
public void visit(Node.CustomTag n) throws JasperException {
if (n.useTagPlugin()) {
// If a custom tag is configured to use a plug-in
// getAtSTag() and getAtETag() will always be non-null
n.getAtSTag().visit(this);
visitBody(n);
n.getAtETag().visit(this);
} else {
visitBody(n);
}
}
}
out.println();
page.visit(new DeclarationVisitor());
}
/**
* Compiles list of tag handler pool names.
*/
private void compileTagHandlerPoolList(Node.Nodes page)
throws JasperException {
class TagHandlerPoolVisitor extends Node.Visitor {
private final List<String> names;
/*
* Constructor
*
* @param v Vector of tag handler pool names to populate
*/
TagHandlerPoolVisitor(List<String> v) {
names = v;
}
/*
* Gets the name of the tag handler pool for the given custom tag
* and adds it to the list of tag handler pool names unless it is
* already contained in it.
*/
@Override
public void visit(Node.CustomTag n) throws JasperException {
if (!n.implementsSimpleTag()) {
String name = createTagHandlerPoolName(n.getPrefix(), n
.getLocalName(), n.getAttributes(),
n.getNamedAttributeNodes(), n.hasEmptyBody());
n.setTagHandlerPoolName(name);
if (!names.contains(name)) {
names.add(name);
}
}
visitBody(n);
}
/*
* Creates the name of the tag handler pool whose tag handlers may
* be (re)used to service this action.
*
* @return The name of the tag handler pool
*/
private String createTagHandlerPoolName(String prefix,
String shortName, Attributes attrs, Node.Nodes namedAttrs,
boolean hasEmptyBody) {
StringBuilder poolName = new StringBuilder(64);
poolName.append("_jspx_tagPool_").append(prefix).append('_')
.append(shortName);
if (attrs != null) {
String[] attrNames =
new String[attrs.getLength() + namedAttrs.size()];
for (int i = 0; i < attrNames.length; i++) {
attrNames[i] = attrs.getQName(i);
}
for (int i = 0; i < namedAttrs.size(); i++) {
attrNames[attrs.getLength() + i] =
namedAttrs.getNode(i).getQName();
}
Arrays.sort(attrNames, Collections.reverseOrder());
if (attrNames.length > 0) {
poolName.append('&');
}
for (String attrName : attrNames) {
poolName.append('_');
poolName.append(attrName);
}
}
if (hasEmptyBody) {
poolName.append("_nobody");
}
return JspUtil.makeJavaIdentifier(poolName.toString());
}
}
page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames));
}
private void declareTemporaryScriptingVars(Node.Nodes page)
throws JasperException {
class ScriptingVarVisitor extends Node.Visitor {
private final List<String> vars;
ScriptingVarVisitor() {
vars = new ArrayList<>();
}
@Override
public void visit(Node.CustomTag n) throws JasperException {
// XXX - Actually there is no need to declare those
// "_jspx_" + varName + "_" + nestingLevel variables when we are
// inside a JspFragment.
if (n.getCustomNestingLevel() > 0) {
TagVariableInfo[] tagVarInfos = n.getTagVariableInfos();
VariableInfo[] varInfos = n.getVariableInfos();
if (varInfos.length > 0) {
for (VariableInfo varInfo : varInfos) {
String varName = varInfo.getVarName();
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
if (!vars.contains(tmpVarName)) {
vars.add(tmpVarName);
out.printin(varInfo.getClassName());
out.print(" ");
out.print(tmpVarName);
out.print(" = ");
out.print(null);
out.println(";");
}
}
} else {
for (TagVariableInfo tagVarInfo : tagVarInfos) {
String varName = tagVarInfo.getNameGiven();
if (varName == null) {
varName = n.getTagData().getAttributeString(
tagVarInfo.getNameFromAttribute());
}
else if (tagVarInfo.getNameFromAttribute() != null) {
// alias
continue;
}
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
if (!vars.contains(tmpVarName)) {
vars.add(tmpVarName);
out.printin(tagVarInfo.getClassName());
out.print(" ");
out.print(tmpVarName);
out.print(" = ");
out.print(null);
out.println(";");
}
}
}
}
visitBody(n);
}
}
page.visit(new ScriptingVarVisitor());
}
/*
* Generates getters for
* - instance manager
* - expression factory
*
* For JSPs these methods use lazy init. This is not an option for tag files
* (at least it would be more complicated to generate) because the
* ServletConfig is not readily available.
*/
private void generateGetters() {
out.printil("public jakarta.el.ExpressionFactory _jsp_getExpressionFactory() {");
out.pushIndent();
if (!ctxt.isTagFile()) {
out.printin("if (");
out.print(ctxt.getOptions().getVariableForExpressionFactory());
out.println(" == null) {");
out.pushIndent();
out.printil("synchronized (this) {");
out.pushIndent();
out.printin("if (");
out.print(ctxt.getOptions().getVariableForExpressionFactory());
out.println(" == null) {");
out.pushIndent();
out.printin(ctxt.getOptions().getVariableForExpressionFactory());
out.println(" = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("}");
}
out.printin("return ");
out.print(ctxt.getOptions().getVariableForExpressionFactory());
out.println(";");
out.popIndent();
out.printil("}");
out.println();
out.printil("public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {");
out.pushIndent();
if (!ctxt.isTagFile()) {
out.printin("if (");
out.print(ctxt.getOptions().getVariableForInstanceManager());
out.println(" == null) {");
out.pushIndent();
out.printil("synchronized (this) {");
out.pushIndent();
out.printin("if (");
out.print(ctxt.getOptions().getVariableForInstanceManager());
out.println(" == null) {");
out.pushIndent();
out.printin(ctxt.getOptions().getVariableForInstanceManager());
out.println(" = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("}");
}
out.printin("return ");
out.print(ctxt.getOptions().getVariableForInstanceManager());
out.println(";");
out.popIndent();
out.printil("}");
out.println();
}
/**
* Generates the _jspInit() method for instantiating the tag handler pools.
* For tag file, _jspInit has to be invoked manually, and the ServletConfig
* object explicitly passed.
*
* In JSP 2.1, we also instantiate an ExpressionFactory
*/
private void generateInit() {
if (ctxt.isTagFile()) {
out.printil("private void _jspInit(jakarta.servlet.ServletConfig config) {");
} else {
out.printil("public void _jspInit() {");
}
out.pushIndent();
if (isPoolingEnabled) {
for (int i = 0; i < tagHandlerPoolNames.size(); i++) {
out.printin(tagHandlerPoolNames.get(i));
out.print(" = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(");
if (ctxt.isTagFile()) {
out.print("config");
} else {
out.print("getServletConfig()");
}
out.println(");");
}
}
// Tag files can't (easily) use lazy init for these so initialise them
// here.
if (ctxt.isTagFile()) {
out.printin(ctxt.getOptions().getVariableForExpressionFactory());
out.println(" = _jspxFactory.getJspApplicationContext(config.getServletContext()).getExpressionFactory();");
out.printin(ctxt.getOptions().getVariableForInstanceManager());
out.println(" = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(config);");
}
out.popIndent();
out.printil("}");
out.println();
}
/**
* Generates the _jspDestroy() method which is responsible for calling the
* release() method on every tag handler in any of the tag handler pools.
*/
private void generateDestroy() {
out.printil("public void _jspDestroy() {");
out.pushIndent();
if (isPoolingEnabled) {
for (int i = 0; i < tagHandlerPoolNames.size(); i++) {
out.printin(tagHandlerPoolNames.get(i));
out.println(".release();");
}
}
out.popIndent();
out.printil("}");
out.println();
}
/**
* Generate preamble package name (shared by servlet and tag handler
* preamble generation). Package is always non-null as neither Servlets nor
* tags can use a default package.
*/
private void genPreamblePackage(String packageName) {
out.printil("package " + packageName + ";");
out.println();
}
/**
* Generate preamble imports (shared by servlet and tag handler preamble
* generation)
*/
private void genPreambleImports() {
for (String i : pageInfo.getImports()) {
out.printin("import ");
out.print(i);
out.println(";");
}
out.println();
}
/**
* Generation of static initializers in preamble. For example, dependent
* list, el function map, prefix map. (shared by servlet and tag handler
* preamble generation)
*/
private void genPreambleStaticInitializers() {
out.printil("private static final jakarta.servlet.jsp.JspFactory _jspxFactory =");
out.printil(" jakarta.servlet.jsp.JspFactory.getDefaultFactory();");
out.println();
// Static data for getDependants()
out.printil("private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;");
out.println();
Map<String,Long> dependants = pageInfo.getDependants();
if (!dependants.isEmpty()) {
out.printil("static {");
out.pushIndent();
out.printin("_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(");
out.print("" + dependants.size());
out.println(");");
for (Entry<String, Long> entry : dependants.entrySet()) {
out.printin("_jspx_dependants.put(\"");
out.print(entry.getKey());
out.print("\", Long.valueOf(");
out.print(entry.getValue().toString());
out.println("L));");
}
out.popIndent();
out.printil("}");
out.println();
}
// Static data for getImports()
List<String> imports = pageInfo.getImports();
Set<String> packages = new HashSet<>();
Set<String> classes = new HashSet<>();
for (String importName : imports) {
String trimmed = importName.trim();
if (trimmed.endsWith(".*")) {
packages.add(trimmed.substring(0, trimmed.length() - 2));
} else {
classes.add(trimmed);
}
}
out.printil("private static final java.util.Set<java.lang.String> _jspx_imports_packages;");
out.println();
out.printil("private static final java.util.Set<java.lang.String> _jspx_imports_classes;");
out.println();
out.printil("static {");
out.pushIndent();
// Packages is never empty because o.a.j.Constants.STANDARD_IMPORTS
// contains 3 packages and is always added to the imports.
out.printin("_jspx_imports_packages = new java.util.LinkedHashSet<>(");
out.print(Integer.toString(packages.size()));
out.print(");");
out.println();
for (String packageName : packages) {
out.printin("_jspx_imports_packages.add(\"");
out.print(packageName);
out.println("\");");
}
// classes however, may be empty depending on the import declarations
if (classes.size() == 0) {
out.printin("_jspx_imports_classes = null;");
out.println();
} else {
out.printin("_jspx_imports_classes = new java.util.LinkedHashSet<>(");
out.print(Integer.toString(classes.size()));
out.print(");");
out.println();
for (String className : classes) {
out.printin("_jspx_imports_classes.add(\"");
out.print(className);
out.println("\");");
}
}
out.popIndent();
out.printil("}");
out.println();
}
/**
* Declare tag handler pools (tags of the same type and with the same
* attribute set share the same tag handler pool) (shared by servlet and tag
* handler preamble generation)
*
* In JSP 2.1, we also scope an instance of ExpressionFactory
*/
private void genPreambleClassVariableDeclarations() {
if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) {
for (int i = 0; i < tagHandlerPoolNames.size(); i++) {
out.printil("private org.apache.jasper.runtime.TagHandlerPool " + tagHandlerPoolNames.get(i) + ";");
}
out.println();
}
out.printin("private volatile jakarta.el.ExpressionFactory ");
out.print(ctxt.getOptions().getVariableForExpressionFactory());
out.println(";");
out.printin("private volatile org.apache.tomcat.InstanceManager ");
out.print(ctxt.getOptions().getVariableForInstanceManager());
out.println(";");
out.println();
}
/**
* Declare general-purpose methods (shared by servlet and tag handler
* preamble generation)
*/
private void genPreambleMethods() {
// Implement JspSourceDependent
out.printil("public java.util.Map<java.lang.String,java.lang.Long> getDependants() {");
out.pushIndent();
out.printil("return _jspx_dependants;");
out.popIndent();
out.printil("}");
out.println();
// Implement JspSourceImports
out.printil("public java.util.Set<java.lang.String> getPackageImports() {");
out.pushIndent();
out.printil("return _jspx_imports_packages;");
out.popIndent();
out.printil("}");
out.println();
out.printil("public java.util.Set<java.lang.String> getClassImports() {");
out.pushIndent();
out.printil("return _jspx_imports_classes;");
out.popIndent();
out.printil("}");
out.println();
// Implement JspSourceDirectives
out.printil("public boolean getErrorOnELNotFound() {");
out.pushIndent();
if (pageInfo.isErrorOnELNotFound()) {
out.printil("return true;");
} else {
out.printil("return false;");
}
out.popIndent();
out.printil("}");
out.println();
generateGetters();
generateInit();
generateDestroy();
}
/**
* Generates the beginning of the static portion of the servlet.
*/
private void generatePreamble(Node.Nodes page) throws JasperException {
String servletPackageName = ctxt.getServletPackageName();
String servletClassName = ctxt.getServletClassName();
String serviceMethodName = ctxt.getOptions().getServiceMethodName();
// First the package name:
genPreamblePackage(servletPackageName);
// Generate imports
genPreambleImports();
// Generate class declaration
out.printin("public final class ");
out.print(servletClassName);
out.print(" extends ");
out.println(pageInfo.getExtends());
out.printin(" implements org.apache.jasper.runtime.JspSourceDependent,");
out.println();
out.printin(" org.apache.jasper.runtime.JspSourceImports");
out.println(",");
out.printin(" org.apache.jasper.runtime.JspSourceDirectives");
out.println(" {");
out.pushIndent();
// Class body begins here
generateDeclarations(page);
// Static initializations here
genPreambleStaticInitializers();
// Class variable declarations
genPreambleClassVariableDeclarations();
// Methods here
genPreambleMethods();
// Now the service method
out.printin("public void ");
out.print(serviceMethodName);
out.println("(final jakarta.servlet.http.HttpServletRequest request, final jakarta.servlet.http.HttpServletResponse response)");
out.pushIndent();
out.pushIndent();
out.printil("throws java.io.IOException, jakarta.servlet.ServletException {");
out.popIndent();
out.println();
// Method check
if (!pageInfo.isErrorPage()) {
out.printil("if (!jakarta.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {");
out.pushIndent();
out.printil("final java.lang.String _jspx_method = request.getMethod();");
out.printil("if (\"OPTIONS\".equals(_jspx_method)) {");
out.pushIndent();
out.printil("response.setHeader(\"Allow\",\"GET, HEAD, POST, OPTIONS\");");
out.printil("return;");
out.popIndent();
out.printil("}");
out.printil("if (!\"GET\".equals(_jspx_method) && !\"POST\".equals(_jspx_method) && !\"HEAD\".equals(_jspx_method)) {");
out.pushIndent();
out.printil("response.setHeader(\"Allow\",\"GET, HEAD, POST, OPTIONS\");");
out.printin("response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ");
out.println("\"" + Localizer.getMessage("jsp.error.servlet.invalid.method") + "\");");
out.printil("return;");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("}");
out.println();
}
// Local variable declarations
out.printil("final jakarta.servlet.jsp.PageContext pageContext;");
if (pageInfo.isSession()) {
out.printil("jakarta.servlet.http.HttpSession session = null;");
}
if (pageInfo.isErrorPage()) {
out.printil("java.lang.Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);");
out.printil("if (exception != null) {");
out.pushIndent();
out.printil("response.setStatus(jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);");
out.popIndent();
out.printil("}");
}
out.printil("final jakarta.servlet.ServletContext application;");
out.printil("final jakarta.servlet.ServletConfig config;");
out.printil("jakarta.servlet.jsp.JspWriter out = null;");
out.printil("final java.lang.Object page = this;");
out.printil("jakarta.servlet.jsp.JspWriter _jspx_out = null;");
out.printil("jakarta.servlet.jsp.PageContext _jspx_page_context = null;");
out.println();
declareTemporaryScriptingVars(page);
out.println();
out.printil("try {");
out.pushIndent();
out.printin("response.setContentType(");
out.print(quote(pageInfo.getContentType()));
out.println(");");
if (ctxt.getOptions().isXpoweredBy()) {
out.printil("response.addHeader(\"X-Powered-By\", \"JSP/4.0\");");
}
out.printil("pageContext = _jspxFactory.getPageContext(this, request, response,");
out.printin("\t\t\t");
out.print(quote(pageInfo.getErrorPage()));
out.print(", " + pageInfo.isSession());
out.print(", " + pageInfo.getBuffer());
out.print(", " + pageInfo.isAutoFlush());
out.println(");");
out.printil("_jspx_page_context = pageContext;");
out.printil("application = pageContext.getServletContext();");
out.printil("config = pageContext.getServletConfig();");
if (pageInfo.isSession()) {
out.printil("session = pageContext.getSession();");
}
out.printil("out = pageContext.getOut();");
out.printil("_jspx_out = out;");
out.println();
}
/**
* Generates an XML Prolog, which includes an XML declaration and an XML
* doctype declaration.
*/
private void generateXmlProlog(Node.Nodes page) {
/*
* An XML declaration is generated under the following conditions: -
* 'omit-xml-declaration' attribute of <jsp:output> action is set to
* "no" or "false" - JSP document without a <jsp:root>
*/
String omitXmlDecl = pageInfo.getOmitXmlDecl();
if ((omitXmlDecl != null && !JspUtil.booleanValue(omitXmlDecl)) ||
(omitXmlDecl == null && page.getRoot().isXmlSyntax() && !pageInfo.hasJspRoot() && !ctxt.isTagFile())) {
String cType = pageInfo.getContentType();
String charSet = cType.substring(cType.indexOf("charset=") + 8);
out.printil("out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\""
+ charSet + "\\\"?>\\n\");");
}
/*
* Output a DOCTYPE declaration if the doctype-root-element appears. If
* doctype-public appears: <!DOCTYPE name PUBLIC "doctypePublic"
* "doctypeSystem"> else <!DOCTYPE name SYSTEM "doctypeSystem" >
*/
String doctypeName = pageInfo.getDoctypeName();
if (doctypeName != null) {
String doctypePublic = pageInfo.getDoctypePublic();
String doctypeSystem = pageInfo.getDoctypeSystem();
out.printin("out.write(\"<!DOCTYPE ");
out.print(doctypeName);
if (doctypePublic == null) {
out.print(" SYSTEM \\\"");
} else {
out.print(" PUBLIC \\\"");
out.print(doctypePublic);
out.print("\\\" \\\"");
}
out.print(doctypeSystem);
out.println("\\\">\\n\");");
}
}
/**
* A visitor that generates codes for the elements in the page.
*/
private class GenerateVisitor extends Node.Visitor {
/*
* Map containing introspection information on tag handlers:
* <key>: tag prefix <value>: Map containing introspection on tag
* handlers: <key>: tag short name <value>: introspection info of tag
* handler for <prefix:shortName> tag
*/
private final Map<String,Map<String,TagHandlerInfo>> handlerInfos;
private final Map<String,Integer> tagVarNumbers;
private String parent;
private boolean isSimpleTagParent; // Is parent a SimpleTag?
private String pushBodyCountVar;
private String simpleTagHandlerVar;
private boolean isSimpleTagHandler;
private boolean isFragment;
private final boolean isTagFile;
private ServletWriter out;
private final ArrayList<GenBuffer> methodsBuffered;
private final FragmentHelperClass fragmentHelperClass;
private int methodNesting;
private int charArrayCount;
private HashMap<String,String> textMap;
private final boolean useInstanceManagerForTags;
GenerateVisitor(boolean isTagFile, ServletWriter out,
ArrayList<GenBuffer> methodsBuffered,
FragmentHelperClass fragmentHelperClass,
boolean useInstanceManagerForTags) {
this.isTagFile = isTagFile;
this.out = out;
this.methodsBuffered = methodsBuffered;
this.fragmentHelperClass = fragmentHelperClass;
this.useInstanceManagerForTags = useInstanceManagerForTags;
methodNesting = 0;
handlerInfos = new HashMap<>();
tagVarNumbers = new HashMap<>();
textMap = new HashMap<>();
}
/**
* Returns an attribute value, optionally URL encoded. If the value is a
* runtime expression, the result is the expression itself, as a string.
* If the result is an EL expression, we insert a call to the
* interpreter. If the result is a Named Attribute we insert the
* generated variable name. Otherwise the result is a string literal,
* quoted and escaped.
*
* @param attr
* An JspAttribute object
* @param encode
* true if to be URL encoded
* @param expectedType
* the expected type for an EL evaluation (ignored for
* attributes that aren't EL expressions)
*/
private String attributeValue(Node.JspAttribute attr, boolean encode,
Class<?> expectedType) {
String v = attr.getValue();
if (attr.isExpression()) {
if (encode) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(String.valueOf("
+ v + "), request.getCharacterEncoding())";
}
return v;
} else if (attr.isELInterpreterInput()) {
v = elInterpreter.interpreterCall(ctxt, this.isTagFile, v,
expectedType, attr.getEL().getMapName());
if (encode) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("
+ v + ", request.getCharacterEncoding())";
}
return v;
} else if (attr.isNamedAttribute()) {
return attr.getNamedAttributeNode().getTemporaryVariableName();
} else {
if (encode) {
return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode("
+ quote(v) + ", request.getCharacterEncoding())";
}
return quote(v);
}
}
/**
* Prints the attribute value specified in the param action, in the form
* of name=value string.
*
* @param n
* the parent node for the param action nodes.
*/
private void printParams(Node n, String pageParam, boolean literal)
throws JasperException {
class ParamVisitor extends Node.Visitor {
private String separator;
ParamVisitor(String separator) {
this.separator = separator;
}
@Override
public void visit(Node.ParamAction n) throws JasperException {
out.print(" + ");
out.print(separator);
out.print(" + ");
out.print("org.apache.jasper.runtime.JspRuntimeLibrary."
+ "URLEncode(" + quote(n.getTextAttribute("name"))
+ ", request.getCharacterEncoding())");
out.print("+ \"=\" + ");
out.print(attributeValue(n.getValue(), true, String.class));
// The separator is '&' after the second use
separator = "\"&\"";
}
}
String sep;
if (literal) {
sep = pageParam.indexOf('?') > 0 ? "\"&\"" : "\"?\"";
} else {
sep = "((" + pageParam + ").indexOf('?')>0? '&': '?')";
}
if (n.getBody() != null) {
n.getBody().visit(new ParamVisitor(sep));
}
}
@Override
public void visit(Node.Expression n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
out.printin("out.print(");
out.printMultiLn(n.getText());
out.println(");");
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.Scriptlet n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
out.printMultiLn(n.getText());
out.println();
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.ELExpression n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
out.printil("out.write("
+ elInterpreter.interpreterCall(ctxt, this.isTagFile,
n.getType() + "{" + n.getText() + "}",
String.class, n.getEL().getMapName()) +
");");
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.IncludeAction n) throws JasperException {
String flush = n.getTextAttribute("flush");
Node.JspAttribute page = n.getPage();
boolean isFlush = "true".equals(flush);
n.setBeginJavaLine(out.getJavaLine());
String pageParam;
if (page.isNamedAttribute()) {
// If the page for jsp:include was specified via
// jsp:attribute, first generate code to evaluate
// that body.
pageParam = generateNamedAttributeValue(page
.getNamedAttributeNode());
} else {
pageParam = attributeValue(page, false, String.class);
}
// If any of the params have their values specified by
// jsp:attribute, prepare those values first.
Node jspBody = findJspBody(n);
if (jspBody != null) {
prepareParams(jspBody);
} else {
prepareParams(n);
}
out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "
+ pageParam);
printParams(n, pageParam, page.isLiteral());
out.println(", out, " + isFlush + ");");
n.setEndJavaLine(out.getJavaLine());
}
/**
* Scans through all child nodes of the given parent for <param>
* subelements. For each <param> element, if its value is specified via
* a Named Attribute (<jsp:attribute>), generate the code to evaluate
* those bodies first.
* <p>
* {@code parent} is assumed to be non-null
*/
private void prepareParams(Node parent) throws JasperException {
Node.Nodes subelements = parent.getBody();
if (subelements != null) {
for (int i = 0; i < subelements.size(); i++) {
Node n = subelements.getNode(i);
// Validation during parsing ensures n is an instance of
// Node.ParamAction
Node.Nodes paramSubElements = n.getBody();
for (int j = 0; (paramSubElements != null)
&& (j < paramSubElements.size()); j++) {
Node m = paramSubElements.getNode(j);
if (m instanceof Node.NamedAttribute) {
generateNamedAttributeValue((Node.NamedAttribute) m);
}
}
}
}
}
/**
* Finds the <jsp:body> subelement of the given parent node. If not
* found, null is returned.
*/
private Node.JspBody findJspBody(Node parent) {
Node.JspBody result = null;
Node.Nodes subelements = parent.getBody();
for (int i = 0; (subelements != null) && (i < subelements.size()); i++) {
Node n = subelements.getNode(i);
if (n instanceof Node.JspBody) {
result = (Node.JspBody) n;
break;
}
}
return result;
}
@Override
public void visit(Node.ForwardAction n) throws JasperException {
Node.JspAttribute page = n.getPage();
n.setBeginJavaLine(out.getJavaLine());
out.printil("if (true) {"); // So that javac won't complain about
out.pushIndent(); // codes after "return"
String pageParam;
if (page.isNamedAttribute()) {
// If the page for jsp:forward was specified via
// jsp:attribute, first generate code to evaluate
// that body.
pageParam = generateNamedAttributeValue(page.getNamedAttributeNode());
} else {
pageParam = attributeValue(page, false, String.class);
}
// If any of the params have their values specified by
// jsp:attribute, prepare those values first.
Node jspBody = findJspBody(n);
if (jspBody != null) {
prepareParams(jspBody);
} else {
prepareParams(n);
}
out.printin("_jspx_page_context.forward(");
out.print(pageParam);
printParams(n, pageParam, page.isLiteral());
out.println(");");
if (isTagFile || isFragment) {
out.printil("throw new jakarta.servlet.jsp.SkipPageException();");
} else {
out.printil((methodNesting > 0) ? "return true;" : "return;");
}
out.popIndent();
out.printil("}");
n.setEndJavaLine(out.getJavaLine());
// XXX Not sure if we can eliminate dead codes after this.
}
@Override
public void visit(Node.GetProperty n) throws JasperException {
String name = n.getTextAttribute("name");
String property = n.getTextAttribute("property");
n.setBeginJavaLine(out.getJavaLine());
if (beanInfo.checkVariable(name)) {
// Bean is defined using useBean, introspect at compile time
Class<?> bean = beanInfo.getBeanType(name);
String beanName = bean.getCanonicalName();
Method meth = JspRuntimeLibrary.getReadMethod(bean, property);
String methodName = meth.getName();
out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString("
+ "((("
+ beanName
+ ")_jspx_page_context.findAttribute("
+ "\""
+ name + "\"))." + methodName + "())));");
} else if (!ctxt.getOptions().getStrictGetProperty() || varInfoNames.contains(name)) {
// The object is a custom action with an associated
// VariableInfo entry for this name.
// Get the class name and then introspect at runtime.
out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString"
+ "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty"
+ "(_jspx_page_context.findAttribute(\""
+ name
+ "\"), \""
+ property
+ "\")));");
} else {
throw new JasperException(Localizer.getMessage("jsp.error.invalid.name", n.getStart(), name));
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.SetProperty n) throws JasperException {
String name = n.getTextAttribute("name");
String property = n.getTextAttribute("property");
String param = n.getTextAttribute("param");
Node.JspAttribute value = n.getValue();
n.setBeginJavaLine(out.getJavaLine());
if ("*".equals(property)) {
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspect("
+ "_jspx_page_context.findAttribute("
+ "\""
+ name + "\"), request);");
} else if (value == null) {
if (param == null)
{
param = property; // default to same as property
}
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \""
+ property
+ "\", request.getParameter(\""
+ param
+ "\"), "
+ "request, \""
+ param
+ "\", false);");
} else if (value.isExpression()) {
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetProperty("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \"" + property + "\",");
out.print(attributeValue(value, false, null));
out.println(");");
} else if (value.isELInterpreterInput()) {
// We've got to resolve the very call to the interpreter
// at runtime since we don't know what type to expect
// in the general case; we thus can't hard-wire the call
// into the generated code. (XXX We could, however,
// optimize the case where the bean is exposed with
// <jsp:useBean>, much as the code here does for
// getProperty.)
// The following holds true for the arguments passed to
// JspRuntimeLibrary.handleSetPropertyExpression():
// - 'pageContext' is a VariableResolver.
// - 'this' (either the generated Servlet or the generated tag
// handler for Tag files) is a FunctionMapper.
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetPropertyExpression("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \""
+ property
+ "\", "
+ quote(value.getValue())
+ ", "
+ "_jspx_page_context, "
+ value.getEL().getMapName() + ");");
} else if (value.isNamedAttribute()) {
// If the value for setProperty was specified via
// jsp:attribute, first generate code to evaluate
// that body.
String valueVarName = generateNamedAttributeValue(value
.getNamedAttributeNode());
out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \""
+ property
+ "\", "
+ valueVarName
+ ", null, null, false);");
} else {
out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper("
+ "_jspx_page_context.findAttribute(\""
+ name
+ "\"), \"" + property + "\", ");
out.print(attributeValue(value, false, null));
out.println(", null, null, false);");
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.UseBean n) throws JasperException {
String name = n.getTextAttribute("id");
String scope = n.getTextAttribute("scope");
String klass = n.getTextAttribute("class");
String type = n.getTextAttribute("type");
Node.JspAttribute beanName = n.getBeanName();
// If "class" is specified, try an instantiation at compile time
boolean generateNew = false;
String canonicalName = null; // Canonical name for klass
if (klass != null) {
try {
Class<?> bean = ctxt.getClassLoader().loadClass(klass);
if (klass.indexOf('$') >= 0) {
// Obtain the canonical type name
canonicalName = bean.getCanonicalName();
} else {
canonicalName = klass;
}
// Check that there is a 0 arg constructor
Constructor<?> constructor = bean.getConstructor(new Class[] {});
// Check the bean is public, not an interface, not abstract
// and in an exported module
int modifiers = bean.getModifiers();
// No need to test for being an interface here as the
// getConstructor() call above will have already failed for
// any interfaces.
if (!Modifier.isPublic(modifiers) ||
Modifier.isAbstract(modifiers) ||
!constructor.canAccess(null) ) {
throw new JasperException(Localizer.getMessage("jsp.error.invalid.bean",
Integer.valueOf(modifiers)));
}
// At compile time, we have determined that the bean class
// exists, with a public zero constructor, new() can be
// used for bean instantiation.
generateNew = true;
} catch (Exception e) {
// Cannot instantiate the specified class, either a
// compilation error or a runtime error will be raised,
// depending on a compiler flag.
if (ctxt.getOptions()
.getErrorOnUseBeanInvalidClassAttribute()) {
err.jspError(n, "jsp.error.invalid.bean", klass);
}
if (canonicalName == null) {
// Doing our best here to get a canonical name
// from the binary name, should work 99.99% of time.
canonicalName = klass.replace('$', '.');
}
}
if (type == null) {
// if type is unspecified, use "class" as type of bean
type = canonicalName;
}
}
// JSP.5.1, Semantics, para 1 - lock not required for request or
// page scope
String scopename = "jakarta.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page
String lock = null;
if ("request".equals(scope)) {
scopename = "jakarta.servlet.jsp.PageContext.REQUEST_SCOPE";
} else if ("session".equals(scope)) {
scopename = "jakarta.servlet.jsp.PageContext.SESSION_SCOPE";
lock = "session";
} else if ("application".equals(scope)) {
scopename = "jakarta.servlet.jsp.PageContext.APPLICATION_SCOPE";
lock = "application";
}
n.setBeginJavaLine(out.getJavaLine());
// Declare bean
out.printin(type);
out.print(' ');
out.print(name);
out.println(" = null;");
// Lock (if required) while getting or creating bean
if (lock != null) {
out.printin("synchronized (");
out.print(lock);
out.println(") {");
out.pushIndent();
}
// Locate bean from context
out.printin(name);
out.print(" = (");
out.print(type);
out.print(") _jspx_page_context.getAttribute(");
out.print(quote(name));
out.print(", ");
out.print(scopename);
out.println(");");
// Create bean
/*
* Check if bean is already there
*/
out.printin("if (");
out.print(name);
out.println(" == null){");
out.pushIndent();
if (klass == null && beanName == null) {
/*
* If both class name and beanName is not specified, the bean
* must be found locally, otherwise it's an error
*/
out.printin("throw new java.lang.InstantiationException(\"bean ");
out.print(name);
out.println(" not found within scope\");");
} else {
/*
* Instantiate the bean if it is not in the specified scope.
*/
if (!generateNew) {
String binaryName;
if (beanName != null) {
if (beanName.isNamedAttribute()) {
// If the value for beanName was specified via
// jsp:attribute, first generate code to evaluate
// that body.
binaryName = generateNamedAttributeValue(beanName
.getNamedAttributeNode());
} else {
binaryName = attributeValue(beanName, false, String.class);
}
} else {
// Implies klass is not null
binaryName = quote(klass);
}
out.printil("try {");
out.pushIndent();
out.printin(name);
out.print(" = (");
out.print(type);
out.print(") java.beans.Beans.instantiate(");
out.print("this.getClass().getClassLoader(), ");
out.print(binaryName);
out.println(");");
out.popIndent();
/*
* Note: Beans.instantiate throws ClassNotFoundException if
* the bean class is abstract.
*/
out.printil("} catch (java.lang.ClassNotFoundException exc) {");
out.pushIndent();
out.printil("throw new InstantiationException(exc.getMessage());");
out.popIndent();
out.printil("} catch (java.lang.Exception exc) {");
out.pushIndent();
out.printin("throw new jakarta.servlet.ServletException(");
out.print("\"Cannot create bean of class \" + ");
out.print(binaryName);
out.println(", exc);");
out.popIndent();
out.printil("}"); // close of try
} else {
// Implies klass is not null
// Generate codes to instantiate the bean class
out.printin(name);
out.print(" = new ");
out.print(canonicalName);
out.println("();");
}
/*
* Set attribute for bean in the specified scope
*/
out.printin("_jspx_page_context.setAttribute(");
out.print(quote(name));
out.print(", ");
out.print(name);
out.print(", ");
out.print(scopename);
out.println(");");
// Only visit the body when bean is instantiated
visitBody(n);
}
out.popIndent();
out.printil("}");
// End of lock block
if (lock != null) {
out.popIndent();
out.printil("}");
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.NamedAttribute n) throws JasperException {
// Don't visit body of this tag - we already did earlier.
}
@Override
public void visit(Node.CustomTag n) throws JasperException {
// Use plugin to generate more efficient code if there is one.
if (n.useTagPlugin()) {
generateTagPlugin(n);
return;
}
TagHandlerInfo handlerInfo = getTagHandlerInfo(n);
// Create variable names
String baseVar = createTagVarName(n.getQName(), n.getPrefix(), n
.getLocalName());
String tagEvalVar = "_jspx_eval_" + baseVar;
String tagHandlerVar = "_jspx_th_" + baseVar;
String tagPushBodyCountVar = "_jspx_push_body_count_" + baseVar;
// If the tag contains no scripting element, generate its codes
// to a method.
ServletWriter outSave = null;
Node.ChildInfo ci = n.getChildInfo();
if (ci.isScriptless() && !ci.hasScriptingVars()) {
// The tag handler and its body code can reside in a separate
// method if it is scriptless and does not have any scripting
// variable defined.
String tagMethod = "_jspx_meth_" + baseVar;
// Generate a call to this method
out.printin("if (");
out.print(tagMethod);
out.print("(");
if (parent != null) {
out.print(parent);
out.print(", ");
}
out.print("_jspx_page_context");
if (pushBodyCountVar != null) {
out.print(", ");
out.print(pushBodyCountVar);
}
out.println("))");
out.pushIndent();
out.printil((methodNesting > 0) ? "return true;" : "return;");
out.popIndent();
// Set up new buffer for the method
outSave = out;
/*
* For fragments, their bodies will be generated in fragment
* helper classes, and the Java line adjustments will be done
* there, hence they are set to null here to avoid double
* adjustments.
*/
GenBuffer genBuffer = new GenBuffer(n,
n.implementsSimpleTag() ? null : n.getBody());
methodsBuffered.add(genBuffer);
out = genBuffer.getOut();
methodNesting++;
// Generate code for method declaration
out.println();
out.pushIndent();
out.printin("private boolean ");
out.print(tagMethod);
out.print("(");
if (parent != null) {
out.print("jakarta.servlet.jsp.tagext.JspTag ");
out.print(parent);
out.print(", ");
}
out.print("jakarta.servlet.jsp.PageContext _jspx_page_context");
if (pushBodyCountVar != null) {
out.print(", int[] ");
out.print(pushBodyCountVar);
}
out.println(")");
out.printil(" throws java.lang.Throwable {");
out.pushIndent();
// Initialize local variables used in this method.
if (!isTagFile) {
out.printil("jakarta.servlet.jsp.PageContext pageContext = _jspx_page_context;");
}
// Only need to define out if the tag has a non-empty body,
// implements TryCatchFinally or uses
// <jsp:attribute>...</jsp:attribute> nodes
if (!n.hasEmptyBody() || n.implementsTryCatchFinally() || n.getNamedAttributeNodes().size() > 0) {
out.printil("jakarta.servlet.jsp.JspWriter out = _jspx_page_context.getOut();");
}
generateLocalVariables(out, n);
}
// Add the named objects to the list of 'introduced' names to enable
// a later test as per JSP.5.3
VariableInfo[] infos = n.getVariableInfos();
// The Validator always calls setTagData() which ensures infos is
// non-null
if (infos.length > 0) {
for (VariableInfo info : infos) {
// A null variable name will trigger multiple compilation
// failures so assume non-null here
pageInfo.getVarInfoNames().add(info.getVarName());
}
}
TagVariableInfo[] tagInfos = n.getTagVariableInfos();
// The way Tomcat constructs the TagInfo, getTagVariableInfos()
// will never return null.
if (tagInfos.length > 0) {
for (TagVariableInfo tagInfo : tagInfos) {
// tagInfo is always non-null
String name = tagInfo.getNameGiven();
if (name == null) {
String nameFromAttribute =
tagInfo.getNameFromAttribute();
name = n.getAttributeValue(nameFromAttribute);
}
pageInfo.getVarInfoNames().add(name);
}
}
if (n.implementsSimpleTag()) {
generateCustomDoTag(n, handlerInfo, tagHandlerVar);
} else {
/*
* Classic tag handler: Generate code for start element, body,
* and end element
*/
generateCustomStart(n, handlerInfo, tagHandlerVar, tagEvalVar,
tagPushBodyCountVar);
// visit body
String tmpParent = parent;
parent = tagHandlerVar;
boolean isSimpleTagParentSave = isSimpleTagParent;
isSimpleTagParent = false;
String tmpPushBodyCountVar = null;
if (n.implementsTryCatchFinally()) {
tmpPushBodyCountVar = pushBodyCountVar;
pushBodyCountVar = tagPushBodyCountVar;
}
boolean tmpIsSimpleTagHandler = isSimpleTagHandler;
isSimpleTagHandler = false;
visitBody(n);
parent = tmpParent;
isSimpleTagParent = isSimpleTagParentSave;
if (n.implementsTryCatchFinally()) {
pushBodyCountVar = tmpPushBodyCountVar;
}
isSimpleTagHandler = tmpIsSimpleTagHandler;
generateCustomEnd(n, tagHandlerVar, tagEvalVar,
tagPushBodyCountVar);
}
if (ci.isScriptless() && !ci.hasScriptingVars()) {
// Generate end of method
out.printil("return false;");
out.popIndent();
out.printil("}");
out.popIndent();
methodNesting--;
// restore previous writer
out = outSave;
}
}
private static final String DOUBLE_QUOTE = "\\\"";
@Override
public void visit(Node.UninterpretedTag n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
/*
* Write begin tag
*/
out.printin("out.write(\"<");
out.print(n.getQName());
Attributes attrs = n.getNonTaglibXmlnsAttributes();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
out.print(" ");
out.print(attrs.getQName(i));
out.print("=");
out.print(DOUBLE_QUOTE);
out.print(escape(attrs.getValue(i).replace("\"", """)));
out.print(DOUBLE_QUOTE);
}
}
attrs = n.getAttributes();
if (attrs != null) {
Node.JspAttribute[] jspAttrs = n.getJspAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
out.print(" ");
out.print(attrs.getQName(i));
out.print("=");
if (jspAttrs[i].isELInterpreterInput()) {
out.print("\\\"\" + ");
String debug = attributeValue(jspAttrs[i], false, String.class);
out.print(debug);
out.print(" + \"\\\"");
} else {
out.print(DOUBLE_QUOTE);
out.print(escape(jspAttrs[i].getValue().replace("\"", """)));
out.print(DOUBLE_QUOTE);
}
}
}
if (n.getBody() != null) {
out.println(">\");");
// Visit tag body
visitBody(n);
/*
* Write end tag
*/
out.printin("out.write(\"</");
out.print(n.getQName());
out.println(">\");");
} else {
out.println("/>\");");
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.JspElement n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
// Compute attribute value string for XML-style and named
// attributes
Map<String,String> map = new HashMap<>();
// Validator ensures this is non-null
Node.JspAttribute[] attrs = n.getJspAttributes();
for (int i = 0; i < attrs.length; i++) {
String value = null;
String nvp = null;
if (attrs[i].isNamedAttribute()) {
NamedAttribute attr = attrs[i].getNamedAttributeNode();
Node.JspAttribute omitAttr = attr.getOmit();
String omit;
if (omitAttr == null) {
omit = "false";
} else {
// String literals returned by attributeValue will be
// quoted and escaped.
omit = attributeValue(omitAttr, false, boolean.class);
if ("\"true\"".equals(omit)) {
continue;
}
}
value = generateNamedAttributeValue(
attrs[i].getNamedAttributeNode());
if ("\"false\"".equals(omit)) {
nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " +
value + " + \"\\\"\"";
} else {
nvp = " + (java.lang.Boolean.valueOf(" + omit + ")?\"\":\" " +
attrs[i].getName() + "=\\\"\" + " + value +
" + \"\\\"\")";
}
} else {
value = attributeValue(attrs[i], false, Object.class);
nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " +
value + " + \"\\\"\"";
}
map.put(attrs[i].getName(), nvp);
}
// Write begin tag, using XML-style 'name' attribute as the
// element name
String elemName = attributeValue(n.getNameAttribute(), false, String.class);
out.printin("out.write(\"<\"");
out.print(" + " + elemName);
// Write remaining attributes
for (Entry<String, String> attrEntry : map.entrySet()) {
out.print(attrEntry.getValue());
}
// Does the <jsp:element> have nested tags other than
// <jsp:attribute>
boolean hasBody = false;
Node.Nodes subelements = n.getBody();
if (subelements != null) {
for (int i = 0; i < subelements.size(); i++) {
Node subelem = subelements.getNode(i);
if (!(subelem instanceof Node.NamedAttribute)) {
hasBody = true;
break;
}
}
}
if (hasBody) {
out.println(" + \">\");");
// Smap should not include the body
n.setEndJavaLine(out.getJavaLine());
// Visit tag body
visitBody(n);
// Write end tag
out.printin("out.write(\"</\"");
out.print(" + " + elemName);
out.println(" + \">\");");
} else {
out.println(" + \"/>\");");
n.setEndJavaLine(out.getJavaLine());
}
}
@Override
public void visit(Node.TemplateText n) throws JasperException {
String text = n.getText();
// If the extended option is being used attempt to minimize the
// frequency of regex operations.
if (ctxt.getOptions().getTrimSpaces().equals(TrimSpacesOption.EXTENDED) && text.contains("\n")) {
// Ensure there are no <pre> or </pre> tags embedded in this
// text - if there are, we want to NOT modify the whitespace.
Matcher preMatcher = PRE_TAG_PATTERN.matcher(text);
if (!preMatcher.matches()) {
Matcher matcher = BLANK_LINE_PATTERN.matcher(text);
String revisedText = matcher.replaceAll("\n");
// Leading and trailing whitespace can be trimmed so remove
// it here as the regex won't remove it.
text = revisedText.trim();
}
}
int textSize = text.length();
if (textSize == 0) {
return;
}
if (textSize <= 3) {
// Special case small text strings
n.setBeginJavaLine(out.getJavaLine());
int lineInc = 0;
for (int i = 0; i < textSize; i++) {
char ch = text.charAt(i);
out.printil("out.write(" + quote(ch) + ");");
if (i > 0) {
n.addSmap(lineInc);
}
if (ch == '\n') {
lineInc++;
}
}
n.setEndJavaLine(out.getJavaLine());
return;
}
if (ctxt.getOptions().genStringAsCharArray()) {
// Generate Strings as char arrays, for performance
ServletWriter caOut;
if (charArrayBuffer == null) {
charArrayBuffer = new GenBuffer();
caOut = charArrayBuffer.getOut();
caOut.pushIndent();
textMap = new HashMap<>();
} else {
caOut = charArrayBuffer.getOut();
}
// UTF-8 is up to 4 bytes per character
// String constants are limited to 64k bytes
// Limit string constants here to 16k characters
int textIndex = 0;
int textLength = text.length();
while (textIndex < textLength) {
int len = 0;
if (textLength - textIndex > 16384) {
len = 16384;
} else {
len = textLength - textIndex;
}
String output = text.substring(textIndex, textIndex + len);
String charArrayName = textMap.get(output);
if (charArrayName == null) {
charArrayName = "_jspx_char_array_" + charArrayCount++;
textMap.put(output, charArrayName);
caOut.printin("static char[] ");
caOut.print(charArrayName);
caOut.print(" = ");
caOut.print(quote(output));
caOut.println(".toCharArray();");
}
n.setBeginJavaLine(out.getJavaLine());
out.printil("out.write(" + charArrayName + ");");
n.setEndJavaLine(out.getJavaLine());
textIndex = textIndex + len;
}
return;
}
n.setBeginJavaLine(out.getJavaLine());
out.printin();
StringBuilder sb = new StringBuilder("out.write(\"");
int initLength = sb.length();
int count = JspUtil.CHUNKSIZE;
int srcLine = 0; // relative to starting source line
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
--count;
switch (ch) {
case '"':
sb.append('\\').append('\"');
break;
case '\\':
sb.append('\\').append('\\');
break;
case '\r':
sb.append('\\').append('r');
break;
case '\n':
sb.append('\\').append('n');
srcLine++;
if (breakAtLF || count < 0) {
// Generate an out.write() when see a '\n' in template
sb.append("\");");
out.println(sb.toString());
if (i < text.length() - 1) {
out.printin();
}
sb.setLength(initLength);
count = JspUtil.CHUNKSIZE;
}
// add a Smap for this line
n.addSmap(srcLine);
break;
default:
sb.append(ch);
}
}
if (sb.length() > initLength) {
sb.append("\");");
out.println(sb.toString());
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.JspBody n) throws JasperException {
if (n.getBody() != null) {
if (isSimpleTagHandler) {
out.printin(simpleTagHandlerVar);
out.print(".setJspBody(");
generateJspFragment(n, simpleTagHandlerVar);
out.println(");");
} else {
visitBody(n);
}
}
}
@Override
public void visit(Node.InvokeAction n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
// Copy virtual page scope of tag file to page scope of invoking
// page
out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();");
String varReaderAttr = n.getTextAttribute("varReader");
String varAttr = n.getTextAttribute("var");
if (varReaderAttr != null || varAttr != null) {
out.printil("_jspx_sout = new java.io.StringWriter();");
} else {
out.printil("_jspx_sout = null;");
}
// Invoke fragment, unless fragment is null
out.printin("if (");
out.print(toGetterMethod(n.getTextAttribute("fragment")));
out.println(" != null) {");
out.pushIndent();
out.printin(toGetterMethod(n.getTextAttribute("fragment")));
out.println(".invoke(_jspx_sout);");
out.popIndent();
out.printil("}");
// Store varReader in appropriate scope
if (varReaderAttr != null || varAttr != null) {
String scopeName = n.getTextAttribute("scope");
out.printin("_jspx_page_context.setAttribute(");
if (varReaderAttr != null) {
out.print(quote(varReaderAttr));
out.print(", new java.io.StringReader(_jspx_sout.toString())");
} else {
out.print(quote(varAttr));
out.print(", _jspx_sout.toString()");
}
if (scopeName != null) {
out.print(", ");
out.print(getScopeConstant(scopeName));
}
out.println(");");
}
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.DoBodyAction n) throws JasperException {
n.setBeginJavaLine(out.getJavaLine());
// Copy virtual page scope of tag file to page scope of invoking
// page
out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();");
// Invoke body
String varReaderAttr = n.getTextAttribute("varReader");
String varAttr = n.getTextAttribute("var");
if (varReaderAttr != null || varAttr != null) {
out.printil("_jspx_sout = new java.io.StringWriter();");
} else {
out.printil("_jspx_sout = null;");
}
out.printil("if (getJspBody() != null)");
out.pushIndent();
out.printil("getJspBody().invoke(_jspx_sout);");
out.popIndent();
// Store varReader in appropriate scope
if (varReaderAttr != null || varAttr != null) {
String scopeName = n.getTextAttribute("scope");
out.printin("_jspx_page_context.setAttribute(");
if (varReaderAttr != null) {
out.print(quote(varReaderAttr));
out.print(", new java.io.StringReader(_jspx_sout.toString())");
} else {
out.print(quote(varAttr));
out.print(", _jspx_sout.toString()");
}
if (scopeName != null) {
out.print(", ");
out.print(getScopeConstant(scopeName));
}
out.println(");");
}
// Restore EL context
out.printil("jspContext.getELContext().putContext(jakarta.servlet.jsp.JspContext.class,getJspContext());");
n.setEndJavaLine(out.getJavaLine());
}
@Override
public void visit(Node.AttributeGenerator n) throws JasperException {
Node.CustomTag tag = n.getTag();
Node.JspAttribute[] attrs = tag.getJspAttributes();
// The TagPluginManager only creates AttributeGenerator nodes for
// attributes that are present.
for (int i = 0; i < attrs.length; i++) {
if (attrs[i].getName().equals(n.getName())) {
out.print(evaluateAttribute(getTagHandlerInfo(tag),
attrs[i], tag, null));
break;
}
}
}
private TagHandlerInfo getTagHandlerInfo(Node.CustomTag n)
throws JasperException {
Map<String, TagHandlerInfo> handlerInfosByShortName = handlerInfos.
computeIfAbsent(n.getPrefix(), k -> new HashMap<>());
TagHandlerInfo handlerInfo =
handlerInfosByShortName.get(n.getLocalName());
if (handlerInfo == null) {
handlerInfo = new TagHandlerInfo(n, n.getTagHandlerClass(), err);
handlerInfosByShortName.put(n.getLocalName(), handlerInfo);
}
return handlerInfo;
}
private void generateTagPlugin(Node.CustomTag n) throws JasperException {
n.getAtSTag().visit(this);
visitBody(n);
n.getAtETag().visit(this);
}
private void generateCustomStart(Node.CustomTag n,
TagHandlerInfo handlerInfo, String tagHandlerVar,
String tagEvalVar, String tagPushBodyCountVar)
throws JasperException {
Class<?> tagHandlerClass =
handlerInfo.getTagHandlerClass();
out.printin("// ");
out.println(n.getQName());
n.setBeginJavaLine(out.getJavaLine());
// Declare AT_BEGIN scripting variables
declareScriptingVars(n, VariableInfo.AT_BEGIN);
saveScriptingVars(n, VariableInfo.AT_BEGIN);
String tagHandlerClassName = tagHandlerClass.getCanonicalName();
if (isPoolingEnabled && !(n.implementsJspIdConsumer())) {
out.printin(tagHandlerClassName);
out.print(" ");
out.print(tagHandlerVar);
out.print(" = ");
out.print("(");
out.print(tagHandlerClassName);
out.print(") ");
out.print(n.getTagHandlerPoolName());
out.print(".get(");
out.print(tagHandlerClassName);
out.println(".class);");
out.printin("boolean ");
out.print(tagHandlerVar);
out.println("_reused = false;");
} else {
writeNewInstance(tagHandlerVar, tagHandlerClass);
}
// Wrap use of tag in try/finally to ensure clean-up takes place
out.printil("try {");
out.pushIndent();
// includes setting the context
generateSetters(n, tagHandlerVar, handlerInfo, false);
if (n.implementsTryCatchFinally()) {
out.printin("int[] ");
out.print(tagPushBodyCountVar);
out.println(" = new int[] { 0 };");
out.printil("try {");
out.pushIndent();
}
out.printin("int ");
out.print(tagEvalVar);
out.print(" = ");
out.print(tagHandlerVar);
out.println(".doStartTag();");
if (!n.implementsBodyTag()) {
// Synchronize AT_BEGIN scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
}
if (!n.hasEmptyBody()) {
out.printin("if (");
out.print(tagEvalVar);
out.println(" != jakarta.servlet.jsp.tagext.Tag.SKIP_BODY) {");
out.pushIndent();
// Declare NESTED scripting variables
declareScriptingVars(n, VariableInfo.NESTED);
saveScriptingVars(n, VariableInfo.NESTED);
if (n.implementsBodyTag()) {
out.printin("if (");
out.print(tagEvalVar);
out.println(" != jakarta.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {");
// Assume EVAL_BODY_BUFFERED
out.pushIndent();
if (n.implementsTryCatchFinally()) {
out.printin(tagPushBodyCountVar);
out.println("[0]++;");
} else if (pushBodyCountVar != null) {
out.printin(pushBodyCountVar);
out.println("[0]++;");
}
out.printin("out = org.apache.jasper.runtime.JspRuntimeLibrary.startBufferedBody(");
out.print("_jspx_page_context, ");
out.print(tagHandlerVar);
out.println(");");
out.popIndent();
out.printil("}");
// Synchronize AT_BEGIN and NESTED scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
syncScriptingVars(n, VariableInfo.NESTED);
} else {
// Synchronize NESTED scripting variables
syncScriptingVars(n, VariableInfo.NESTED);
}
if (n.implementsIterationTag()) {
out.printil("do {");
out.pushIndent();
}
}
// Map the Java lines that handles start of custom tags to the
// JSP line for this tag
n.setEndJavaLine(out.getJavaLine());
}
private void writeNewInstance(String tagHandlerVar, Class<?> tagHandlerClass) {
String tagHandlerClassName = tagHandlerClass.getCanonicalName();
out.printin(tagHandlerClassName);
out.print(" ");
out.print(tagHandlerVar);
out.print(" = ");
if (useInstanceManagerForTags) {
out.print("(");
out.print(tagHandlerClassName);
out.print(")");
out.print("_jsp_getInstanceManager().newInstance(\"");
// Need the binary name here, not the canonical name
out.print(tagHandlerClass.getName());
out.println("\", this.getClass().getClassLoader());");
} else {
out.print("new ");
out.print(tagHandlerClassName);
out.println("();");
out.printin("_jsp_getInstanceManager().newInstance(");
out.print(tagHandlerVar);
out.println(");");
}
}
private void writeDestroyInstance(String tagHandlerVar) {
out.printin("_jsp_getInstanceManager().destroyInstance(");
out.print(tagHandlerVar);
out.println(");");
}
private void generateCustomEnd(Node.CustomTag n, String tagHandlerVar,
String tagEvalVar, String tagPushBodyCountVar) {
if (!n.hasEmptyBody()) {
if (n.implementsIterationTag()) {
out.printin("int evalDoAfterBody = ");
out.print(tagHandlerVar);
out.println(".doAfterBody();");
// Synchronize AT_BEGIN and NESTED scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
syncScriptingVars(n, VariableInfo.NESTED);
out.printil("if (evalDoAfterBody != jakarta.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)");
out.pushIndent();
out.printil("break;");
out.popIndent();
out.popIndent();
out.printil("} while (true);");
}
restoreScriptingVars(n, VariableInfo.NESTED);
if (n.implementsBodyTag()) {
out.printin("if (");
out.print(tagEvalVar);
out.println(" != jakarta.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {");
out.pushIndent();
out.printil("out = _jspx_page_context.popBody();");
if (n.implementsTryCatchFinally()) {
out.printin(tagPushBodyCountVar);
out.println("[0]--;");
} else if (pushBodyCountVar != null) {
out.printin(pushBodyCountVar);
out.println("[0]--;");
}
out.popIndent();
out.printil("}");
}
out.popIndent(); // EVAL_BODY
out.printil("}");
}
out.printin("if (");
out.print(tagHandlerVar);
out.println(".doEndTag() == jakarta.servlet.jsp.tagext.Tag.SKIP_PAGE) {");
out.pushIndent();
if (isTagFile || isFragment) {
out.printil("throw new jakarta.servlet.jsp.SkipPageException();");
} else {
out.printil((methodNesting > 0) ? "return true;" : "return;");
}
out.popIndent();
out.printil("}");
// Synchronize AT_BEGIN scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
// TryCatchFinally
if (n.implementsTryCatchFinally()) {
out.popIndent(); // try
out.printil("} catch (java.lang.Throwable _jspx_exception) {");
out.pushIndent();
out.printin("while (");
out.print(tagPushBodyCountVar);
out.println("[0]-- > 0)");
out.pushIndent();
out.printil("out = _jspx_page_context.popBody();");
out.popIndent();
out.printin(tagHandlerVar);
out.println(".doCatch(_jspx_exception);");
out.popIndent();
out.printil("} finally {");
out.pushIndent();
out.printin(tagHandlerVar);
out.println(".doFinally();");
}
if (n.implementsTryCatchFinally()) {
out.popIndent();
out.printil("}");
}
// Print tag reuse
if (isPoolingEnabled && !(n.implementsJspIdConsumer())) {
out.printin(n.getTagHandlerPoolName());
out.print(".reuse(");
out.print(tagHandlerVar);
out.println(");");
out.printin(tagHandlerVar);
out.println("_reused = true;");
}
// Ensure clean-up takes place
// Use JspRuntimeLibrary to minimise code in _jspService()
out.popIndent();
out.printil("} finally {");
out.pushIndent();
out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.releaseTag(");
out.print(tagHandlerVar);
out.print(", _jsp_getInstanceManager(), ");
if (isPoolingEnabled && !(n.implementsJspIdConsumer())) {
out.print(tagHandlerVar);
out.println("_reused);");
} else {
out.println("false);");
}
out.popIndent();
out.printil("}");
// Declare and synchronize AT_END scripting variables (must do this
// outside the try/catch/finally block)
declareScriptingVars(n, VariableInfo.AT_END);
syncScriptingVars(n, VariableInfo.AT_END);
restoreScriptingVars(n, VariableInfo.AT_BEGIN);
}
private void generateCustomDoTag(Node.CustomTag n,
TagHandlerInfo handlerInfo, String tagHandlerVar)
throws JasperException {
Class<?> tagHandlerClass =
handlerInfo.getTagHandlerClass();
n.setBeginJavaLine(out.getJavaLine());
out.printin("// ");
out.println(n.getQName());
// Declare AT_BEGIN scripting variables
declareScriptingVars(n, VariableInfo.AT_BEGIN);
saveScriptingVars(n, VariableInfo.AT_BEGIN);
// Declare AT_END scripting variables
declareScriptingVars(n, VariableInfo.AT_END);
writeNewInstance(tagHandlerVar, tagHandlerClass);
out.printil("try {");
out.pushIndent();
generateSetters(n, tagHandlerVar, handlerInfo, true);
// Set the body
if (findJspBody(n) == null) {
/*
* Encapsulate body of custom tag invocation in JspFragment and
* pass it to tag handler's setJspBody(), unless tag body is
* empty
*/
if (!n.hasEmptyBody()) {
out.printin(tagHandlerVar);
out.print(".setJspBody(");
generateJspFragment(n, tagHandlerVar);
out.println(");");
}
} else {
/*
* Body of tag is the body of the <jsp:body> element. The visit
* method for that element is going to encapsulate that
* element's body in a JspFragment and pass it to the tag
* handler's setJspBody()
*/
String tmpTagHandlerVar = simpleTagHandlerVar;
simpleTagHandlerVar = tagHandlerVar;
boolean tmpIsSimpleTagHandler = isSimpleTagHandler;
isSimpleTagHandler = true;
visitBody(n);
simpleTagHandlerVar = tmpTagHandlerVar;
isSimpleTagHandler = tmpIsSimpleTagHandler;
}
out.printin(tagHandlerVar);
out.println(".doTag();");
restoreScriptingVars(n, VariableInfo.AT_BEGIN);
// Synchronize AT_BEGIN scripting variables
syncScriptingVars(n, VariableInfo.AT_BEGIN);
// Synchronize AT_END scripting variables
syncScriptingVars(n, VariableInfo.AT_END);
out.popIndent();
out.printil("} finally {");
out.pushIndent();
// Resource injection
writeDestroyInstance(tagHandlerVar);
out.popIndent();
out.printil("}");
n.setEndJavaLine(out.getJavaLine());
}
private void declareScriptingVars(Node.CustomTag n, int scope) {
if (isFragment) {
// No need to declare Java variables, if we inside a
// JspFragment, because a fragment is always scriptless.
return;
}
// Note: ScriptingVariabler$ScriptingVariableVisitor will already
// have skipped any variables where declare is set to false.
List<Object> vec = n.getScriptingVars(scope);
if (vec != null) {
for (Object elem : vec) {
if (elem instanceof VariableInfo) {
VariableInfo varInfo = (VariableInfo) elem;
out.printin(varInfo.getClassName());
out.print(" ");
out.print(varInfo.getVarName());
out.println(" = null;");
} else {
TagVariableInfo tagVarInfo = (TagVariableInfo) elem;
String varName = tagVarInfo.getNameGiven();
if (varName == null) {
varName = n.getTagData().getAttributeString(
tagVarInfo.getNameFromAttribute());
} else if (tagVarInfo.getNameFromAttribute() != null) {
// alias
continue;
}
out.printin(tagVarInfo.getClassName());
out.print(" ");
out.print(varName);
out.println(" = null;");
}
}
}
}
/*
* This method is called as part of the custom tag's start element.
*
* If the given custom tag has a custom nesting level greater than 0,
* save the current values of its scripting variables to temporary
* variables, so those values may be restored in the tag's end element.
* This way, the scripting variables may be synchronized by the given
* tag without affecting their original values.
*/
private void saveScriptingVars(Node.CustomTag n, int scope) {
if (n.getCustomNestingLevel() == 0) {
return;
}
if (isFragment) {
// No need to declare Java variables, if we inside a
// JspFragment, because a fragment is always scriptless.
// Thus, there is no need to save/ restore/ sync them.
// Note, that JspContextWrapper.syncFoo() methods will take
// care of saving/ restoring/ sync'ing of JspContext attributes.
return;
}
TagVariableInfo[] tagVarInfos = n.getTagVariableInfos();
VariableInfo[] varInfos = n.getVariableInfos();
if ((varInfos.length == 0) && (tagVarInfos.length == 0)) {
return;
}
List<Object> declaredVariables = n.getScriptingVars(scope);
if (varInfos.length > 0) {
for (VariableInfo varInfo : varInfos) {
if (varInfo.getScope() != scope) {
continue;
}
// If the scripting variable has been declared, skip codes
// for saving and restoring it.
if (declaredVariables.contains(varInfo)) {
continue;
}
String varName = varInfo.getVarName();
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
out.printin(tmpVarName);
out.print(" = ");
out.print(varName);
out.println(";");
}
} else {
for (TagVariableInfo tagVarInfo : tagVarInfos) {
if (tagVarInfo.getScope() != scope) {
continue;
}
// If the scripting variable has been declared, skip codes
// for saving and restoring it.
if (declaredVariables.contains(tagVarInfo)) {
continue;
}
String varName = tagVarInfo.getNameGiven();
if (varName == null) {
varName = n.getTagData().getAttributeString(
tagVarInfo.getNameFromAttribute());
}
// Alias is not possible here.
// Alias can only be configured for tag files. As SimpleTag
// implementations, isFragment will always be true above
// hence execution never reaches this point.
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
out.printin(tmpVarName);
out.print(" = ");
out.print(varName);
out.println(";");
}
}
}
/*
* This method is called as part of the custom tag's end element.
*
* If the given custom tag has a custom nesting level greater than 0,
* restore its scripting variables to their original values that were
* saved in the tag's start element.
*/
private void restoreScriptingVars(Node.CustomTag n, int scope) {
if (n.getCustomNestingLevel() == 0) {
return;
}
if (isFragment) {
// No need to declare Java variables, if we inside a
// JspFragment, because a fragment is always scriptless.
// Thus, there is no need to save/ restore/ sync them.
// Note, that JspContextWrapper.syncFoo() methods will take
// care of saving/ restoring/ sync'ing of JspContext attributes.
return;
}
TagVariableInfo[] tagVarInfos = n.getTagVariableInfos();
VariableInfo[] varInfos = n.getVariableInfos();
if ((varInfos.length == 0) && (tagVarInfos.length == 0)) {
return;
}
List<Object> declaredVariables = n.getScriptingVars(scope);
if (varInfos.length > 0) {
for (VariableInfo varInfo : varInfos) {
if (varInfo.getScope() != scope) {
continue;
}
// If the scripting variable has been declared, skip codes
// for saving and restoring it.
if (declaredVariables.contains(varInfo)) {
continue;
}
String varName = varInfo.getVarName();
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
out.printin(varName);
out.print(" = ");
out.print(tmpVarName);
out.println(";");
}
} else {
for (TagVariableInfo tagVarInfo : tagVarInfos) {
if (tagVarInfo.getScope() != scope) {
continue;
}
// If the scripting variable has been declared, skip codes
// for saving and restoring it.
if (declaredVariables.contains(tagVarInfo)) {
continue;
}
String varName = tagVarInfo.getNameGiven();
if (varName == null) {
varName = n.getTagData().getAttributeString(
tagVarInfo.getNameFromAttribute());
}
// Alias is not possible here.
// Alias can only be configured for tag files. As SimpleTag
// implementations, isFragment will always be true above
// hence execution never reaches this point.
String tmpVarName = "_jspx_" + varName + "_"
+ n.getCustomNestingLevel();
out.printin(varName);
out.print(" = ");
out.print(tmpVarName);
out.println(";");
}
}
}
/*
* Synchronizes the scripting variables of the given custom tag for the
* given scope.
*/
private void syncScriptingVars(Node.CustomTag n, int scope) {
if (isFragment) {
// No need to declare Java variables, if we inside a
// JspFragment, because a fragment is always scriptless.
// Thus, there is no need to save/ restore/ sync them.
// Note, that JspContextWrapper.syncFoo() methods will take
// care of saving/ restoring/ sync'ing of JspContext attributes.
return;
}
TagVariableInfo[] tagVarInfos = n.getTagVariableInfos();
VariableInfo[] varInfos = n.getVariableInfos();
if ((varInfos.length == 0) && (tagVarInfos.length == 0)) {
return;
}
if (varInfos.length > 0) {
for (VariableInfo varInfo : varInfos) {
if (varInfo.getScope() == scope) {
out.printin(varInfo.getVarName());
out.print(" = (");
out.print(varInfo.getClassName());
out.print(") _jspx_page_context.findAttribute(");
out.print(quote(varInfo.getVarName()));
out.println(");");
}
}
} else {
for (TagVariableInfo tagVarInfo : tagVarInfos) {
if (tagVarInfo.getScope() == scope) {
String name = tagVarInfo.getNameGiven();
if (name == null) {
name = n.getTagData().getAttributeString(
tagVarInfo.getNameFromAttribute());
} else if (tagVarInfo.getNameFromAttribute() != null) {
// alias
continue;
}
out.printin(name);
out.print(" = (");
out.print(tagVarInfo.getClassName());
out.print(") _jspx_page_context.findAttribute(");
out.print(quote(name));
out.println(");");
}
}
}
}
private String getJspContextVar() {
if (this.isTagFile) {
return "this.getJspContext()";
}
return "_jspx_page_context";
}
/*
* Creates a tag variable name by concatenating the given prefix and
* shortName and encoded to make the resultant string a valid Java
* Identifier.
*/
private String createTagVarName(String fullName, String prefix,
String shortName) {
String varName;
synchronized (tagVarNumbers) {
varName = prefix + "_" + shortName + "_";
if (tagVarNumbers.get(fullName) != null) {
Integer i = tagVarNumbers.get(fullName);
varName = varName + i.intValue();
tagVarNumbers.put(fullName,
Integer.valueOf(i.intValue() + 1));
} else {
tagVarNumbers.put(fullName, Integer.valueOf(1));
varName = varName + "0";
}
}
return JspUtil.makeJavaIdentifier(varName);
}
@SuppressWarnings("null")
private String evaluateAttribute(TagHandlerInfo handlerInfo,
Node.JspAttribute attr, Node.CustomTag n, String tagHandlerVar)
throws JasperException {
String attrValue = attr.getValue();
if (attrValue == null) {
// Must be a named attribute
if (n.checkIfAttributeIsJspFragment(attr.getName())) {
// XXX - no need to generate temporary variable here
attrValue = generateNamedAttributeJspFragment(attr
.getNamedAttributeNode(), tagHandlerVar);
} else {
attrValue = generateNamedAttributeValue(attr
.getNamedAttributeNode());
}
}
String localName = attr.getLocalName();
Method m = null;
Class<?>[] c = null;
if (attr.isDynamic()) {
c = OBJECT_CLASS;
} else {
m = handlerInfo.getSetterMethod(localName);
if (m == null) {
err.jspError(n, "jsp.error.unable.to_find_method", attr
.getName());
}
c = m.getParameterTypes();
// XXX assert(c.length > 0)
}
if (attr.isExpression()) {
// Do nothing
} else if (attr.isNamedAttribute()) {
if (!n.checkIfAttributeIsJspFragment(attr.getName())
&& !attr.isDynamic()) {
attrValue = stringInterpreter.convertString(c[0], attrValue, localName,
handlerInfo.getPropertyEditorClass(localName), true);
}
} else if (attr.isELInterpreterInput()) {
// results buffer
StringBuilder sb = new StringBuilder(64);
TagAttributeInfo tai = attr.getTagAttributeInfo();
// generate elContext reference
sb.append(getJspContextVar());
sb.append(".getELContext()");
String elContext = sb.toString();
if (attr.getEL() != null && attr.getEL().getMapName() != null) {
sb.setLength(0);
sb.append("new org.apache.jasper.el.ELContextWrapper(");
sb.append(elContext);
sb.append(',');
sb.append(attr.getEL().getMapName());
sb.append(')');
elContext = sb.toString();
}
// reset buffer
sb.setLength(0);
// create our mark
sb.append(n.getStart().toString());
sb.append(" '");
sb.append(attrValue);
sb.append('\'');
String mark = sb.toString();
// reset buffer
sb.setLength(0);
// depending on type
if (attr.isDeferredInput()
|| ((tai != null) && ValueExpression.class.getName().equals(tai.getTypeName()))) {
sb.append("new org.apache.jasper.el.JspValueExpression(");
sb.append(quote(mark));
sb.append(",_jsp_getExpressionFactory().createValueExpression(");
if (attr.getEL() != null) { // optimize
sb.append(elContext);
sb.append(',');
}
sb.append(quote(attrValue));
sb.append(',');
sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName()));
sb.append("))");
// should the expression be evaluated before passing to
// the setter?
boolean evaluate = false;
if (tai.canBeRequestTime()) {
evaluate = true; // JSP.2.3.2
}
if (attr.isDeferredInput()) {
evaluate = false; // JSP.2.3.3
}
if (attr.isDeferredInput() && tai.canBeRequestTime()) {
evaluate = !attrValue.contains("#{"); // JSP.2.3.5
}
if (evaluate) {
sb.append(".getValue(");
sb.append(getJspContextVar());
sb.append(".getELContext()");
sb.append(')');
}
attrValue = sb.toString();
} else if (attr.isDeferredMethodInput()
|| ((tai != null) && MethodExpression.class.getName().equals(tai.getTypeName()))) {
sb.append("new org.apache.jasper.el.JspMethodExpression(");
sb.append(quote(mark));
sb.append(",_jsp_getExpressionFactory().createMethodExpression(");
sb.append(elContext);
sb.append(',');
sb.append(quote(attrValue));
sb.append(',');
sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName()));
sb.append(',');
sb.append("new java.lang.Class[] {");
String[] p = attr.getParameterTypeNames();
for (String s : p) {
sb.append(JspUtil.toJavaSourceTypeFromTld(s));
sb.append(',');
}
if (p.length > 0) {
sb.setLength(sb.length() - 1);
}
sb.append("}))");
attrValue = sb.toString();
} else {
// Must be EL
// run attrValue through the expression interpreter
String mapName = attr.getEL().getMapName();
attrValue = elInterpreter.interpreterCall(ctxt,
this.isTagFile, attrValue, c[0], mapName);
}
} else {
attrValue = stringInterpreter.convertString(c[0], attrValue, localName,
handlerInfo.getPropertyEditorClass(localName), false);
}
return attrValue;
}
/**
* Generate code to create a map for the alias variables
*
* @return the name of the map
*/
private String generateAliasMap(Node.CustomTag n,
String tagHandlerVar) {
TagVariableInfo[] tagVars = n.getTagVariableInfos();
String aliasMapVar = null;
boolean aliasSeen = false;
for (TagVariableInfo tagVar : tagVars) {
String nameFrom = tagVar.getNameFromAttribute();
if (nameFrom != null) {
String aliasedName = n.getAttributeValue(nameFrom);
if (!aliasSeen) {
out.printin("java.util.HashMap ");
aliasMapVar = tagHandlerVar + "_aliasMap";
out.print(aliasMapVar);
out.println(" = new java.util.HashMap();");
aliasSeen = true;
}
out.printin(aliasMapVar);
out.print(".put(");
out.print(quote(tagVar.getNameGiven()));
out.print(", ");
out.print(quote(aliasedName));
out.println(");");
}
}
return aliasMapVar;
}
private void generateSetters(Node.CustomTag n, String tagHandlerVar,
TagHandlerInfo handlerInfo, boolean simpleTag)
throws JasperException {
// Set context
if (simpleTag) {
// Generate alias map
String aliasMapVar = null;
if (n.isTagFile()) {
aliasMapVar = generateAliasMap(n, tagHandlerVar);
}
out.printin(tagHandlerVar);
if (aliasMapVar == null) {
out.println(".setJspContext(_jspx_page_context);");
} else {
out.print(".setJspContext(_jspx_page_context, ");
out.print(aliasMapVar);
out.println(");");
}
} else {
out.printin(tagHandlerVar);
out.println(".setPageContext(_jspx_page_context);");
}
// Set parent
if (isTagFile && parent == null) {
out.printin(tagHandlerVar);
out.print(".setParent(");
out.print("new jakarta.servlet.jsp.tagext.TagAdapter(");
out.println("(jakarta.servlet.jsp.tagext.SimpleTag) this ));");
} else if (!simpleTag) {
out.printin(tagHandlerVar);
out.print(".setParent(");
if (parent != null) {
if (isSimpleTagParent) {
out.print("new jakarta.servlet.jsp.tagext.TagAdapter(");
out.print("(jakarta.servlet.jsp.tagext.SimpleTag) ");
out.print(parent);
out.println("));");
} else {
out.print("(jakarta.servlet.jsp.tagext.Tag) ");
out.print(parent);
out.println(");");
}
} else {
out.println("null);");
}
} else {
// The setParent() method need not be called if the value being
// passed is null, since SimpleTag instances are not reused
if (parent != null) {
out.printin(tagHandlerVar);
out.print(".setParent(");
out.print(parent);
out.println(");");
}
}
// need to handle deferred values and methods
Node.JspAttribute[] attrs = n.getJspAttributes();
for (int i = 0; attrs != null && i < attrs.length; i++) {
String attrValue = evaluateAttribute(handlerInfo, attrs[i], n,
tagHandlerVar);
Mark m = n.getStart();
out.printil("// "+m.getFile()+"("+m.getLineNumber()+","+m.getColumnNumber()+") "+ attrs[i].getTagAttributeInfo());
if (attrs[i].isDynamic()) {
out.printin(tagHandlerVar);
out.print(".");
out.print("setDynamicAttribute(");
String uri = attrs[i].getURI();
if ("".equals(uri) || (uri == null)) {
out.print("null");
} else {
out.print("\"" + attrs[i].getURI() + "\"");
}
out.print(", \"");
out.print(attrs[i].getLocalName());
out.print("\", ");
out.print(attrValue);
out.println(");");
} else {
out.printin(tagHandlerVar);
out.print(".");
out.print(handlerInfo.getSetterMethod(
attrs[i].getLocalName()).getName());
out.print("(");
out.print(attrValue);
out.println(");");
}
}
// JspIdConsumer (after context has been set)
if (n.implementsJspIdConsumer()) {
out.printin(tagHandlerVar);
out.print(".setJspId(\"");
out.print(createJspId());
out.println("\");");
}
}
/*
* Converts the scope string representation, whose possible values are
* "page", "request", "session", and "application", to the corresponding
* scope constant.
*/
private String getScopeConstant(String scope) {
String scopeName = "jakarta.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page
if ("request".equals(scope)) {
scopeName = "jakarta.servlet.jsp.PageContext.REQUEST_SCOPE";
} else if ("session".equals(scope)) {
scopeName = "jakarta.servlet.jsp.PageContext.SESSION_SCOPE";
} else if ("application".equals(scope)) {
scopeName = "jakarta.servlet.jsp.PageContext.APPLICATION_SCOPE";
}
return scopeName;
}
/**
* Generates anonymous JspFragment inner class which is passed as an
* argument to SimpleTag.setJspBody().
*/
private void generateJspFragment(ChildInfoBase n, String tagHandlerVar) throws JasperException {
// XXX - A possible optimization here would be to check to see
// if the only child of the parent node is TemplateText. If so,
// we know there won't be any parameters, etc, so we can
// generate a low-overhead JspFragment that just echoes its
// body. The implementation of this fragment can come from
// the org.apache.jasper.runtime package as a support class.
FragmentHelperClass.Fragment fragment = fragmentHelperClass
.openFragment(n, methodNesting);
ServletWriter outSave = out;
out = fragment.getGenBuffer().getOut();
String tmpParent = parent;
parent = "_jspx_parent";
boolean isSimpleTagParentSave = isSimpleTagParent;
isSimpleTagParent = true;
boolean tmpIsFragment = isFragment;
isFragment = true;
String pushBodyCountVarSave = pushBodyCountVar;
if (pushBodyCountVar != null) {
// Use a fixed name for push body count, to simplify code gen
pushBodyCountVar = "_jspx_push_body_count";
}
visitBody(n);
out = outSave;
parent = tmpParent;
isSimpleTagParent = isSimpleTagParentSave;
isFragment = tmpIsFragment;
pushBodyCountVar = pushBodyCountVarSave;
fragmentHelperClass.closeFragment(fragment, methodNesting);
// XXX - Need to change pageContext to jspContext if
// we're not in a place where pageContext is defined (e.g.
// in a fragment or in a tag file.
out.print("new " + fragmentHelperClass.getClassName() + "( "
+ fragment.getId() + ", _jspx_page_context, "
+ tagHandlerVar + ", " + pushBodyCountVar + ")");
}
/**
* Generate the code required to obtain the runtime value of the given
* named attribute.
*
* @param n The named attribute node whose value is required
*
* @return The name of the temporary variable the result is stored in.
*
* @throws JasperException If an error
*/
public String generateNamedAttributeValue(Node.NamedAttribute n)
throws JasperException {
String varName = n.getTemporaryVariableName();
// If the only body element for this named attribute node is
// template text, we need not generate an extra call to
// pushBody and popBody. Maybe we can further optimize
// here by getting rid of the temporary variable, but in
// reality it looks like javac does this for us.
Node.Nodes body = n.getBody();
if (body != null) {
boolean templateTextOptimization = false;
if (body.size() == 1) {
Node bodyElement = body.getNode(0);
if (bodyElement instanceof Node.TemplateText) {
templateTextOptimization = true;
out.printil("java.lang.String "
+ varName
+ " = "
+ quote(bodyElement.getText()) + ";");
}
}
// XXX - Another possible optimization would be for
// lone EL expressions (no need to pushBody here either).
if (!templateTextOptimization) {
out.printil("out = _jspx_page_context.pushBody();");
visitBody(n);
out.printil("java.lang.String " + varName + " = "
+ "((jakarta.servlet.jsp.tagext.BodyContent)"
+ "out).getString();");
out.printil("out = _jspx_page_context.popBody();");
}
} else {
// Empty body must be treated as ""
out.printil("java.lang.String " + varName + " = \"\";");
}
return varName;
}
/**
* Similar to generateNamedAttributeValue, but create a JspFragment
* instead.
*
* @param n
* The parent node of the named attribute
* @param tagHandlerVar
* The variable the tag handler is stored in, so the fragment
* knows its parent tag.
* @return The name of the temporary variable the fragment is stored in.
*
* @throws JasperException If an error occurs trying to generate the
* fragment
*/
public String generateNamedAttributeJspFragment(Node.NamedAttribute n,
String tagHandlerVar) throws JasperException {
String varName = n.getTemporaryVariableName();
out.printin("jakarta.servlet.jsp.tagext.JspFragment " + varName
+ " = ");
generateJspFragment(n, tagHandlerVar);
out.println(";");
return varName;
}
}
private static void generateLocalVariables(ServletWriter out, ChildInfoBase n) {
Node.ChildInfo ci = n.getChildInfo();
if (ci.hasUseBean()) {
out.printil("jakarta.servlet.http.HttpSession session = _jspx_page_context.getSession();");
out.printil("jakarta.servlet.ServletContext application = _jspx_page_context.getServletContext();");
}
if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty()
|| ci.hasParamAction()) {
out.printil("jakarta.servlet.http.HttpServletRequest request = (jakarta.servlet.http.HttpServletRequest)_jspx_page_context.getRequest();");
}
if (ci.hasIncludeAction()) {
out.printil("jakarta.servlet.http.HttpServletResponse response = (jakarta.servlet.http.HttpServletResponse)_jspx_page_context.getResponse();");
}
}
/**
* Common part of postamble, shared by both servlets and tag files.
*/
private void genCommonPostamble() {
// Append any methods that were generated in the buffer.
for (GenBuffer methodBuffer : methodsBuffered) {
methodBuffer.adjustJavaLines(out.getJavaLine() - 1);
out.printMultiLn(methodBuffer.toString());
}
// Append the helper class
if (fragmentHelperClass.isUsed()) {
fragmentHelperClass.generatePostamble();
fragmentHelperClass.adjustJavaLines(out.getJavaLine() - 1);
out.printMultiLn(fragmentHelperClass.toString());
}
// Append char array declarations
if (charArrayBuffer != null) {
out.printMultiLn(charArrayBuffer.toString());
}
// Close the class definition
out.popIndent();
out.printil("}");
}
/**
* Generates the ending part of the static portion of the servlet.
*/
private void generatePostamble() {
out.popIndent();
out.printil("} catch (java.lang.Throwable t) {");
out.pushIndent();
out.printil("if (!(t instanceof jakarta.servlet.jsp.SkipPageException)){");
out.pushIndent();
out.printil("out = _jspx_out;");
out.printil("if (out != null && out.getBufferSize() != 0)");
out.pushIndent();
out.printil("try {");
out.pushIndent();
out.printil("if (response.isCommitted()) {");
out.pushIndent();
out.printil("out.flush();");
out.popIndent();
out.printil("} else {");
out.pushIndent();
out.printil("out.clearBuffer();");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("} catch (java.io.IOException e) {}");
out.popIndent();
out.printil("if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);");
out.printil("else throw new ServletException(t);");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("} finally {");
out.pushIndent();
out.printil("_jspxFactory.releasePageContext(_jspx_page_context);");
out.popIndent();
out.printil("}");
// Close the service method
out.popIndent();
out.printil("}");
// Generated methods, helper classes, etc.
genCommonPostamble();
}
/**
* Constructor.
*/
Generator(ServletWriter out, Compiler compiler) throws JasperException {
this.out = out;
methodsBuffered = new ArrayList<>();
charArrayBuffer = null;
err = compiler.getErrorDispatcher();
ctxt = compiler.getCompilationContext();
fragmentHelperClass = new FragmentHelperClass("Helper");
pageInfo = compiler.getPageInfo();
ELInterpreter elInterpreter = null;
try {
elInterpreter = ELInterpreterFactory.getELInterpreter(
compiler.getCompilationContext().getServletContext());
} catch (Exception e) {
err.jspError("jsp.error.el_interpreter_class.instantiation",
e.getMessage());
}
this.elInterpreter = elInterpreter;
StringInterpreter stringInterpreter = null;
try {
stringInterpreter = StringInterpreterFactory.getStringInterpreter(
compiler.getCompilationContext().getServletContext());
} catch (Exception e) {
err.jspError("jsp.error.string_interpreter_class.instantiation",
e.getMessage());
}
this.stringInterpreter = stringInterpreter;
/*
* Temporary hack. If a JSP page uses the "extends" attribute of the
* page directive, the _jspInit() method of the generated servlet class
* will not be called (it is only called for those generated servlets
* that extend HttpJspBase, the default), causing the tag handler pools
* not to be initialized and resulting in a NPE. The JSP spec needs to
* clarify whether containers can override init() and destroy(). For
* now, we just disable tag pooling for pages that use "extends".
*/
if (pageInfo.getExtends(false) == null || ctxt.getOptions().getPoolTagsWithExtends()) {
isPoolingEnabled = ctxt.getOptions().isPoolingEnabled();
} else {
isPoolingEnabled = false;
}
beanInfo = pageInfo.getBeanRepository();
varInfoNames = pageInfo.getVarInfoNames();
breakAtLF = ctxt.getOptions().getMappedFile();
if (isPoolingEnabled) {
tagHandlerPoolNames = new ArrayList<>();
} else {
tagHandlerPoolNames = null;
}
timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
timestampFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
/**
* The main entry for Generator.
*
* @param out
* The servlet output writer
* @param compiler
* The compiler
* @param page
* The input page
*
* @throws JasperException If something goes wrong during generation
*/
public static void generate(ServletWriter out, Compiler compiler,
Node.Nodes page) throws JasperException {
Generator gen = new Generator(out, compiler);
if (gen.isPoolingEnabled) {
gen.compileTagHandlerPoolList(page);
}
gen.generateCommentHeader();
if (gen.ctxt.isTagFile()) {
JasperTagInfo tagInfo = (JasperTagInfo) gen.ctxt.getTagInfo();
gen.generateTagHandlerPreamble(tagInfo, page);
if (gen.ctxt.isPrototypeMode()) {
return;
}
gen.generateXmlProlog(page);
gen.fragmentHelperClass.generatePreamble();
page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out,
gen.methodsBuffered, gen.fragmentHelperClass,
gen.ctxt.getOptions().getUseInstanceManagerForTags()));
gen.generateTagHandlerPostamble(tagInfo);
} else {
gen.generatePreamble(page);
gen.generateXmlProlog(page);
gen.fragmentHelperClass.generatePreamble();
page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out,
gen.methodsBuffered, gen.fragmentHelperClass,
gen.ctxt.getOptions().getUseInstanceManagerForTags()));
gen.generatePostamble();
}
}
private void generateCommentHeader() {
out.println("/*");
out.println(" * Generated by the Jasper component of Apache Tomcat");
out.println(" * Version: " + ctxt.getServletContext().getServerInfo());
if (ctxt.getOptions().getGeneratedJavaAddTimestamp()) {
out.println(" * Generated at: " + timestampFormat.format(new Date()) +
" UTC");
}
out.println(" * Note: The last modified time of this file was set to");
out.println(" * the last modified time of the source file after");
out.println(" * generation to assist with modification tracking.");
out.println(" */");
}
/*
* Generates tag handler preamble.
*/
private void generateTagHandlerPreamble(JasperTagInfo tagInfo,
Node.Nodes tag) throws JasperException {
// Generate package declaration
String className = tagInfo.getTagClassName();
int lastIndex = className.lastIndexOf('.');
String packageName = className.substring(0, lastIndex);
genPreamblePackage(packageName);
className = className.substring(lastIndex + 1);
// Generate imports
genPreambleImports();
// Generate class declaration
out.printin("public final class ");
out.println(className);
out.printil(" extends jakarta.servlet.jsp.tagext.SimpleTagSupport");
out.printin(" implements org.apache.jasper.runtime.JspSourceDependent,");
out.println();
out.printin(" org.apache.jasper.runtime.JspSourceImports");
if (tagInfo.hasDynamicAttributes()) {
out.println(",");
out.printin(" jakarta.servlet.jsp.tagext.DynamicAttributes");
}
out.println(",");
out.printin(" org.apache.jasper.runtime.JspSourceDirectives");
out.println(" {");
out.pushIndent();
/*
* Class body begins here
*/
generateDeclarations(tag);
// Static initializations here
genPreambleStaticInitializers();
out.printil("private jakarta.servlet.jsp.JspContext jspContext;");
// Declare writer used for storing result of fragment/body invocation
// if 'varReader' or 'var' attribute is specified
out.printil("private java.io.Writer _jspx_sout;");
// Class variable declarations
genPreambleClassVariableDeclarations();
generateSetJspContext(tagInfo);
// Tag-handler specific declarations
generateTagHandlerAttributes(tagInfo);
if (tagInfo.hasDynamicAttributes()) {
generateSetDynamicAttribute();
}
// Methods here
genPreambleMethods();
// Now the doTag() method
out.printil("public void doTag() throws jakarta.servlet.jsp.JspException, java.io.IOException {");
if (ctxt.isPrototypeMode()) {
out.printil("}");
out.popIndent();
out.printil("}");
return;
}
out.pushIndent();
/*
* According to the spec, 'pageContext' must not be made available as an
* implicit object in tag files. Declare _jspx_page_context, so we can
* share the code generator with JSPs.
*/
out.printil("jakarta.servlet.jsp.PageContext _jspx_page_context = (jakarta.servlet.jsp.PageContext)jspContext;");
// Declare implicit objects.
out.printil("jakarta.servlet.http.HttpServletRequest request = "
+ "(jakarta.servlet.http.HttpServletRequest) _jspx_page_context.getRequest();");
out.printil("jakarta.servlet.http.HttpServletResponse response = "
+ "(jakarta.servlet.http.HttpServletResponse) _jspx_page_context.getResponse();");
out.printil("jakarta.servlet.http.HttpSession session = _jspx_page_context.getSession();");
out.printil("jakarta.servlet.ServletContext application = _jspx_page_context.getServletContext();");
out.printil("jakarta.servlet.ServletConfig config = _jspx_page_context.getServletConfig();");
out.printil("jakarta.servlet.jsp.JspWriter out = jspContext.getOut();");
out.printil("_jspInit(config);");
// set current JspContext on ELContext
out.printil("jspContext.getELContext().putContext(jakarta.servlet.jsp.JspContext.class,jspContext);");
generatePageScopedVariables(tagInfo);
declareTemporaryScriptingVars(tag);
out.println();
out.printil("try {");
out.pushIndent();
}
private void generateTagHandlerPostamble(TagInfo tagInfo) {
out.popIndent();
// Have to catch Throwable because a classic tag handler
// helper method is declared to throw Throwable.
out.printil("} catch( java.lang.Throwable t ) {");
out.pushIndent();
out.printil("if( t instanceof jakarta.servlet.jsp.SkipPageException )");
out.printil(" throw (jakarta.servlet.jsp.SkipPageException) t;");
out.printil("if( t instanceof java.io.IOException )");
out.printil(" throw (java.io.IOException) t;");
out.printil("if( t instanceof java.lang.IllegalStateException )");
out.printil(" throw (java.lang.IllegalStateException) t;");
out.printil("if( t instanceof jakarta.servlet.jsp.JspException )");
out.printil(" throw (jakarta.servlet.jsp.JspException) t;");
out.printil("throw new jakarta.servlet.jsp.JspException(t);");
out.popIndent();
out.printil("} finally {");
out.pushIndent();
// handle restoring VariableMapper
TagAttributeInfo[] attrInfos = tagInfo.getAttributes();
for (int i = 0; i < attrInfos.length; i++) {
if (attrInfos[i].isDeferredMethod() || attrInfos[i].isDeferredValue()) {
out.printin("_el_variablemapper.setVariable(");
out.print(quote(attrInfos[i].getName()));
out.print(",_el_ve");
out.print(i);
out.println(");");
}
}
// restore nested JspContext on ELContext
out.printil("jspContext.getELContext().putContext(jakarta.servlet.jsp.JspContext.class,super.getJspContext());");
out.printil("((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile();");
if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) {
out.printil("_jspDestroy();");
}
out.popIndent();
out.printil("}");
// Close the doTag method
out.popIndent();
out.printil("}");
// Generated methods, helper classes, etc.
genCommonPostamble();
}
/**
* Generates declarations for tag handler attributes, and defines the getter
* and setter methods for each.
*/
private void generateTagHandlerAttributes(TagInfo tagInfo) {
if (tagInfo.hasDynamicAttributes()) {
out.printil("private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();");
}
// Declare attributes
TagAttributeInfo[] attrInfos = tagInfo.getAttributes();
for (TagAttributeInfo info : attrInfos) {
out.printin("private ");
if (info.isFragment()) {
out.print("jakarta.servlet.jsp.tagext.JspFragment ");
} else {
out.print(JspUtil.toJavaSourceType(info.getTypeName()));
out.print(" ");
}
out.print(JspUtil.makeJavaIdentifierForAttribute(
info.getName()));
out.println(";");
}
out.println();
// Define attribute getter and setter methods
for (TagAttributeInfo attrInfo : attrInfos) {
String javaName =
JspUtil.makeJavaIdentifierForAttribute(attrInfo.getName());
// getter method
out.printin("public ");
if (attrInfo.isFragment()) {
out.print("jakarta.servlet.jsp.tagext.JspFragment ");
} else {
out.print(JspUtil.toJavaSourceType(attrInfo.getTypeName()));
out.print(" ");
}
out.print(toGetterMethod(attrInfo.getName()));
out.println(" {");
out.pushIndent();
out.printin("return this.");
out.print(javaName);
out.println(";");
out.popIndent();
out.printil("}");
out.println();
// setter method
out.printin("public void ");
out.print(toSetterMethodName(attrInfo.getName()));
if (attrInfo.isFragment()) {
out.print("(jakarta.servlet.jsp.tagext.JspFragment ");
} else {
out.print("(");
out.print(JspUtil.toJavaSourceType(attrInfo.getTypeName()));
out.print(" ");
}
out.print(javaName);
out.println(") {");
out.pushIndent();
out.printin("this.");
out.print(javaName);
out.print(" = ");
out.print(javaName);
out.println(";");
// Tag files should also set jspContext attributes
// Only called for tag files so always set the jspContext
out.printin("jspContext.setAttribute(\"");
out.print(attrInfo.getName());
out.print("\", ");
out.print(javaName);
out.println(");");
out.popIndent();
out.printil("}");
out.println();
}
}
/*
* Generate setter for JspContext so we can create a wrapper and store both
* the original and the wrapper. We need the wrapper to mask the page
* context from the tag file and simulate a fresh page context. We need the
* original to do things like sync AT_BEGIN and AT_END scripting variables.
*/
private void generateSetJspContext(TagInfo tagInfo) {
boolean nestedSeen = false;
boolean atBeginSeen = false;
boolean atEndSeen = false;
// Determine if there are any aliases
boolean aliasSeen = false;
TagVariableInfo[] tagVars = tagInfo.getTagVariableInfos();
for (TagVariableInfo var : tagVars) {
// If a tag file uses a named attribute, the TagFileDirectiveVisitor
// will ensure that an alias is configured.
if (var.getNameFromAttribute() != null) {
aliasSeen = true;
break;
}
}
if (aliasSeen) {
out.printil("public void setJspContext(jakarta.servlet.jsp.JspContext ctx, java.util.Map aliasMap) {");
} else {
out.printil("public void setJspContext(jakarta.servlet.jsp.JspContext ctx) {");
}
out.pushIndent();
out.printil("super.setJspContext(ctx);");
out.printil("java.util.ArrayList _jspx_nested = null;");
out.printil("java.util.ArrayList _jspx_at_begin = null;");
out.printil("java.util.ArrayList _jspx_at_end = null;");
for (TagVariableInfo tagVar : tagVars) {
switch (tagVar.getScope()) {
case VariableInfo.NESTED:
if (!nestedSeen) {
out.printil("_jspx_nested = new java.util.ArrayList();");
nestedSeen = true;
}
out.printin("_jspx_nested.add(");
break;
case VariableInfo.AT_BEGIN:
if (!atBeginSeen) {
out.printil("_jspx_at_begin = new java.util.ArrayList();");
atBeginSeen = true;
}
out.printin("_jspx_at_begin.add(");
break;
case VariableInfo.AT_END:
if (!atEndSeen) {
out.printil("_jspx_at_end = new java.util.ArrayList();");
atEndSeen = true;
}
out.printin("_jspx_at_end.add(");
break;
} // switch
out.print(quote(tagVar.getNameGiven()));
out.println(");");
}
if (aliasSeen) {
out.printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(this, ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, aliasMap);");
} else {
out.printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(this, ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null);");
}
out.popIndent();
out.printil("}");
out.println();
out.printil("public jakarta.servlet.jsp.JspContext getJspContext() {");
out.pushIndent();
out.printil("return this.jspContext;");
out.popIndent();
out.printil("}");
}
/*
* Generates implementation of
* jakarta.servlet.jsp.tagext.DynamicAttributes.setDynamicAttribute() method,
* which saves each dynamic attribute that is passed in so that a scoped
* variable can later be created for it.
*/
public void generateSetDynamicAttribute() {
out.printil("public void setDynamicAttribute(java.lang.String uri, java.lang.String localName, java.lang.Object value) throws jakarta.servlet.jsp.JspException {");
out.pushIndent();
/*
* According to the spec, only dynamic attributes with no uri are to be
* present in the Map; all other dynamic attributes are ignored.
*/
out.printil("if (uri == null)");
out.pushIndent();
out.printil("_jspx_dynamic_attrs.put(localName, value);");
out.popIndent();
out.popIndent();
out.printil("}");
}
/*
* Creates a page-scoped variable for each declared tag attribute. Also, if
* the tag accepts dynamic attributes, a page-scoped variable is made
* available for each dynamic attribute that was passed in.
*/
private void generatePageScopedVariables(JasperTagInfo tagInfo) {
// "normal" attributes
TagAttributeInfo[] attrInfos = tagInfo.getAttributes();
boolean variableMapperVar = false;
for (int i = 0; i < attrInfos.length; i++) {
String attrName = attrInfos[i].getName();
// handle assigning deferred vars to VariableMapper, storing
// previous values under '_el_ve[i]' for later re-assignment
if (attrInfos[i].isDeferredValue() || attrInfos[i].isDeferredMethod()) {
// we need to scope the modified VariableMapper for consistency and performance
if (!variableMapperVar) {
out.printil("jakarta.el.VariableMapper _el_variablemapper = jspContext.getELContext().getVariableMapper();");
variableMapperVar = true;
}
out.printin("jakarta.el.ValueExpression _el_ve");
out.print(i);
out.print(" = _el_variablemapper.setVariable(");
out.print(quote(attrName));
out.print(',');
if (attrInfos[i].isDeferredMethod()) {
out.print("_jsp_getExpressionFactory().createValueExpression(");
out.print(toGetterMethod(attrName));
out.print(",jakarta.el.MethodExpression.class)");
} else {
out.print(toGetterMethod(attrName));
}
out.println(");");
} else {
out.printil("if( " + toGetterMethod(attrName) + " != null ) ");
out.pushIndent();
out.printin("_jspx_page_context.setAttribute(");
out.print(quote(attrName));
out.print(", ");
out.print(toGetterMethod(attrName));
out.println(");");
out.popIndent();
}
}
// Expose the Map containing dynamic attributes as a page-scoped var
if (tagInfo.hasDynamicAttributes()) {
out.printin("_jspx_page_context.setAttribute(\"");
out.print(tagInfo.getDynamicAttributesMapName());
out.print("\", _jspx_dynamic_attrs);");
}
}
/*
* Generates the getter method for the given attribute name.
*/
private String toGetterMethod(String attrName) {
char[] attrChars = attrName.toCharArray();
attrChars[0] = Character.toUpperCase(attrChars[0]);
return "get" + new String(attrChars) + "()";
}
/*
* Generates the setter method name for the given attribute name.
*/
private String toSetterMethodName(String attrName) {
char[] attrChars = attrName.toCharArray();
attrChars[0] = Character.toUpperCase(attrChars[0]);
return "set" + new String(attrChars);
}
/**
* Class storing the result of introspecting a custom tag handler.
*/
private static class TagHandlerInfo {
private Map<String, Method> methodMaps;
private Map<String, Class<?>> propertyEditorMaps;
private Class<?> tagHandlerClass;
/**
* Constructor.
*
* @param n
* The custom tag whose tag handler class is to be
* introspected
* @param tagHandlerClass
* Tag handler class
* @param err
* Error dispatcher
*/
TagHandlerInfo(Node n, Class<?> tagHandlerClass,
ErrorDispatcher err) throws JasperException {
this.tagHandlerClass = tagHandlerClass;
this.methodMaps = new HashMap<>();
this.propertyEditorMaps = new HashMap<>();
try {
BeanInfo tagClassInfo = Introspector.getBeanInfo(tagHandlerClass);
PropertyDescriptor[] pd = tagClassInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : pd) {
/*
* FIXME: should probably be checking for things like
* pageContext, bodyContent, and parent here -akv
*/
if (propertyDescriptor.getWriteMethod() != null) {
methodMaps.put(propertyDescriptor.getName(), propertyDescriptor.getWriteMethod());
}
if (propertyDescriptor.getPropertyEditorClass() != null) {
propertyEditorMaps.put(propertyDescriptor.getName(), propertyDescriptor
.getPropertyEditorClass());
}
}
} catch (IntrospectionException ie) {
// Likely unreachable code
// When last checked (May 2021), current versions of Java only
// throw IntrospectionException for the 2-arg version of
// getBeanInfo if the stop class is not a super class of the
// bean class. That does not apply here.
err.jspError(n, ie, "jsp.error.introspect.taghandler", tagHandlerClass.getName());
}
}
public Method getSetterMethod(String attrName) {
return methodMaps.get(attrName);
}
public Class<?> getPropertyEditorClass(String attrName) {
return propertyEditorMaps.get(attrName);
}
public Class<?> getTagHandlerClass() {
return tagHandlerClass;
}
}
/**
* A class for generating codes to a buffer. Included here are some support
* for tracking source to Java lines mapping.
*/
private static class GenBuffer {
/*
* For a CustomTag, the codes that are generated at the beginning of the
* tag may not be in the same buffer as those for the body of the tag.
* Two fields are used here to keep this straight. For codes that do not
* corresponds to any JSP lines, they should be null.
*/
private Node node;
private Node.Nodes body;
private java.io.CharArrayWriter charWriter;
protected ServletWriter out;
GenBuffer() {
this(null, null);
}
GenBuffer(Node n, Node.Nodes b) {
node = n;
body = b;
if (body != null) {
body.setGeneratedInBuffer(true);
}
charWriter = new java.io.CharArrayWriter();
out = new ServletWriter(new java.io.PrintWriter(charWriter));
}
public ServletWriter getOut() {
return out;
}
@Override
public String toString() {
return charWriter.toString();
}
/**
* Adjust the Java Lines. This is necessary because the Java lines
* stored with the nodes are relative the beginning of this buffer and
* need to be adjusted when this buffer is inserted into the source.
*
* @param offset The offset to apply to the start line and end line of
* and Java lines of nodes in this buffer
*/
public void adjustJavaLines(final int offset) {
if (node != null) {
adjustJavaLine(node, offset);
}
if (body != null) {
try {
body.visit(new Node.Visitor() {
@Override
public void doVisit(Node n) {
adjustJavaLine(n, offset);
}
@Override
public void visit(Node.CustomTag n)
throws JasperException {
Node.Nodes b = n.getBody();
if (b != null && !b.isGeneratedInBuffer()) {
// Don't adjust lines for the nested tags that
// are also generated in buffers, because the
// adjustments will be done elsewhere.
b.visit(this);
}
}
});
} catch (JasperException ex) {
// Ignore
}
}
}
private static void adjustJavaLine(Node n, int offset) {
if (n.getBeginJavaLine() > 0) {
n.setBeginJavaLine(n.getBeginJavaLine() + offset);
n.setEndJavaLine(n.getEndJavaLine() + offset);
}
}
}
/**
* Keeps track of the generated Fragment Helper Class
*/
private static class FragmentHelperClass {
private static class Fragment {
private GenBuffer genBuffer;
private int id;
Fragment(int id, Node node) {
this.id = id;
genBuffer = new GenBuffer(null, node.getBody());
}
public GenBuffer getGenBuffer() {
return this.genBuffer;
}
public int getId() {
return this.id;
}
}
// True if the helper class should be generated.
private boolean used = false;
private List<Fragment> fragments = new ArrayList<>();
private String className;
// Buffer for entire helper class
private GenBuffer classBuffer = new GenBuffer();
FragmentHelperClass(String className) {
this.className = className;
}
public String getClassName() {
return this.className;
}
public boolean isUsed() {
return this.used;
}
public void generatePreamble() {
ServletWriter out = this.classBuffer.getOut();
out.println();
out.pushIndent();
// Note: cannot be static, as we need to reference things like
// _jspx_meth_*
out.printil("private class " + className);
out.printil(" extends "
+ "org.apache.jasper.runtime.JspFragmentHelper");
out.printil("{");
out.pushIndent();
out.printil("private jakarta.servlet.jsp.tagext.JspTag _jspx_parent;");
out.printil("private int[] _jspx_push_body_count;");
out.println();
out.printil("public " + className
+ "( int discriminator, jakarta.servlet.jsp.JspContext jspContext, "
+ "jakarta.servlet.jsp.tagext.JspTag _jspx_parent, "
+ "int[] _jspx_push_body_count ) {");
out.pushIndent();
out.printil("super( discriminator, jspContext, _jspx_parent );");
out.printil("this._jspx_parent = _jspx_parent;");
out.printil("this._jspx_push_body_count = _jspx_push_body_count;");
out.popIndent();
out.printil("}");
}
public Fragment openFragment(ChildInfoBase parent, int methodNesting) {
Fragment result = new Fragment(fragments.size(), parent);
fragments.add(result);
this.used = true;
parent.setInnerClassName(className);
ServletWriter out = result.getGenBuffer().getOut();
out.pushIndent();
out.pushIndent();
// XXX - Returns boolean because if a tag is invoked from
// within this fragment, the Generator sometimes might
// generate code like "return true". This is ignored for now,
// meaning only the fragment is skipped. The JSR-152
// expert group is currently discussing what to do in this case.
// See comment in closeFragment()
if (methodNesting > 0) {
out.printin("public boolean invoke");
} else {
out.printin("public void invoke");
}
out.println(result.getId() + "( " + "jakarta.servlet.jsp.JspWriter out ) ");
out.pushIndent();
// Note: Throwable required because methods like _jspx_meth_*
// throw Throwable.
out.printil("throws java.lang.Throwable");
out.popIndent();
out.printil("{");
out.pushIndent();
generateLocalVariables(out, parent);
return result;
}
public void closeFragment(Fragment fragment, int methodNesting) {
ServletWriter out = fragment.getGenBuffer().getOut();
// XXX - See comment in openFragment()
if (methodNesting > 0) {
out.printil("return false;");
} else {
out.printil("return;");
}
out.popIndent();
out.printil("}");
}
public void generatePostamble() {
ServletWriter out = this.classBuffer.getOut();
// Generate all fragment methods:
for (Fragment fragment : fragments) {
fragment.getGenBuffer().adjustJavaLines(out.getJavaLine() - 1);
out.printMultiLn(fragment.getGenBuffer().toString());
}
// Generate postamble:
out.printil("public void invoke( java.io.Writer writer )");
out.pushIndent();
out.printil("throws jakarta.servlet.jsp.JspException");
out.popIndent();
out.printil("{");
out.pushIndent();
out.printil("jakarta.servlet.jsp.JspWriter out = null;");
out.printil("if( writer != null ) {");
out.pushIndent();
out.printil("out = this.jspContext.pushBody(writer);");
out.popIndent();
out.printil("} else {");
out.pushIndent();
out.printil("out = this.jspContext.getOut();");
out.popIndent();
out.printil("}");
out.printil("try {");
out.pushIndent();
out.printil("Object _jspx_saved_JspContext = this.jspContext.getELContext().getContext(jakarta.servlet.jsp.JspContext.class);");
out.printil("this.jspContext.getELContext().putContext(jakarta.servlet.jsp.JspContext.class,this.jspContext);");
out.printil("switch( this.discriminator ) {");
out.pushIndent();
for (int i = 0; i < fragments.size(); i++) {
out.printil("case " + i + ":");
out.pushIndent();
out.printil("invoke" + i + "( out );");
out.printil("break;");
out.popIndent();
}
out.popIndent();
out.printil("}"); // switch
// restore nested JspContext on ELContext
out.printil("jspContext.getELContext().putContext(jakarta.servlet.jsp.JspContext.class,_jspx_saved_JspContext);");
out.popIndent();
out.printil("}"); // try
out.printil("catch( java.lang.Throwable e ) {");
out.pushIndent();
out.printil("if (e instanceof jakarta.servlet.jsp.SkipPageException)");
out.printil(" throw (jakarta.servlet.jsp.SkipPageException) e;");
out.printil("throw new jakarta.servlet.jsp.JspException( e );");
out.popIndent();
out.printil("}"); // catch
out.printil("finally {");
out.pushIndent();
out.printil("if( writer != null ) {");
out.pushIndent();
out.printil("this.jspContext.popBody();");
out.popIndent();
out.printil("}");
out.popIndent();
out.printil("}"); // finally
out.popIndent();
out.printil("}"); // invoke method
out.popIndent();
out.printil("}"); // helper class
out.popIndent();
}
@Override
public String toString() {
return classBuffer.toString();
}
public void adjustJavaLines(int offset) {
for (Fragment fragment : fragments) {
fragment.getGenBuffer().adjustJavaLines(offset);
}
}
}
}
| apache/tomcat | java/org/apache/jasper/compiler/Generator.java |
2,790 | package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;
/**
* @author Benjamin Winterberg
*/
public class LongAdder1 {
private static final int NUM_INCREMENTS = 10000;
private static LongAdder adder = new LongAdder();
public static void main(String[] args) {
testIncrement();
testAdd();
}
private static void testAdd() {
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, NUM_INCREMENTS)
.forEach(i -> executor.submit(() -> adder.add(2)));
ConcurrentUtils.stop(executor);
System.out.format("Add: %d\n", adder.sumThenReset());
}
private static void testIncrement() {
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, NUM_INCREMENTS)
.forEach(i -> executor.submit(adder::increment));
ConcurrentUtils.stop(executor);
System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, adder.sumThenReset());
}
}
| winterbe/java8-tutorial | src/com/winterbe/java8/samples/concurrent/LongAdder1.java |
2,791 | /*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.Objects;
// Maps Class instances to values of type T. Under memory pressure, the
// mapping is released (under soft references GC policy) and would be
// recomputed the next time it is queried. The mapping is bound to the
// lifetime of the class: when the class is unloaded, the mapping is
// removed too.
abstract class ClassCache<T> {
private static class CacheRef<T> extends SoftReference<T> {
private final Class<?> type;
// This field is deliberately accessed without sychronization. ClassValue
// provides synchronization when CacheRef is published. However, when
// a thread reads this field, while another thread is clearing the field, it
// would formally constitute a data race. But that data race is benign, and
// fixing it could introduce noticeable performance penalty, see JDK-8309688.
private T strongReferent;
CacheRef(T referent, ReferenceQueue<T> queue, Class<?> type) {
super(referent, queue);
this.type = type;
this.strongReferent = referent;
}
Class<?> getType() {
return type;
}
T getStrong() {
return strongReferent;
}
void clearStrong() {
strongReferent = null;
}
}
private final ReferenceQueue<T> queue;
private final ClassValue<CacheRef<T>> map;
protected abstract T computeValue(Class<?> cl);
protected ClassCache() {
queue = new ReferenceQueue<>();
map = new ClassValue<>() {
@Override
protected CacheRef<T> computeValue(Class<?> type) {
T v = ClassCache.this.computeValue(type);
Objects.requireNonNull(v);
return new CacheRef<>(v, queue, type);
}
};
}
T get(Class<?> cl) {
while (true) {
processQueue();
CacheRef<T> ref = map.get(cl);
// Case 1: A recently created CacheRef.
// We might still have strong referent, and can return it.
// This guarantees progress for at least one thread on every CacheRef.
// Clear the strong referent before returning to make the cache soft.
T strongVal = ref.getStrong();
if (strongVal != null) {
ref.clearStrong();
return strongVal;
}
// Case 2: Older or recently cleared CacheRef.
// Check if its soft referent is still available, and return it.
T val = ref.get();
if (val != null) {
return val;
}
// Case 3: The reference was cleared.
// Clear the mapping and retry.
map.remove(cl);
}
}
private void processQueue() {
Reference<? extends T> ref;
while((ref = queue.poll()) != null) {
CacheRef<? extends T> cacheRef = (CacheRef<? extends T>)ref;
map.remove(cacheRef.getType());
}
}
}
| openjdk/jdk | src/java.base/share/classes/java/io/ClassCache.java |
2,792 | /*
* Copyright (C) 2009-2023 Lightbend Inc. <https://www.lightbend.com>
*/
package akka.actor;
import akka.util.Unsafe;
final class AbstractActorRef {
static final long cellOffset;
static final long lookupOffset;
static {
try {
cellOffset =
Unsafe.instance.objectFieldOffset(
RepointableActorRef.class.getDeclaredField("_cellDoNotCallMeDirectly"));
lookupOffset =
Unsafe.instance.objectFieldOffset(
RepointableActorRef.class.getDeclaredField("_lookupDoNotCallMeDirectly"));
} catch (Throwable t) {
throw new ExceptionInInitializerError(t);
}
}
}
| akka/akka | akka-actor/src/main/java/akka/actor/AbstractActorRef.java |
2,793 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.reflect;
import com.google.common.collect.ForwardingMap;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import java.util.Map;
import javax.annotation.CheckForNull;
/**
* A type-to-instance map backed by an {@link ImmutableMap}. See also {@link
* MutableTypeToInstanceMap}.
*
* @author Ben Yu
* @since 13.0
*/
@ElementTypesAreNonnullByDefault
public final class ImmutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<? extends B>, B>
implements TypeToInstanceMap<B> {
/** Returns an empty type to instance map. */
public static <B> ImmutableTypeToInstanceMap<B> of() {
return new ImmutableTypeToInstanceMap<>(ImmutableMap.<TypeToken<? extends B>, B>of());
}
/** Returns a new builder. */
public static <B> Builder<B> builder() {
return new Builder<>();
}
/**
* A builder for creating immutable type-to-instance maps. Example:
*
* <pre>{@code
* static final ImmutableTypeToInstanceMap<Handler<?>> HANDLERS =
* ImmutableTypeToInstanceMap.<Handler<?>>builder()
* .put(new TypeToken<Handler<Foo>>() {}, new FooHandler())
* .put(new TypeToken<Handler<Bar>>() {}, new SubBarHandler())
* .build();
* }</pre>
*
* <p>After invoking {@link #build()} it is still possible to add more entries and build again.
* Thus each map generated by this builder will be a superset of any map generated before it.
*
* @since 13.0
*/
public static final class Builder<B> {
private final ImmutableMap.Builder<TypeToken<? extends B>, B> mapBuilder =
ImmutableMap.builder();
private Builder() {}
/**
* Associates {@code key} with {@code value} in the built map. Duplicate keys are not allowed,
* and will cause {@link #build} to fail.
*/
@CanIgnoreReturnValue
public <T extends B> Builder<B> put(Class<T> key, T value) {
mapBuilder.put(TypeToken.of(key), value);
return this;
}
/**
* Associates {@code key} with {@code value} in the built map. Duplicate keys are not allowed,
* and will cause {@link #build} to fail.
*/
@CanIgnoreReturnValue
public <T extends B> Builder<B> put(TypeToken<T> key, T value) {
mapBuilder.put(key.rejectTypeVariables(), value);
return this;
}
/**
* Returns a new immutable type-to-instance map containing the entries provided to this builder.
*
* @throws IllegalArgumentException if duplicate keys were added
*/
public ImmutableTypeToInstanceMap<B> build() {
return new ImmutableTypeToInstanceMap<>(mapBuilder.buildOrThrow());
}
}
private final ImmutableMap<TypeToken<? extends B>, B> delegate;
private ImmutableTypeToInstanceMap(ImmutableMap<TypeToken<? extends B>, B> delegate) {
this.delegate = delegate;
}
@Override
@CheckForNull
public <T extends B> T getInstance(TypeToken<T> type) {
return trustedGet(type.rejectTypeVariables());
}
@Override
@CheckForNull
public <T extends B> T getInstance(Class<T> type) {
return trustedGet(TypeToken.of(type));
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @deprecated unsupported operation
* @throws UnsupportedOperationException always
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
public <T extends B> T putInstance(TypeToken<T> type, T value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @deprecated unsupported operation
* @throws UnsupportedOperationException always
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
public <T extends B> T putInstance(Class<T> type, T value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @deprecated unsupported operation
* @throws UnsupportedOperationException always
*/
@CanIgnoreReturnValue
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
@CheckForNull
public B put(TypeToken<? extends B> key, B value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @deprecated unsupported operation
* @throws UnsupportedOperationException always
*/
@Deprecated
@Override
@DoNotCall("Always throws UnsupportedOperationException")
public void putAll(Map<? extends TypeToken<? extends B>, ? extends B> map) {
throw new UnsupportedOperationException();
}
@Override
protected Map<TypeToken<? extends B>, B> delegate() {
return delegate;
}
@SuppressWarnings("unchecked") // value could not get in if not a T
@CheckForNull
private <T extends B> T trustedGet(TypeToken<T> type) {
return (T) delegate.get(type);
}
}
| google/guava | guava/src/com/google/common/reflect/ImmutableTypeToInstanceMap.java |
2,794 | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Equivalence;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Ticker;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedMultiset;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.LinkedHashMultiset;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.collect.RowSortedTable;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.SortedMultiset;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import com.google.common.collect.TreeMultiset;
import com.google.common.primitives.Primitives;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import com.google.common.reflect.AbstractInvocationHandler;
import com.google.common.reflect.Invokable;
import com.google.common.reflect.Parameter;
import com.google.common.reflect.Reflection;
import com.google.common.reflect.TypeToken;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Currency;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Generates fresh instances of types that are different from each other (if possible).
*
* @author Ben Yu
*/
@GwtIncompatible
@J2ktIncompatible
class FreshValueGenerator {
private static final ImmutableMap<Class<?>, Method> GENERATORS;
static {
ImmutableMap.Builder<Class<?>, Method> builder = ImmutableMap.builder();
for (Method method : FreshValueGenerator.class.getDeclaredMethods()) {
if (method.isAnnotationPresent(Generates.class)) {
builder.put(method.getReturnType(), method);
}
}
GENERATORS = builder.buildOrThrow();
}
private static final ImmutableMap<Class<?>, Method> EMPTY_GENERATORS;
static {
ImmutableMap.Builder<Class<?>, Method> builder = ImmutableMap.builder();
for (Method method : FreshValueGenerator.class.getDeclaredMethods()) {
if (method.isAnnotationPresent(Empty.class)) {
builder.put(method.getReturnType(), method);
}
}
EMPTY_GENERATORS = builder.buildOrThrow();
}
private final AtomicInteger freshness = new AtomicInteger(1);
private final ListMultimap<Class<?>, Object> sampleInstances = ArrayListMultimap.create();
/**
* The freshness level at which the {@link Empty @Empty} annotated method was invoked to generate
* instance.
*/
private final Map<Type, Integer> emptyInstanceGenerated = new HashMap<>();
final <T> void addSampleInstances(Class<T> type, Iterable<? extends T> instances) {
sampleInstances.putAll(checkNotNull(type), checkNotNull(instances));
}
/**
* Returns a fresh instance for {@code type} if possible. The returned instance could be:
*
* <ul>
* <li>exactly of the given type, including generic type parameters, such as {@code
* ImmutableList<String>};
* <li>of the raw type;
* <li>null if no value can be generated.
* </ul>
*/
final @Nullable Object generateFresh(TypeToken<?> type) {
Object generated = generate(type);
if (generated != null) {
freshness.incrementAndGet();
}
return generated;
}
final <T> @Nullable T generateFresh(Class<T> type) {
return Primitives.wrap(type).cast(generateFresh(TypeToken.of(type)));
}
final <T> T newFreshProxy(final Class<T> interfaceType) {
T proxy = newProxy(interfaceType);
freshness.incrementAndGet();
return proxy;
}
/**
* Generates an instance for {@code type} using the current {@link #freshness}. The generated
* instance may or may not be unique across different calls.
*/
private @Nullable Object generate(TypeToken<?> type) {
Class<?> rawType = type.getRawType();
List<Object> samples = sampleInstances.get(rawType);
Object sample = pickInstance(samples, null);
if (sample != null) {
return sample;
}
if (rawType.isEnum()) {
return pickInstance(rawType.getEnumConstants(), null);
}
if (type.isArray()) {
TypeToken<?> componentType = requireNonNull(type.getComponentType());
Object array = Array.newInstance(componentType.getRawType(), 1);
Array.set(array, 0, generate(componentType));
return array;
}
Method emptyGenerate = EMPTY_GENERATORS.get(rawType);
if (emptyGenerate != null) {
if (emptyInstanceGenerated.containsKey(type.getType())) {
// empty instance already generated
if (emptyInstanceGenerated.get(type.getType()).intValue() == freshness.get()) {
// same freshness, generate again.
return invokeGeneratorMethod(emptyGenerate);
} else {
// Cannot use empty generator. Proceed with other generators.
}
} else {
// never generated empty instance for this type before.
Object emptyInstance = invokeGeneratorMethod(emptyGenerate);
emptyInstanceGenerated.put(type.getType(), freshness.get());
return emptyInstance;
}
}
Method generate = GENERATORS.get(rawType);
if (generate != null) {
ImmutableList<Parameter> params = Invokable.from(generate).getParameters();
List<Object> args = Lists.newArrayListWithCapacity(params.size());
TypeVariable<?>[] typeVars = rawType.getTypeParameters();
for (int i = 0; i < params.size(); i++) {
TypeToken<?> paramType = type.resolveType(typeVars[i]);
// We require all @Generates methods to either be parameter-less or accept non-null
// values for their generic parameter types.
Object argValue = generate(paramType);
if (argValue == null) {
// When a parameter of a @Generates method cannot be created,
// The type most likely is a collection.
// Our distinct proxy doesn't work for collections.
// So just refuse to generate.
return null;
}
args.add(argValue);
}
return invokeGeneratorMethod(generate, args.toArray());
}
return defaultGenerate(rawType);
}
private <T> @Nullable T defaultGenerate(Class<T> rawType) {
if (rawType.isInterface()) {
// always create a new proxy
return newProxy(rawType);
}
return ArbitraryInstances.get(rawType);
}
private <T> T newProxy(final Class<T> interfaceType) {
return Reflection.newProxy(interfaceType, new FreshInvocationHandler(interfaceType));
}
private Object invokeGeneratorMethod(Method generator, Object... args) {
try {
return generator.invoke(this, args);
} catch (InvocationTargetException e) {
throwIfUnchecked(e.getCause());
throw new RuntimeException(e.getCause());
} catch (Exception e) {
throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
private final class FreshInvocationHandler extends AbstractInvocationHandler {
private final int identity = generateInt();
private final Class<?> interfaceType;
FreshInvocationHandler(Class<?> interfaceType) {
this.interfaceType = interfaceType;
}
@Override
@CheckForNull
protected Object handleInvocation(Object proxy, Method method, @Nullable Object[] args) {
return interfaceMethodCalled(interfaceType, method);
}
@Override
public int hashCode() {
return identity;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof FreshInvocationHandler) {
FreshInvocationHandler that = (FreshInvocationHandler) obj;
return identity == that.identity;
}
return false;
}
@Override
public String toString() {
return paramString(interfaceType, identity);
}
}
/** Subclasses can override to provide different return value for proxied interface methods. */
@CheckForNull
Object interfaceMethodCalled(Class<?> interfaceType, Method method) {
throw new UnsupportedOperationException();
}
private <T> T pickInstance(T[] instances, T defaultValue) {
return pickInstance(Arrays.asList(instances), defaultValue);
}
private <T> T pickInstance(Collection<T> instances, T defaultValue) {
if (instances.isEmpty()) {
return defaultValue;
}
// generateInt() is 1-based.
return Iterables.get(instances, (generateInt() - 1) % instances.size());
}
private static String paramString(Class<?> type, int i) {
return type.getSimpleName() + '@' + i;
}
/**
* Annotates a method to be the instance generator of a certain type. The return type is the
* generated type. The method parameters correspond to the generated type's type parameters. For
* example, if the annotated method returns {@code Map<K, V>}, the method signature should be:
* {@code Map<K, V> generateMap(K key, V value)}.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
private @interface Generates {}
/**
* Annotates a method to generate the "empty" instance of a collection. This method should accept
* no parameter. The value it generates should be unequal to the values generated by methods
* annotated with {@link Generates}.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
private @interface Empty {}
@Generates
Class<?> generateClass() {
return pickInstance(
ImmutableList.of(
int.class, long.class, void.class, Object.class, Object[].class, Iterable.class),
Object.class);
}
@Generates
Object generateObject() {
return generateString();
}
@Generates
Number generateNumber() {
return generateInt();
}
@Generates
int generateInt() {
return freshness.get();
}
@SuppressWarnings("removal") // b/321209431 -- maybe just use valueOf here?
@Generates
Integer generateInteger() {
return new Integer(generateInt());
}
@Generates
long generateLong() {
return generateInt();
}
@SuppressWarnings("removal") // b/321209431 -- maybe just use valueOf here?
@Generates
Long generateLongObject() {
return new Long(generateLong());
}
@Generates
float generateFloat() {
return generateInt();
}
@SuppressWarnings("removal") // b/321209431 -- maybe just use valueOf here?
@Generates
Float generateFloatObject() {
return new Float(generateFloat());
}
@Generates
double generateDouble() {
return generateInt();
}
@SuppressWarnings("removal") // b/321209431 -- maybe just use valueOf here?
@Generates
Double generateDoubleObject() {
return new Double(generateDouble());
}
@Generates
short generateShort() {
return (short) generateInt();
}
@SuppressWarnings("removal") // b/321209431 -- maybe just use valueOf here?
@Generates
Short generateShortObject() {
return new Short(generateShort());
}
@Generates
byte generateByte() {
return (byte) generateInt();
}
@SuppressWarnings("removal") // b/321209431 -- maybe just use valueOf here?
@Generates
Byte generateByteObject() {
return new Byte(generateByte());
}
@Generates
char generateChar() {
return generateString().charAt(0);
}
@SuppressWarnings("removal") // b/321209431 -- maybe just use valueOf here?
@Generates
Character generateCharacter() {
return new Character(generateChar());
}
@Generates
boolean generateBoolean() {
return generateInt() % 2 == 0;
}
@SuppressWarnings("removal") // b/321209431 -- maybe just use valueOf here?
@Generates
Boolean generateBooleanObject() {
return new Boolean(generateBoolean());
}
@Generates
UnsignedInteger generateUnsignedInteger() {
return UnsignedInteger.fromIntBits(generateInt());
}
@Generates
UnsignedLong generateUnsignedLong() {
return UnsignedLong.fromLongBits(generateLong());
}
@Generates
BigInteger generateBigInteger() {
return BigInteger.valueOf(generateInt());
}
@Generates
BigDecimal generateBigDecimal() {
return BigDecimal.valueOf(generateInt());
}
@Generates
CharSequence generateCharSequence() {
return generateString();
}
@Generates
String generateString() {
return Integer.toString(generateInt());
}
@Generates
Comparable<?> generateComparable() {
return generateString();
}
@Generates
Pattern generatePattern() {
return Pattern.compile(generateString());
}
@Generates
Charset generateCharset() {
return pickInstance(Charset.availableCharsets().values(), Charsets.UTF_8);
}
@Generates
Locale generateLocale() {
return pickInstance(Locale.getAvailableLocales(), Locale.US);
}
@Generates
Currency generateCurrency() {
return pickInstance(Currency.getAvailableCurrencies(), Currency.getInstance(Locale.US));
}
// common.base
@Empty
<T> com.google.common.base.Optional<T> generateGoogleOptional() {
return com.google.common.base.Optional.absent();
}
@Generates
<T> com.google.common.base.Optional<T> generateGoogleOptional(T value) {
return com.google.common.base.Optional.of(value);
}
@Generates
Joiner generateJoiner() {
return Joiner.on(generateString());
}
@Generates
Splitter generateSplitter() {
return Splitter.on(generateString());
}
@Generates
<T> Equivalence<T> generateEquivalence() {
return new Equivalence<T>() {
@Override
protected boolean doEquivalent(T a, T b) {
return false;
}
@Override
protected int doHash(T t) {
return 0;
}
final String string = paramString(Equivalence.class, generateInt());
@Override
public String toString() {
return string;
}
};
}
@Generates
CharMatcher generateCharMatcher() {
return new CharMatcher() {
@Override
public boolean matches(char c) {
return false;
}
final String string = paramString(CharMatcher.class, generateInt());
@Override
public String toString() {
return string;
}
};
}
@Generates
Ticker generateTicker() {
return new Ticker() {
@Override
public long read() {
return 0;
}
final String string = paramString(Ticker.class, generateInt());
@Override
public String toString() {
return string;
}
};
}
// collect
@Generates
<T> Comparator<T> generateComparator() {
return generateOrdering();
}
@Generates
<T extends @Nullable Object> Ordering<T> generateOrdering() {
return new Ordering<T>() {
@Override
public int compare(T left, T right) {
return 0;
}
final String string = paramString(Ordering.class, generateInt());
@Override
public String toString() {
return string;
}
};
}
@Empty
static <C extends Comparable<?>> Range<C> generateRange() {
return Range.all();
}
@Generates
static <C extends Comparable<?>> Range<C> generateRange(C freshElement) {
return Range.singleton(freshElement);
}
@Generates
static <E> Iterable<E> generateIterable(@Nullable E freshElement) {
return generateList(freshElement);
}
@Generates
static <E> Collection<E> generateCollection(@Nullable E freshElement) {
return generateList(freshElement);
}
@Generates
static <E> List<E> generateList(@Nullable E freshElement) {
return generateArrayList(freshElement);
}
@Generates
static <E> ArrayList<E> generateArrayList(@Nullable E freshElement) {
ArrayList<E> list = Lists.newArrayList();
list.add(freshElement);
return list;
}
@Generates
static <E> LinkedList<E> generateLinkedList(@Nullable E freshElement) {
LinkedList<E> list = Lists.newLinkedList();
list.add(freshElement);
return list;
}
@Generates
static <E> ImmutableList<E> generateImmutableList(E freshElement) {
return ImmutableList.of(freshElement);
}
@Generates
static <E> ImmutableCollection<E> generateImmutableCollection(E freshElement) {
return generateImmutableList(freshElement);
}
@Generates
static <E> Set<E> generateSet(@Nullable E freshElement) {
return generateHashSet(freshElement);
}
@Generates
static <E> HashSet<E> generateHashSet(@Nullable E freshElement) {
return generateLinkedHashSet(freshElement);
}
@Generates
static <E> LinkedHashSet<E> generateLinkedHashSet(@Nullable E freshElement) {
LinkedHashSet<E> set = Sets.newLinkedHashSet();
set.add(freshElement);
return set;
}
@Generates
static <E> ImmutableSet<E> generateImmutableSet(E freshElement) {
return ImmutableSet.of(freshElement);
}
@Generates
static <E extends Comparable<? super E>> SortedSet<E> generateSortedSet(E freshElement) {
return generateNavigableSet(freshElement);
}
@Generates
static <E extends Comparable<? super E>> NavigableSet<E> generateNavigableSet(E freshElement) {
return generateTreeSet(freshElement);
}
@Generates
static <E extends Comparable<? super E>> TreeSet<E> generateTreeSet(E freshElement) {
TreeSet<E> set = Sets.newTreeSet();
set.add(freshElement);
return set;
}
@Generates
static <E extends Comparable<? super E>> ImmutableSortedSet<E> generateImmutableSortedSet(
E freshElement) {
return ImmutableSortedSet.of(freshElement);
}
@Generates
static <E> Multiset<E> generateMultiset(@Nullable E freshElement) {
return generateHashMultiset(freshElement);
}
@Generates
static <E> HashMultiset<E> generateHashMultiset(@Nullable E freshElement) {
HashMultiset<E> multiset = HashMultiset.create();
multiset.add(freshElement);
return multiset;
}
@Generates
static <E> LinkedHashMultiset<E> generateLinkedHashMultiset(@Nullable E freshElement) {
LinkedHashMultiset<E> multiset = LinkedHashMultiset.create();
multiset.add(freshElement);
return multiset;
}
@Generates
static <E> ImmutableMultiset<E> generateImmutableMultiset(E freshElement) {
return ImmutableMultiset.of(freshElement);
}
@Generates
static <E extends Comparable<E>> SortedMultiset<E> generateSortedMultiset(E freshElement) {
return generateTreeMultiset(freshElement);
}
@Generates
static <E extends Comparable<E>> TreeMultiset<E> generateTreeMultiset(E freshElement) {
TreeMultiset<E> multiset = TreeMultiset.create();
multiset.add(freshElement);
return multiset;
}
@Generates
static <E extends Comparable<E>> ImmutableSortedMultiset<E> generateImmutableSortedMultiset(
E freshElement) {
return ImmutableSortedMultiset.of(freshElement);
}
@Generates
static <K, V> Map<K, V> generateMap(@Nullable K key, @Nullable V value) {
return generateHashdMap(key, value);
}
@Generates
static <K, V> HashMap<K, V> generateHashdMap(@Nullable K key, @Nullable V value) {
return generateLinkedHashMap(key, value);
}
@Generates
static <K, V> LinkedHashMap<K, V> generateLinkedHashMap(@Nullable K key, @Nullable V value) {
LinkedHashMap<K, V> map = Maps.newLinkedHashMap();
map.put(key, value);
return map;
}
@Generates
static <K, V> ImmutableMap<K, V> generateImmutableMap(K key, V value) {
return ImmutableMap.of(key, value);
}
@Empty
static <K, V> ConcurrentMap<K, V> generateConcurrentMap() {
return Maps.newConcurrentMap();
}
@Generates
static <K, V> ConcurrentMap<K, V> generateConcurrentMap(K key, V value) {
ConcurrentMap<K, V> map = Maps.newConcurrentMap();
map.put(key, value);
return map;
}
@Generates
static <K extends Comparable<? super K>, V> SortedMap<K, V> generateSortedMap(
K key, @Nullable V value) {
return generateNavigableMap(key, value);
}
@Generates
static <K extends Comparable<? super K>, V> NavigableMap<K, V> generateNavigableMap(
K key, @Nullable V value) {
return generateTreeMap(key, value);
}
@Generates
static <K extends Comparable<? super K>, V> TreeMap<K, V> generateTreeMap(
K key, @Nullable V value) {
TreeMap<K, V> map = Maps.newTreeMap();
map.put(key, value);
return map;
}
@Generates
static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> generateImmutableSortedMap(
K key, V value) {
return ImmutableSortedMap.of(key, value);
}
@Generates
static <K, V> Multimap<K, V> generateMultimap(@Nullable K key, @Nullable V value) {
return generateListMultimap(key, value);
}
@Generates
static <K, V> ImmutableMultimap<K, V> generateImmutableMultimap(K key, V value) {
return ImmutableMultimap.of(key, value);
}
@Generates
static <K, V> ListMultimap<K, V> generateListMultimap(@Nullable K key, @Nullable V value) {
return generateArrayListMultimap(key, value);
}
@Generates
static <K, V> ArrayListMultimap<K, V> generateArrayListMultimap(
@Nullable K key, @Nullable V value) {
ArrayListMultimap<K, V> multimap = ArrayListMultimap.create();
multimap.put(key, value);
return multimap;
}
@Generates
static <K, V> ImmutableListMultimap<K, V> generateImmutableListMultimap(K key, V value) {
return ImmutableListMultimap.of(key, value);
}
@Generates
static <K, V> SetMultimap<K, V> generateSetMultimap(@Nullable K key, @Nullable V value) {
return generateLinkedHashMultimap(key, value);
}
@Generates
static <K, V> HashMultimap<K, V> generateHashMultimap(@Nullable K key, @Nullable V value) {
HashMultimap<K, V> multimap = HashMultimap.create();
multimap.put(key, value);
return multimap;
}
@Generates
static <K, V> LinkedHashMultimap<K, V> generateLinkedHashMultimap(
@Nullable K key, @Nullable V value) {
LinkedHashMultimap<K, V> multimap = LinkedHashMultimap.create();
multimap.put(key, value);
return multimap;
}
@Generates
static <K, V> ImmutableSetMultimap<K, V> generateImmutableSetMultimap(K key, V value) {
return ImmutableSetMultimap.of(key, value);
}
@Generates
static <K, V> BiMap<K, V> generateBimap(@Nullable K key, @Nullable V value) {
return generateHashBiMap(key, value);
}
@Generates
static <K, V> HashBiMap<K, V> generateHashBiMap(@Nullable K key, @Nullable V value) {
HashBiMap<K, V> bimap = HashBiMap.create();
bimap.put(key, value);
return bimap;
}
@Generates
static <K, V> ImmutableBiMap<K, V> generateImmutableBimap(K key, V value) {
return ImmutableBiMap.of(key, value);
}
@Generates
static <R, C, V> Table<R, C, V> generateTable(R row, C column, V value) {
return generateHashBasedTable(row, column, value);
}
@Generates
static <R, C, V> HashBasedTable<R, C, V> generateHashBasedTable(R row, C column, V value) {
HashBasedTable<R, C, V> table = HashBasedTable.create();
table.put(row, column, value);
return table;
}
@SuppressWarnings("rawtypes") // TreeBasedTable.create() is defined as such
@Generates
static <R extends Comparable, C extends Comparable, V>
RowSortedTable<R, C, V> generateRowSortedTable(R row, C column, V value) {
return generateTreeBasedTable(row, column, value);
}
@SuppressWarnings("rawtypes") // TreeBasedTable.create() is defined as such
@Generates
static <R extends Comparable, C extends Comparable, V>
TreeBasedTable<R, C, V> generateTreeBasedTable(R row, C column, V value) {
TreeBasedTable<R, C, V> table = TreeBasedTable.create();
table.put(row, column, value);
return table;
}
@Generates
static <R, C, V> ImmutableTable<R, C, V> generateImmutableTable(R row, C column, V value) {
return ImmutableTable.of(row, column, value);
}
// common.reflect
@Generates
TypeToken<?> generateTypeToken() {
return TypeToken.of(generateClass());
}
// io types
@Generates
File generateFile() {
return new File(generateString());
}
@Generates
static ByteArrayInputStream generateByteArrayInputStream() {
return new ByteArrayInputStream(new byte[0]);
}
@Generates
static InputStream generateInputStream() {
return generateByteArrayInputStream();
}
@Generates
StringReader generateStringReader() {
return new StringReader(generateString());
}
@Generates
Reader generateReader() {
return generateStringReader();
}
@Generates
Readable generateReadable() {
return generateReader();
}
@Generates
Buffer generateBuffer() {
return generateCharBuffer();
}
@Generates
CharBuffer generateCharBuffer() {
return CharBuffer.allocate(generateInt());
}
@Generates
ByteBuffer generateByteBuffer() {
return ByteBuffer.allocate(generateInt());
}
@Generates
ShortBuffer generateShortBuffer() {
return ShortBuffer.allocate(generateInt());
}
@Generates
IntBuffer generateIntBuffer() {
return IntBuffer.allocate(generateInt());
}
@Generates
LongBuffer generateLongBuffer() {
return LongBuffer.allocate(generateInt());
}
@Generates
FloatBuffer generateFloatBuffer() {
return FloatBuffer.allocate(generateInt());
}
@Generates
DoubleBuffer generateDoubleBuffer() {
return DoubleBuffer.allocate(generateInt());
}
}
| google/guava | android/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java |
2,795 | package org.telegram.messenger;
import java.util.regex.Pattern;
public class LinkifyPort {
private static String IANA_TOP_LEVEL_DOMAINS =
"(?:"
+ "(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active"
+ "|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam"
+ "|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates"
+ "|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])"
+ "|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva"
+ "|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black"
+ "|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique"
+ "|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business"
+ "|buzz|bzh|b[abdefghijmnorstvwyz])"
+ "|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards"
+ "|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo"
+ "|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco"
+ "|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach"
+ "|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos"
+ "|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses"
+ "|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])"
+ "|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta"
+ "|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount"
+ "|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])"
+ "|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises"
+ "|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed"
+ "|express|e[cegrstu])"
+ "|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film"
+ "|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth"
+ "|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi"
+ "|f[ijkmor])"
+ "|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving"
+ "|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger"
+ "|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])"
+ "|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings"
+ "|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai"
+ "|h[kmnrtu])"
+ "|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute"
+ "|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])"
+ "|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])"
+ "|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])"
+ "|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc"
+ "|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live"
+ "|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])"
+ "|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba"
+ "|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda"
+ "|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar"
+ "|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])"
+ "|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk"
+ "|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])"
+ "|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka"
+ "|otsuka|ovh|om)"
+ "|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography"
+ "|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing"
+ "|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property"
+ "|protection|pub|p[aefghklmnrstwy])"
+ "|(?:qpon|quebec|qa)"
+ "|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals"
+ "|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks"
+ "|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])"
+ "|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo"
+ "|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security"
+ "|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski"
+ "|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting"
+ "|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies"
+ "|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])"
+ "|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica"
+ "|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools"
+ "|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])"
+ "|(?:ubs|university|uno|uol|u[agksyz])"
+ "|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin"
+ "|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])"
+ "|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill"
+ "|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])"
+ "|(?:\u03b5\u03bb|\u0431\u0435\u043b|\u0434\u0435\u0442\u0438|\u043a\u043e\u043c|\u043c\u043a\u0434"
+ "|\u043c\u043e\u043d|\u043c\u043e\u0441\u043a\u0432\u0430|\u043e\u043d\u043b\u0430\u0439\u043d"
+ "|\u043e\u0440\u0433|\u0440\u0443\u0441|\u0440\u0444|\u0441\u0430\u0439\u0442|\u0441\u0440\u0431"
+ "|\u0443\u043a\u0440|\u049b\u0430\u0437|\u0570\u0561\u0575|\u05e7\u05d5\u05dd|\u0627\u0631\u0627\u0645\u0643\u0648"
+ "|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629"
+ "|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0627\u06cc\u0631\u0627\u0646"
+ "|\u0628\u0627\u0632\u0627\u0631|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633"
+ "|\u0633\u0648\u062f\u0627\u0646|\u0633\u0648\u0631\u064a\u0629|\u0634\u0628\u0643\u0629"
+ "|\u0639\u0631\u0627\u0642|\u0639\u0645\u0627\u0646|\u0641\u0644\u0633\u0637\u064a\u0646"
+ "|\u0642\u0637\u0631|\u0643\u0648\u0645|\u0645\u0635\u0631|\u0645\u0644\u064a\u0633\u064a\u0627"
+ "|\u0645\u0648\u0642\u0639|\u0915\u0949\u092e|\u0928\u0947\u091f|\u092d\u093e\u0930\u0924"
+ "|\u0938\u0902\u0917\u0920\u0928|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4"
+ "|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd"
+ "|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e04\u0e2d\u0e21|\u0e44\u0e17\u0e22"
+ "|\u10d2\u10d4|\u307f\u3093\u306a|\u30b0\u30fc\u30b0\u30eb|\u30b3\u30e0|\u4e16\u754c"
+ "|\u4e2d\u4fe1|\u4e2d\u56fd|\u4e2d\u570b|\u4e2d\u6587\u7f51|\u4f01\u4e1a|\u4f5b\u5c71"
+ "|\u4fe1\u606f|\u5065\u5eb7|\u516b\u5366|\u516c\u53f8|\u516c\u76ca|\u53f0\u6e7e|\u53f0\u7063"
+ "|\u5546\u57ce|\u5546\u5e97|\u5546\u6807|\u5728\u7ebf|\u5927\u62ff|\u5a31\u4e50|\u5de5\u884c"
+ "|\u5e7f\u4e1c|\u6148\u5584|\u6211\u7231\u4f60|\u624b\u673a|\u653f\u52a1|\u653f\u5e9c"
+ "|\u65b0\u52a0\u5761|\u65b0\u95fb|\u65f6\u5c1a|\u673a\u6784|\u6de1\u9a6c\u9521|\u6e38\u620f"
+ "|\u70b9\u770b|\u79fb\u52a8|\u7ec4\u7ec7\u673a\u6784|\u7f51\u5740|\u7f51\u5e97|\u7f51\u7edc"
+ "|\u8c37\u6b4c|\u96c6\u56e2|\u98de\u5229\u6d66|\u9910\u5385|\u9999\u6e2f|\ub2f7\ub137"
+ "|\ub2f7\ucef4|\uc0bc\uc131|\ud55c\uad6d|xbox"
+ "|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g"
+ "|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim"
+ "|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks"
+ "|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a"
+ "|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd"
+ "|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h"
+ "|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s"
+ "|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c"
+ "|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i"
+ "|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d"
+ "|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt"
+ "|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e"
+ "|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab"
+ "|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema"
+ "|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh"
+ "|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c"
+ "|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb"
+ "|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a"
+ "|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o"
+ "|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)"
+ "|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])"
+ "|(?:zara|zip|zone|zuerich|z[amw]))";
private static final String UCS_CHAR = "[" +
"\u00A0-\uD7FF" +
"\uF900-\uFDCF" +
"\uFDF0-\uFFEF" +
"\uD800\uDC00-\uD83F\uDFFD" +
"\uD840\uDC00-\uD87F\uDFFD" +
"\uD880\uDC00-\uD8BF\uDFFD" +
"\uD8C0\uDC00-\uD8FF\uDFFD" +
"\uD900\uDC00-\uD93F\uDFFD" +
"\uD940\uDC00-\uD97F\uDFFD" +
"\uD980\uDC00-\uD9BF\uDFFD" +
"\uD9C0\uDC00-\uD9FF\uDFFD" +
"\uDA00\uDC00-\uDA3F\uDFFD" +
"\uDA40\uDC00-\uDA7F\uDFFD" +
"\uDA80\uDC00-\uDABF\uDFFD" +
"\uDAC0\uDC00-\uDAFF\uDFFD" +
"\uDB00\uDC00-\uDB3F\uDFFD" +
"\uDB44\uDC00-\uDB7F\uDFFD" +
"&&[^\u00A0[\u2000-\u200A]\u2028\u2029\u202F\u3000]]";
private static final String UCS_CHAR_FIXED = "[" +
"\u00A0-\uD7FF" +
"\uF900-\uFDCF" +
"\uFDF0-\uFFEF" +
// "\uD800\uDC00-\uD83F\uDFFD" +
"\uD840\uDC00-\uD87F\uDFFD" +
"\uD880\uDC00-\uD8BF\uDFFD" +
"\uD8C0\uDC00-\uD8FF\uDFFD" +
"\uD900\uDC00-\uD93F\uDFFD" +
"\uD940\uDC00-\uD97F\uDFFD" +
"\uD980\uDC00-\uD9BF\uDFFD" +
"\uD9C0\uDC00-\uD9FF\uDFFD" +
"\uDA00\uDC00-\uDA3F\uDFFD" +
"\uDA40\uDC00-\uDA7F\uDFFD" +
"\uDA80\uDC00-\uDABF\uDFFD" +
"\uDAC0\uDC00-\uDAFF\uDFFD" +
"\uDB00\uDC00-\uDB3F\uDFFD" +
"\uDB44\uDC00-\uDB7F\uDFFD" +
"&&[^\u00A0[\u2000-\u200A]\u2028\u2029\u202F\u3000]]";
private static final String IP_ADDRESS_STRING =
"((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
+ "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
+ "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
+ "|[1-9][0-9]|[0-9]))";
private static final String TLD_CHAR = "a-zA-Z" + UCS_CHAR;
private static final String PUNYCODE_TLD = "xn\\-\\-[\\w\\-]{0,58}\\w";
private static final String LABEL_CHAR = "a-zA-Z0-9" + UCS_CHAR_FIXED;
private static final String IRI_LABEL = "[" + LABEL_CHAR + "](?:[" + LABEL_CHAR + "_\\-]{0,61}[" + LABEL_CHAR + "]){0,1}";
private static String STRICT_TLD = "(?:" + IANA_TOP_LEVEL_DOMAINS + "|" + PUNYCODE_TLD + ")";
private static final String STRICT_HOST_NAME = "(?:(?:" + IRI_LABEL + "\\.)+" + STRICT_TLD + ")";
private static final String STRICT_DOMAIN_NAME = "(?:" + STRICT_HOST_NAME + "|" + IP_ADDRESS_STRING + ")";
private static final String TLD = "(" + PUNYCODE_TLD + "|" + "[" + TLD_CHAR + "]{2,63}" + ")";
private static final String HOST_NAME = "(" + IRI_LABEL + "\\.)+" + TLD;
private static final String DOMAIN_NAME_STR = "(" + HOST_NAME + "|" + IP_ADDRESS_STRING + ")";
private static final Pattern DOMAIN_NAME = Pattern.compile(DOMAIN_NAME_STR);
private static final String PROTOCOL = "(?i:http|https|ton|tg)://";
private static final String WORD_BOUNDARY = "(?:\\b|$|^)";
private static final String USER_INFO = "(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
+ "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
+ "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@";
private static final String PORT_NUMBER = "\\:\\d{1,5}";
private static final String PATH_AND_QUERY = "[/\\?](?:(?:[" + LABEL_CHAR + ";/\\?:@&=#~" + "\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*";
private static final String RELAXED_DOMAIN_NAME = "(?:" + "(?:" + IRI_LABEL + "(?:\\.(?=\\S))" + ")*" + "(?:" + IRI_LABEL + "(?:\\.(?=\\S))" + "?)" + "|" + IP_ADDRESS_STRING + ")";
private static final String WEB_URL_WITHOUT_PROTOCOL = "("
+ WORD_BOUNDARY
+ "(?<!:\\/\\/)"
+ "("
+ "(?:" + STRICT_DOMAIN_NAME + ")"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")";
private static final String WEB_URL_WITH_PROTOCOL = "("
+ WORD_BOUNDARY
+ "(?:"
+ "(?:" + PROTOCOL + "(?:" + USER_INFO + ")?" + ")"
+ "(?:" + RELAXED_DOMAIN_NAME + ")?"
+ "(?:" + PORT_NUMBER + ")?"
+ ")"
+ "(?:" + PATH_AND_QUERY + ")?"
+ WORD_BOUNDARY
+ ")";
public static Pattern WEB_URL = null;
static {
try {
WEB_URL = Pattern.compile("(" + WEB_URL_WITH_PROTOCOL + "|" + WEB_URL_WITHOUT_PROTOCOL + ")");
} catch (Exception e) {
FileLog.e(e);
}
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/messenger/LinkifyPort.java |
2,796 | /*
* Copyright (C) 2009-2023 Lightbend Inc. <https://www.lightbend.com>
*/
package akka.japi.pf;
/**
* A builder for {@link scala.PartialFunction}.
*
* @param <I> the input type, that this PartialFunction will be applied to
* @param <R> the return type, that the results of the application will have
*/
public final class PFBuilder<I, R> extends AbstractPFBuilder<I, R> {
/** Create a PFBuilder. */
public PFBuilder() {}
/**
* Add a new case statement to this builder.
*
* @param type a type to match the argument against
* @param apply an action to apply to the argument if the type matches
* @return a builder with the case statement added
*/
public <P> PFBuilder<I, R> match(final Class<P> type, FI.Apply<P, R> apply) {
return matchUnchecked(type, apply);
}
/**
* Add a new case statement to this builder without compile time type check of the parameters.
* Should normally not be used, but when matching on class with generic type argument it can be
* useful, e.g. <code>List.class</code> and <code>(List<String> list) -> {}</code>.
*
* @param type a type to match the argument against
* @param apply an action to apply to the argument if the type matches
* @return a builder with the case statement added
*/
@SuppressWarnings("unchecked")
public PFBuilder<I, R> matchUnchecked(final Class<?> type, FI.Apply<?, R> apply) {
FI.Predicate predicate =
new FI.Predicate() {
@Override
public boolean defined(Object o) {
return type.isInstance(o);
}
};
addStatement(new CaseStatement<I, Object, R>(predicate, (FI.Apply<Object, R>) apply));
return this;
}
/**
* Add a new case statement to this builder.
*
* @param type a type to match the argument against
* @param predicate a predicate that will be evaluated on the argument if the type matches
* @param apply an action to apply to the argument if the type matches and the predicate returns
* true
* @return a builder with the case statement added
*/
public <P> PFBuilder<I, R> match(
final Class<P> type, final FI.TypedPredicate<P> predicate, final FI.Apply<P, R> apply) {
return matchUnchecked(type, predicate, apply);
}
/**
* Add a new case statement to this builder without compile time type check of the parameters.
* Should normally not be used, but when matching on class with generic type argument it can be
* useful, e.g. <code>List.class</code> and <code>(List<String> list) -> {}</code>.
*
* @param type a type to match the argument against
* @param predicate a predicate that will be evaluated on the argument if the type matches
* @param apply an action to apply to the argument if the type matches and the predicate returns
* true
* @return a builder with the case statement added
*/
@SuppressWarnings("unchecked")
public PFBuilder<I, R> matchUnchecked(
final Class<?> type, final FI.TypedPredicate<?> predicate, final FI.Apply<?, R> apply) {
FI.Predicate fiPredicate =
new FI.Predicate() {
@Override
public boolean defined(Object o) {
if (!type.isInstance(o)) return false;
else return ((FI.TypedPredicate<Object>) predicate).defined(o);
}
};
addStatement(new CaseStatement<I, Object, R>(fiPredicate, (FI.Apply<Object, R>) apply));
return this;
}
/**
* Add a new case statement to this builder.
*
* @param object the object to compare equals with
* @param apply an action to apply to the argument if the object compares equal
* @return a builder with the case statement added
*/
public <P> PFBuilder<I, R> matchEquals(final P object, final FI.Apply<P, R> apply) {
addStatement(
new CaseStatement<I, P, R>(
new FI.Predicate() {
@Override
public boolean defined(Object o) {
return object.equals(o);
}
},
apply));
return this;
}
/**
* Add a new case statement to this builder, that matches any argument.
*
* @param apply an action to apply to the argument
* @return a builder with the case statement added
*/
public PFBuilder<I, R> matchAny(final FI.Apply<I, R> apply) {
addStatement(
new CaseStatement<I, I, R>(
new FI.Predicate() {
@Override
public boolean defined(Object o) {
return true;
}
},
apply));
return this;
}
}
| akka/akka | akka-actor/src/main/java/akka/japi/pf/PFBuilder.java |
2,797 | /*
* Copyright (c) 1994, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import java.io.ObjectStreamField;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Native;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandles;
import java.lang.constant.Constable;
import java.lang.constant.ConstantDesc;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Spliterator;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import jdk.internal.util.ArraysSupport;
import jdk.internal.util.Preconditions;
import jdk.internal.vm.annotation.ForceInline;
import jdk.internal.vm.annotation.IntrinsicCandidate;
import jdk.internal.vm.annotation.Stable;
import sun.nio.cs.ArrayDecoder;
import sun.nio.cs.ArrayEncoder;
import sun.nio.cs.ISO_8859_1;
import sun.nio.cs.US_ASCII;
import sun.nio.cs.UTF_8;
/**
* The {@code String} class represents character strings. All
* string literals in Java programs, such as {@code "abc"}, are
* implemented as instances of this class.
* <p>
* Strings are constant; their values cannot be changed after they
* are created. String buffers support mutable strings.
* Because String objects are immutable they can be shared. For example:
* <blockquote><pre>
* String str = "abc";
* </pre></blockquote><p>
* is equivalent to:
* <blockquote><pre>
* char data[] = {'a', 'b', 'c'};
* String str = new String(data);
* </pre></blockquote><p>
* Here are some more examples of how strings can be used:
* <blockquote><pre>
* System.out.println("abc");
* String cde = "cde";
* System.out.println("abc" + cde);
* String c = "abc".substring(2, 3);
* String d = cde.substring(1, 2);
* </pre></blockquote>
* <p>
* The class {@code String} includes methods for examining
* individual characters of the sequence, for comparing strings, for
* searching strings, for extracting substrings, and for creating a
* copy of a string with all characters translated to uppercase or to
* lowercase. Case mapping is based on the Unicode Standard version
* specified by the {@link java.lang.Character Character} class.
* <p>
* The Java language provides special support for the string
* concatenation operator ( + ), and for conversion of
* other objects to strings. For additional information on string
* concatenation and conversion, see <i>The Java Language Specification</i>.
*
* <p> Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
*
* <p>A {@code String} represents a string in the UTF-16 format
* in which <em>supplementary characters</em> are represented by <em>surrogate
* pairs</em> (see the section <a href="Character.html#unicode">Unicode
* Character Representations</a> in the {@code Character} class for
* more information).
* Index values refer to {@code char} code units, so a supplementary
* character uses two positions in a {@code String}.
* <p>The {@code String} class provides methods for dealing with
* Unicode code points (i.e., characters), in addition to those for
* dealing with Unicode code units (i.e., {@code char} values).
*
* <p>Unless otherwise noted, methods for comparing Strings do not take locale
* into account. The {@link java.text.Collator} class provides methods for
* finer-grain, locale-sensitive String comparison.
*
* @implNote The implementation of the string concatenation operator is left to
* the discretion of a Java compiler, as long as the compiler ultimately conforms
* to <i>The Java Language Specification</i>. For example, the {@code javac} compiler
* may implement the operator with {@code StringBuffer}, {@code StringBuilder},
* or {@code java.lang.invoke.StringConcatFactory} depending on the JDK version. The
* implementation of string conversion is typically through the method {@code toString},
* defined by {@code Object} and inherited by all classes in Java.
*
* @author Lee Boynton
* @author Arthur van Hoff
* @author Martin Buchholz
* @author Ulf Zibis
* @see java.lang.Object#toString()
* @see java.lang.StringBuffer
* @see java.lang.StringBuilder
* @see java.nio.charset.Charset
* @since 1.0
* @jls 15.18.1 String Concatenation Operator +
*/
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence,
Constable, ConstantDesc {
/**
* The value is used for character storage.
*
* @implNote This field is trusted by the VM, and is a subject to
* constant folding if String instance is constant. Overwriting this
* field after construction will cause problems.
*
* Additionally, it is marked with {@link Stable} to trust the contents
* of the array. No other facility in JDK provides this functionality (yet).
* {@link Stable} is safe here, because value is never null.
*/
@Stable
private final byte[] value;
/**
* The identifier of the encoding used to encode the bytes in
* {@code value}. The supported values in this implementation are
*
* LATIN1
* UTF16
*
* @implNote This field is trusted by the VM, and is a subject to
* constant folding if String instance is constant. Overwriting this
* field after construction will cause problems.
*/
private final byte coder;
/** Cache the hash code for the string */
private int hash; // Default to 0
/**
* Cache if the hash has been calculated as actually being zero, enabling
* us to avoid recalculating this.
*/
private boolean hashIsZero; // Default to false;
/** use serialVersionUID from JDK 1.0.2 for interoperability */
@java.io.Serial
private static final long serialVersionUID = -6849794470754667710L;
/**
* If String compaction is disabled, the bytes in {@code value} are
* always encoded in UTF16.
*
* For methods with several possible implementation paths, when String
* compaction is disabled, only one code path is taken.
*
* The instance field value is generally opaque to optimizing JIT
* compilers. Therefore, in performance-sensitive place, an explicit
* check of the static boolean {@code COMPACT_STRINGS} is done first
* before checking the {@code coder} field since the static boolean
* {@code COMPACT_STRINGS} would be constant folded away by an
* optimizing JIT compiler. The idioms for these cases are as follows.
*
* For code such as:
*
* if (coder == LATIN1) { ... }
*
* can be written more optimally as
*
* if (coder() == LATIN1) { ... }
*
* or:
*
* if (COMPACT_STRINGS && coder == LATIN1) { ... }
*
* An optimizing JIT compiler can fold the above conditional as:
*
* COMPACT_STRINGS == true => if (coder == LATIN1) { ... }
* COMPACT_STRINGS == false => if (false) { ... }
*
* @implNote
* The actual value for this field is injected by JVM. The static
* initialization block is used to set the value here to communicate
* that this static final field is not statically foldable, and to
* avoid any possible circular dependency during vm initialization.
*/
static final boolean COMPACT_STRINGS;
static {
COMPACT_STRINGS = true;
}
/**
* Class String is special cased within the Serialization Stream Protocol.
*
* A String instance is written into an ObjectOutputStream according to
* <a href="{@docRoot}/../specs/serialization/protocol.html#stream-elements">
* <cite>Java Object Serialization Specification</cite>, Section 6.2, "Stream Elements"</a>
*/
@java.io.Serial
private static final ObjectStreamField[] serialPersistentFields =
new ObjectStreamField[0];
/**
* Initializes a newly created {@code String} object so that it represents
* an empty character sequence. Note that use of this constructor is
* unnecessary since Strings are immutable.
*/
public String() {
this.value = "".value;
this.coder = "".coder;
}
/**
* Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
*
* @param original
* A {@code String}
*/
@IntrinsicCandidate
public String(String original) {
this.value = original.value;
this.coder = original.coder;
this.hash = original.hash;
this.hashIsZero = original.hashIsZero;
}
/**
* Allocates a new {@code String} so that it represents the sequence of
* characters currently contained in the character array argument. The
* contents of the character array are copied; subsequent modification of
* the character array does not affect the newly created string.
*
* <p> The contents of the string are unspecified if the character array
* is modified during string construction.
*
* @param value
* The initial value of the string
*/
public String(char[] value) {
this(value, 0, value.length, null);
}
/**
* Allocates a new {@code String} that contains characters from a subarray
* of the character array argument. The {@code offset} argument is the
* index of the first character of the subarray and the {@code count}
* argument specifies the length of the subarray. The contents of the
* subarray are copied; subsequent modification of the character array does
* not affect the newly created string.
*
* <p> The contents of the string are unspecified if the character array
* is modified during string construction.
*
* @param value
* Array that is the source of characters
*
* @param offset
* The initial offset
*
* @param count
* The length
*
* @throws IndexOutOfBoundsException
* If {@code offset} is negative, {@code count} is negative, or
* {@code offset} is greater than {@code value.length - count}
*/
public String(char[] value, int offset, int count) {
this(value, offset, count, rangeCheck(value, offset, count));
}
private static Void rangeCheck(char[] value, int offset, int count) {
checkBoundsOffCount(offset, count, value.length);
return null;
}
/**
* Allocates a new {@code String} that contains characters from a subarray
* of the <a href="Character.html#unicode">Unicode code point</a> array
* argument. The {@code offset} argument is the index of the first code
* point of the subarray and the {@code count} argument specifies the
* length of the subarray. The contents of the subarray are converted to
* {@code char}s; subsequent modification of the {@code int} array does not
* affect the newly created string.
*
* <p> The contents of the string are unspecified if the codepoints array
* is modified during string construction.
*
* @param codePoints
* Array that is the source of Unicode code points
*
* @param offset
* The initial offset
*
* @param count
* The length
*
* @throws IllegalArgumentException
* If any invalid Unicode code point is found in {@code
* codePoints}
*
* @throws IndexOutOfBoundsException
* If {@code offset} is negative, {@code count} is negative, or
* {@code offset} is greater than {@code codePoints.length - count}
*
* @since 1.5
*/
public String(int[] codePoints, int offset, int count) {
checkBoundsOffCount(offset, count, codePoints.length);
if (count == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
if (COMPACT_STRINGS) {
byte[] val = StringUTF16.compress(codePoints, offset, count);
this.coder = StringUTF16.coderFromArrayLen(val, count);
this.value = val;
return;
}
this.coder = UTF16;
this.value = StringUTF16.toBytes(codePoints, offset, count);
}
/**
* Allocates a new {@code String} constructed from a subarray of an array
* of 8-bit integer values.
*
* <p> The {@code offset} argument is the index of the first byte of the
* subarray, and the {@code count} argument specifies the length of the
* subarray.
*
* <p> Each {@code byte} in the subarray is converted to a {@code char} as
* specified in the {@link #String(byte[],int) String(byte[],int)} constructor.
*
* <p> The contents of the string are unspecified if the byte array
* is modified during string construction.
*
* @deprecated This method does not properly convert bytes into characters.
* As of JDK 1.1, the preferred way to do this is via the
* {@code String} constructors that take a {@link Charset}, charset name,
* or that use the {@link Charset#defaultCharset() default charset}.
*
* @param ascii
* The bytes to be converted to characters
*
* @param hibyte
* The top 8 bits of each 16-bit Unicode code unit
*
* @param offset
* The initial offset
* @param count
* The length
*
* @throws IndexOutOfBoundsException
* If {@code offset} is negative, {@code count} is negative, or
* {@code offset} is greater than {@code ascii.length - count}
*
* @see #String(byte[], int)
* @see #String(byte[], int, int, java.lang.String)
* @see #String(byte[], int, int, java.nio.charset.Charset)
* @see #String(byte[], int, int)
* @see #String(byte[], java.lang.String)
* @see #String(byte[], java.nio.charset.Charset)
* @see #String(byte[])
*/
@Deprecated(since="1.1")
public String(byte[] ascii, int hibyte, int offset, int count) {
checkBoundsOffCount(offset, count, ascii.length);
if (count == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
if (COMPACT_STRINGS && (byte)hibyte == 0) {
this.value = Arrays.copyOfRange(ascii, offset, offset + count);
this.coder = LATIN1;
} else {
hibyte <<= 8;
byte[] val = StringUTF16.newBytesFor(count);
for (int i = 0; i < count; i++) {
StringUTF16.putChar(val, i, hibyte | (ascii[offset++] & 0xff));
}
this.value = val;
this.coder = UTF16;
}
}
/**
* Allocates a new {@code String} containing characters constructed from
* an array of 8-bit integer values. Each character <i>c</i> in the
* resulting string is constructed from the corresponding component
* <i>b</i> in the byte array such that:
*
* <blockquote><pre>
* <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
* | (<b><i>b</i></b> & 0xff))
* </pre></blockquote>
*
* <p> The contents of the string are unspecified if the byte array
* is modified during string construction.
*
* @deprecated This method does not properly convert bytes into
* characters. As of JDK 1.1, the preferred way to do this is via the
* {@code String} constructors that take a {@link Charset}, charset name,
* or that use the {@link Charset#defaultCharset() default charset}.
*
* @param ascii
* The bytes to be converted to characters
*
* @param hibyte
* The top 8 bits of each 16-bit Unicode code unit
*
* @see #String(byte[], int, int, java.lang.String)
* @see #String(byte[], int, int, java.nio.charset.Charset)
* @see #String(byte[], int, int)
* @see #String(byte[], java.lang.String)
* @see #String(byte[], java.nio.charset.Charset)
* @see #String(byte[])
*/
@Deprecated(since="1.1")
public String(byte[] ascii, int hibyte) {
this(ascii, hibyte, 0, ascii.length);
}
/**
* Constructs a new {@code String} by decoding the specified subarray of
* bytes using the specified charset. The length of the new {@code String}
* is a function of the charset, and hence may not be equal to the length
* of the subarray.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the given charset is unspecified. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* <p> The contents of the string are unspecified if the byte array
* is modified during string construction.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param offset
* The index of the first byte to decode
*
* @param length
* The number of bytes to decode
*
* @param charsetName
* The name of a supported {@linkplain java.nio.charset.Charset
* charset}
*
* @throws UnsupportedEncodingException
* If the named charset is not supported
*
* @throws IndexOutOfBoundsException
* If {@code offset} is negative, {@code length} is negative, or
* {@code offset} is greater than {@code bytes.length - length}
*
* @since 1.1
*/
public String(byte[] bytes, int offset, int length, String charsetName)
throws UnsupportedEncodingException {
this(lookupCharset(charsetName), bytes, checkBoundsOffCount(offset, length, bytes.length), length);
}
/**
* Constructs a new {@code String} by decoding the specified subarray of
* bytes using the specified {@linkplain java.nio.charset.Charset charset}.
* The length of the new {@code String} is a function of the charset, and
* hence may not be equal to the length of the subarray.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* <p> The contents of the string are unspecified if the byte array
* is modified during string construction.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param offset
* The index of the first byte to decode
*
* @param length
* The number of bytes to decode
*
* @param charset
* The {@linkplain java.nio.charset.Charset charset} to be used to
* decode the {@code bytes}
*
* @throws IndexOutOfBoundsException
* If {@code offset} is negative, {@code length} is negative, or
* {@code offset} is greater than {@code bytes.length - length}
*
* @since 1.6
*/
public String(byte[] bytes, int offset, int length, Charset charset) {
this(Objects.requireNonNull(charset), bytes, checkBoundsOffCount(offset, length, bytes.length), length);
}
/**
* This method does not do any precondition checks on its arguments.
* <p>
* Important: parameter order of this method is deliberately changed in order to
* disambiguate it against other similar methods of this class.
*/
@SuppressWarnings("removal")
private String(Charset charset, byte[] bytes, int offset, int length) {
if (length == 0) {
this.value = "".value;
this.coder = "".coder;
} else if (charset == UTF_8.INSTANCE) {
if (COMPACT_STRINGS) {
int dp = StringCoding.countPositives(bytes, offset, length);
if (dp == length) {
this.value = Arrays.copyOfRange(bytes, offset, offset + length);
this.coder = LATIN1;
return;
}
// Decode with a stable copy, to be the result if the decoded length is the same
byte[] latin1 = Arrays.copyOfRange(bytes, offset, offset + length);
int sp = dp; // first dp bytes are already in the copy
while (sp < length) {
int b1 = latin1[sp++];
if (b1 >= 0) {
latin1[dp++] = (byte)b1;
continue;
}
if ((b1 & 0xfe) == 0xc2 && sp < length) { // b1 either 0xc2 or 0xc3
int b2 = latin1[sp];
if (b2 < -64) { // continuation bytes are always negative values in the range -128 to -65
latin1[dp++] = (byte)decode2(b1, b2);
sp++;
continue;
}
}
// anything not a latin1, including the REPL
// we have to go with the utf16
sp--;
break;
}
if (sp == length) {
if (dp != latin1.length) {
latin1 = Arrays.copyOf(latin1, dp);
}
this.value = latin1;
this.coder = LATIN1;
return;
}
byte[] utf16 = StringUTF16.newBytesFor(length);
StringLatin1.inflate(latin1, 0, utf16, 0, dp);
dp = decodeUTF8_UTF16(latin1, sp, length, utf16, dp, true);
if (dp != length) {
utf16 = Arrays.copyOf(utf16, dp << 1);
}
this.value = utf16;
this.coder = UTF16;
} else { // !COMPACT_STRINGS
byte[] dst = StringUTF16.newBytesFor(length);
int dp = decodeUTF8_UTF16(bytes, offset, offset + length, dst, 0, true);
if (dp != length) {
dst = Arrays.copyOf(dst, dp << 1);
}
this.value = dst;
this.coder = UTF16;
}
} else if (charset == ISO_8859_1.INSTANCE) {
if (COMPACT_STRINGS) {
this.value = Arrays.copyOfRange(bytes, offset, offset + length);
this.coder = LATIN1;
} else {
this.value = StringLatin1.inflate(bytes, offset, length);
this.coder = UTF16;
}
} else if (charset == US_ASCII.INSTANCE) {
if (COMPACT_STRINGS && !StringCoding.hasNegatives(bytes, offset, length)) {
this.value = Arrays.copyOfRange(bytes, offset, offset + length);
this.coder = LATIN1;
} else {
byte[] dst = StringUTF16.newBytesFor(length);
int dp = 0;
while (dp < length) {
int b = bytes[offset++];
StringUTF16.putChar(dst, dp++, (b >= 0) ? (char) b : REPL);
}
this.value = dst;
this.coder = UTF16;
}
} else {
// (1)We never cache the "external" cs, the only benefit of creating
// an additional StringDe/Encoder object to wrap it is to share the
// de/encode() method. These SD/E objects are short-lived, the young-gen
// gc should be able to take care of them well. But the best approach
// is still not to generate them if not really necessary.
// (2)The defensive copy of the input byte/char[] has a big performance
// impact, as well as the outgoing result byte/char[]. Need to do the
// optimization check of (sm==null && classLoader0==null) for both.
CharsetDecoder cd = charset.newDecoder();
// ArrayDecoder fastpaths
if (cd instanceof ArrayDecoder ad) {
// ascii
if (ad.isASCIICompatible() && !StringCoding.hasNegatives(bytes, offset, length)) {
if (COMPACT_STRINGS) {
this.value = Arrays.copyOfRange(bytes, offset, offset + length);
this.coder = LATIN1;
return;
}
this.value = StringLatin1.inflate(bytes, offset, length);
this.coder = UTF16;
return;
}
// fastpath for always Latin1 decodable single byte
if (COMPACT_STRINGS && ad.isLatin1Decodable()) {
byte[] dst = new byte[length];
ad.decodeToLatin1(bytes, offset, length, dst);
this.value = dst;
this.coder = LATIN1;
return;
}
int en = scale(length, cd.maxCharsPerByte());
cd.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
char[] ca = new char[en];
int clen = ad.decode(bytes, offset, length, ca);
if (COMPACT_STRINGS) {
byte[] val = StringUTF16.compress(ca, 0, clen);;
this.coder = StringUTF16.coderFromArrayLen(val, clen);
this.value = val;
return;
}
coder = UTF16;
value = StringUTF16.toBytes(ca, 0, clen);
return;
}
// decode using CharsetDecoder
int en = scale(length, cd.maxCharsPerByte());
cd.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
char[] ca = new char[en];
if (charset.getClass().getClassLoader0() != null &&
System.getSecurityManager() != null) {
bytes = Arrays.copyOfRange(bytes, offset, offset + length);
offset = 0;
}
int caLen;
try {
caLen = decodeWithDecoder(cd, ca, bytes, offset, length);
} catch (CharacterCodingException x) {
// Substitution is enabled, so this shouldn't happen
throw new Error(x);
}
if (COMPACT_STRINGS) {
byte[] val = StringUTF16.compress(ca, 0, caLen);
this.coder = StringUTF16.coderFromArrayLen(val, caLen);
this.value = val;
return;
}
coder = UTF16;
value = StringUTF16.toBytes(ca, 0, caLen);
}
}
/*
* Throws iae, instead of replacing, if malformed or unmappable.
*
* @param noShare
* {@code true} if the resulting string MUST NOT share the byte array,
* {@code false} if the byte array can be exclusively used to construct
* the string and is not modified or used for any other purpose.
*/
static String newStringUTF8NoRepl(byte[] bytes, int offset, int length, boolean noShare) {
checkBoundsOffCount(offset, length, bytes.length);
if (length == 0) {
return "";
}
int dp;
byte[] dst;
if (COMPACT_STRINGS) {
dp = StringCoding.countPositives(bytes, offset, length);
int sl = offset + length;
if (dp == length) {
if (noShare || length != bytes.length) {
return new String(Arrays.copyOfRange(bytes, offset, offset + length), LATIN1);
} else {
return new String(bytes, LATIN1);
}
}
dst = new byte[length];
System.arraycopy(bytes, offset, dst, 0, dp);
offset += dp;
while (offset < sl) {
int b1 = bytes[offset++];
if (b1 >= 0) {
dst[dp++] = (byte)b1;
continue;
}
if ((b1 & 0xfe) == 0xc2 && offset < sl) { // b1 either 0xc2 or 0xc3
int b2 = bytes[offset];
if (b2 < -64) { // continuation bytes are always negative values in the range -128 to -65
dst[dp++] = (byte)decode2(b1, b2);
offset++;
continue;
}
}
// anything not a latin1, including the REPL
// we have to go with the utf16
offset--;
break;
}
if (offset == sl) {
if (dp != dst.length) {
dst = Arrays.copyOf(dst, dp);
}
return new String(dst, LATIN1);
}
if (dp == 0) {
dst = StringUTF16.newBytesFor(length);
} else {
byte[] buf = StringUTF16.newBytesFor(length);
StringLatin1.inflate(dst, 0, buf, 0, dp);
dst = buf;
}
dp = decodeUTF8_UTF16(bytes, offset, sl, dst, dp, false);
} else { // !COMPACT_STRINGS
dst = StringUTF16.newBytesFor(length);
dp = decodeUTF8_UTF16(bytes, offset, offset + length, dst, 0, false);
}
if (dp != length) {
dst = Arrays.copyOf(dst, dp << 1);
}
return new String(dst, UTF16);
}
static String newStringNoRepl(byte[] src, Charset cs) throws CharacterCodingException {
try {
return newStringNoRepl1(src, cs);
} catch (IllegalArgumentException e) {
//newStringNoRepl1 throws IAE with MalformedInputException or CCE as the cause
Throwable cause = e.getCause();
if (cause instanceof MalformedInputException mie) {
throw mie;
}
throw (CharacterCodingException)cause;
}
}
@SuppressWarnings("removal")
private static String newStringNoRepl1(byte[] src, Charset cs) {
int len = src.length;
if (len == 0) {
return "";
}
if (cs == UTF_8.INSTANCE) {
return newStringUTF8NoRepl(src, 0, src.length, false);
}
if (cs == ISO_8859_1.INSTANCE) {
if (COMPACT_STRINGS)
return new String(src, LATIN1);
return new String(StringLatin1.inflate(src, 0, src.length), UTF16);
}
if (cs == US_ASCII.INSTANCE) {
if (!StringCoding.hasNegatives(src, 0, src.length)) {
if (COMPACT_STRINGS)
return new String(src, LATIN1);
return new String(StringLatin1.inflate(src, 0, src.length), UTF16);
} else {
throwMalformed(src);
}
}
CharsetDecoder cd = cs.newDecoder();
// ascii fastpath
if (cd instanceof ArrayDecoder ad &&
ad.isASCIICompatible() &&
!StringCoding.hasNegatives(src, 0, src.length)) {
if (COMPACT_STRINGS)
return new String(src, LATIN1);
return new String(src, 0, src.length, ISO_8859_1.INSTANCE);
}
int en = scale(len, cd.maxCharsPerByte());
char[] ca = new char[en];
if (cs.getClass().getClassLoader0() != null &&
System.getSecurityManager() != null) {
src = Arrays.copyOf(src, len);
}
int caLen;
try {
caLen = decodeWithDecoder(cd, ca, src, 0, src.length);
} catch (CharacterCodingException x) {
// throw via IAE
throw new IllegalArgumentException(x);
}
if (COMPACT_STRINGS) {
byte[] val = StringUTF16.compress(ca, 0, caLen);
byte coder = StringUTF16.coderFromArrayLen(val, caLen);
return new String(val, coder);
}
return new String(StringUTF16.toBytes(ca, 0, caLen), UTF16);
}
private static final char REPL = '\ufffd';
// Trim the given byte array to the given length
@SuppressWarnings("removal")
private static byte[] safeTrim(byte[] ba, int len, boolean isTrusted) {
if (len == ba.length && (isTrusted || System.getSecurityManager() == null)) {
return ba;
} else {
return Arrays.copyOf(ba, len);
}
}
private static int scale(int len, float expansionFactor) {
// We need to perform double, not float, arithmetic; otherwise
// we lose low order bits when len is larger than 2**24.
return (int)(len * (double)expansionFactor);
}
private static Charset lookupCharset(String csn) throws UnsupportedEncodingException {
Objects.requireNonNull(csn);
try {
return Charset.forName(csn);
} catch (UnsupportedCharsetException | IllegalCharsetNameException x) {
throw new UnsupportedEncodingException(csn);
}
}
private static byte[] encode(Charset cs, byte coder, byte[] val) {
if (cs == UTF_8.INSTANCE) {
return encodeUTF8(coder, val, true);
}
if (cs == ISO_8859_1.INSTANCE) {
return encode8859_1(coder, val);
}
if (cs == US_ASCII.INSTANCE) {
return encodeASCII(coder, val);
}
return encodeWithEncoder(cs, coder, val, true);
}
private static byte[] encodeWithEncoder(Charset cs, byte coder, byte[] val, boolean doReplace) {
CharsetEncoder ce = cs.newEncoder();
int len = val.length >> coder; // assume LATIN1=0/UTF16=1;
int en = scale(len, ce.maxBytesPerChar());
// fastpath with ArrayEncoder implies `doReplace`.
if (doReplace && ce instanceof ArrayEncoder ae) {
// fastpath for ascii compatible
if (coder == LATIN1 &&
ae.isASCIICompatible() &&
!StringCoding.hasNegatives(val, 0, val.length)) {
return val.clone();
}
byte[] ba = new byte[en];
if (len == 0) {
return ba;
}
int blen = (coder == LATIN1) ? ae.encodeFromLatin1(val, 0, len, ba)
: ae.encodeFromUTF16(val, 0, len, ba);
if (blen != -1) {
return safeTrim(ba, blen, true);
}
}
byte[] ba = new byte[en];
if (len == 0) {
return ba;
}
if (doReplace) {
ce.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
}
char[] ca = (coder == LATIN1 ) ? StringLatin1.toChars(val)
: StringUTF16.toChars(val);
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(ca, 0, len);
try {
CoderResult cr = ce.encode(cb, bb, true);
if (!cr.isUnderflow())
cr.throwException();
cr = ce.flush(bb);
if (!cr.isUnderflow())
cr.throwException();
} catch (CharacterCodingException x) {
if (!doReplace) {
throw new IllegalArgumentException(x);
} else {
throw new Error(x);
}
}
return safeTrim(ba, bb.position(), cs.getClass().getClassLoader0() == null);
}
/*
* Throws iae, instead of replacing, if unmappable.
*/
static byte[] getBytesUTF8NoRepl(String s) {
return encodeUTF8(s.coder(), s.value(), false);
}
private static boolean isASCII(byte[] src) {
return !StringCoding.hasNegatives(src, 0, src.length);
}
/*
* Throws CCE, instead of replacing, if unmappable.
*/
static byte[] getBytesNoRepl(String s, Charset cs) throws CharacterCodingException {
try {
return getBytesNoRepl1(s, cs);
} catch (IllegalArgumentException e) {
//getBytesNoRepl1 throws IAE with UnmappableCharacterException or CCE as the cause
Throwable cause = e.getCause();
if (cause instanceof UnmappableCharacterException) {
throw (UnmappableCharacterException)cause;
}
throw (CharacterCodingException)cause;
}
}
private static byte[] getBytesNoRepl1(String s, Charset cs) {
byte[] val = s.value();
byte coder = s.coder();
if (cs == UTF_8.INSTANCE) {
if (coder == LATIN1 && isASCII(val)) {
return val;
}
return encodeUTF8(coder, val, false);
}
if (cs == ISO_8859_1.INSTANCE) {
if (coder == LATIN1) {
return val;
}
return encode8859_1(coder, val, false);
}
if (cs == US_ASCII.INSTANCE) {
if (coder == LATIN1) {
if (isASCII(val)) {
return val;
} else {
throwUnmappable(val);
}
}
}
return encodeWithEncoder(cs, coder, val, false);
}
private static byte[] encodeASCII(byte coder, byte[] val) {
if (coder == LATIN1) {
int positives = StringCoding.countPositives(val, 0, val.length);
byte[] dst = val.clone();
if (positives < dst.length) {
replaceNegatives(dst, positives);
}
return dst;
}
int len = val.length >> 1;
byte[] dst = new byte[len];
int dp = 0;
for (int i = 0; i < len; i++) {
char c = StringUTF16.getChar(val, i);
if (c < 0x80) {
dst[dp++] = (byte)c;
continue;
}
if (Character.isHighSurrogate(c) && i + 1 < len &&
Character.isLowSurrogate(StringUTF16.getChar(val, i + 1))) {
i++;
}
dst[dp++] = '?';
}
if (len == dp) {
return dst;
}
return Arrays.copyOf(dst, dp);
}
private static void replaceNegatives(byte[] val, int fromIndex) {
for (int i = fromIndex; i < val.length; i++) {
if (val[i] < 0) {
val[i] = '?';
}
}
}
private static byte[] encode8859_1(byte coder, byte[] val) {
return encode8859_1(coder, val, true);
}
private static byte[] encode8859_1(byte coder, byte[] val, boolean doReplace) {
if (coder == LATIN1) {
return val.clone();
}
int len = val.length >> 1;
byte[] dst = new byte[len];
int dp = 0;
int sp = 0;
int sl = len;
while (sp < sl) {
int ret = StringCoding.implEncodeISOArray(val, sp, dst, dp, len);
sp = sp + ret;
dp = dp + ret;
if (ret != len) {
if (!doReplace) {
throwUnmappable(sp);
}
char c = StringUTF16.getChar(val, sp++);
if (Character.isHighSurrogate(c) && sp < sl &&
Character.isLowSurrogate(StringUTF16.getChar(val, sp))) {
sp++;
}
dst[dp++] = '?';
len = sl - sp;
}
}
if (dp == dst.length) {
return dst;
}
return Arrays.copyOf(dst, dp);
}
//////////////////////////////// utf8 ////////////////////////////////////
/**
* Decodes ASCII from the source byte array into the destination
* char array. Used via JavaLangAccess from UTF_8 and other charset
* decoders.
*
* @return the number of bytes successfully decoded, at most len
*/
/* package-private */
static int decodeASCII(byte[] sa, int sp, char[] da, int dp, int len) {
int count = StringCoding.countPositives(sa, sp, len);
while (count < len) {
if (sa[sp + count] < 0) {
break;
}
count++;
}
StringLatin1.inflate(sa, sp, da, dp, count);
return count;
}
private static boolean isNotContinuation(int b) {
return (b & 0xc0) != 0x80;
}
private static boolean isMalformed3(int b1, int b2, int b3) {
return (b1 == (byte)0xe0 && (b2 & 0xe0) == 0x80) ||
(b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80;
}
private static boolean isMalformed3_2(int b1, int b2) {
return (b1 == (byte)0xe0 && (b2 & 0xe0) == 0x80) ||
(b2 & 0xc0) != 0x80;
}
private static boolean isMalformed4(int b2, int b3, int b4) {
return (b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 ||
(b4 & 0xc0) != 0x80;
}
private static boolean isMalformed4_2(int b1, int b2) {
return (b1 == 0xf0 && (b2 < 0x90 || b2 > 0xbf)) ||
(b1 == 0xf4 && (b2 & 0xf0) != 0x80) ||
(b2 & 0xc0) != 0x80;
}
private static boolean isMalformed4_3(int b3) {
return (b3 & 0xc0) != 0x80;
}
private static char decode2(int b1, int b2) {
return (char)(((b1 << 6) ^ b2) ^
(((byte) 0xC0 << 6) ^
((byte) 0x80 << 0)));
}
private static char decode3(int b1, int b2, int b3) {
return (char)((b1 << 12) ^
(b2 << 6) ^
(b3 ^
(((byte) 0xE0 << 12) ^
((byte) 0x80 << 6) ^
((byte) 0x80 << 0))));
}
private static int decode4(int b1, int b2, int b3, int b4) {
return ((b1 << 18) ^
(b2 << 12) ^
(b3 << 6) ^
(b4 ^
(((byte) 0xF0 << 18) ^
((byte) 0x80 << 12) ^
((byte) 0x80 << 6) ^
((byte) 0x80 << 0))));
}
private static int decodeUTF8_UTF16(byte[] src, int sp, int sl, byte[] dst, int dp, boolean doReplace) {
while (sp < sl) {
int b1 = src[sp++];
if (b1 >= 0) {
StringUTF16.putChar(dst, dp++, (char) b1);
} else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) {
if (sp < sl) {
int b2 = src[sp++];
if (isNotContinuation(b2)) {
if (!doReplace) {
throwMalformed(sp - 1, 1);
}
StringUTF16.putChar(dst, dp++, REPL);
sp--;
} else {
StringUTF16.putChar(dst, dp++, decode2(b1, b2));
}
continue;
}
if (!doReplace) {
throwMalformed(sp, 1); // underflow()
}
StringUTF16.putChar(dst, dp++, REPL);
break;
} else if ((b1 >> 4) == -2) {
if (sp + 1 < sl) {
int b2 = src[sp++];
int b3 = src[sp++];
if (isMalformed3(b1, b2, b3)) {
if (!doReplace) {
throwMalformed(sp - 3, 3);
}
StringUTF16.putChar(dst, dp++, REPL);
sp -= 3;
sp += malformed3(src, sp);
} else {
char c = decode3(b1, b2, b3);
if (Character.isSurrogate(c)) {
if (!doReplace) {
throwMalformed(sp - 3, 3);
}
StringUTF16.putChar(dst, dp++, REPL);
} else {
StringUTF16.putChar(dst, dp++, c);
}
}
continue;
}
if (sp < sl && isMalformed3_2(b1, src[sp])) {
if (!doReplace) {
throwMalformed(sp - 1, 2);
}
StringUTF16.putChar(dst, dp++, REPL);
continue;
}
if (!doReplace) {
throwMalformed(sp, 1);
}
StringUTF16.putChar(dst, dp++, REPL);
break;
} else if ((b1 >> 3) == -2) {
if (sp + 2 < sl) {
int b2 = src[sp++];
int b3 = src[sp++];
int b4 = src[sp++];
int uc = decode4(b1, b2, b3, b4);
if (isMalformed4(b2, b3, b4) ||
!Character.isSupplementaryCodePoint(uc)) { // shortest form check
if (!doReplace) {
throwMalformed(sp - 4, 4);
}
StringUTF16.putChar(dst, dp++, REPL);
sp -= 4;
sp += malformed4(src, sp);
} else {
StringUTF16.putChar(dst, dp++, Character.highSurrogate(uc));
StringUTF16.putChar(dst, dp++, Character.lowSurrogate(uc));
}
continue;
}
b1 &= 0xff;
if (b1 > 0xf4 || sp < sl && isMalformed4_2(b1, src[sp] & 0xff)) {
if (!doReplace) {
throwMalformed(sp - 1, 1); // or 2
}
StringUTF16.putChar(dst, dp++, REPL);
continue;
}
if (!doReplace) {
throwMalformed(sp - 1, 1);
}
sp++;
StringUTF16.putChar(dst, dp++, REPL);
if (sp < sl && isMalformed4_3(src[sp])) {
continue;
}
break;
} else {
if (!doReplace) {
throwMalformed(sp - 1, 1);
}
StringUTF16.putChar(dst, dp++, REPL);
}
}
return dp;
}
private static int decodeWithDecoder(CharsetDecoder cd, char[] dst, byte[] src, int offset, int length)
throws CharacterCodingException {
ByteBuffer bb = ByteBuffer.wrap(src, offset, length);
CharBuffer cb = CharBuffer.wrap(dst, 0, dst.length);
CoderResult cr = cd.decode(bb, cb, true);
if (!cr.isUnderflow())
cr.throwException();
cr = cd.flush(cb);
if (!cr.isUnderflow())
cr.throwException();
return cb.position();
}
private static int malformed3(byte[] src, int sp) {
int b1 = src[sp++];
int b2 = src[sp]; // no need to lookup b3
return ((b1 == (byte)0xe0 && (b2 & 0xe0) == 0x80) ||
isNotContinuation(b2)) ? 1 : 2;
}
private static int malformed4(byte[] src, int sp) {
// we don't care the speed here
int b1 = src[sp++] & 0xff;
int b2 = src[sp++] & 0xff;
if (b1 > 0xf4 ||
(b1 == 0xf0 && (b2 < 0x90 || b2 > 0xbf)) ||
(b1 == 0xf4 && (b2 & 0xf0) != 0x80) ||
isNotContinuation(b2))
return 1;
if (isNotContinuation(src[sp]))
return 2;
return 3;
}
private static void throwMalformed(int off, int nb) {
String msg = "malformed input off : " + off + ", length : " + nb;
throw new IllegalArgumentException(msg, new MalformedInputException(nb));
}
private static void throwMalformed(byte[] val) {
int dp = StringCoding.countPositives(val, 0, val.length);
throwMalformed(dp, 1);
}
private static void throwUnmappable(int off) {
String msg = "malformed input off : " + off + ", length : 1";
throw new IllegalArgumentException(msg, new UnmappableCharacterException(1));
}
private static void throwUnmappable(byte[] val) {
int dp = StringCoding.countPositives(val, 0, val.length);
throwUnmappable(dp);
}
private static byte[] encodeUTF8(byte coder, byte[] val, boolean doReplace) {
if (coder == UTF16) {
return encodeUTF8_UTF16(val, doReplace);
}
if (!StringCoding.hasNegatives(val, 0, val.length)) {
return val.clone();
}
int dp = 0;
byte[] dst = StringUTF16.newBytesFor(val.length);
for (byte c : val) {
if (c < 0) {
dst[dp++] = (byte) (0xc0 | ((c & 0xff) >> 6));
dst[dp++] = (byte) (0x80 | (c & 0x3f));
} else {
dst[dp++] = c;
}
}
if (dp == dst.length) {
return dst;
}
return Arrays.copyOf(dst, dp);
}
private static byte[] encodeUTF8_UTF16(byte[] val, boolean doReplace) {
int dp = 0;
int sp = 0;
int sl = val.length >> 1;
// UTF-8 encoded can be as much as 3 times the string length
// For very large estimate, (as in overflow of 32 bit int), precompute the exact size
long allocLen = (sl * 3 < 0) ? computeSizeUTF8_UTF16(val, doReplace) : sl * 3;
if (allocLen > (long)Integer.MAX_VALUE) {
throw new OutOfMemoryError("Required length exceeds implementation limit");
}
byte[] dst = new byte[(int) allocLen];
while (sp < sl) {
// ascii fast loop;
char c = StringUTF16.getChar(val, sp);
if (c >= '\u0080') {
break;
}
dst[dp++] = (byte)c;
sp++;
}
while (sp < sl) {
char c = StringUTF16.getChar(val, sp++);
if (c < 0x80) {
dst[dp++] = (byte)c;
} else if (c < 0x800) {
dst[dp++] = (byte)(0xc0 | (c >> 6));
dst[dp++] = (byte)(0x80 | (c & 0x3f));
} else if (Character.isSurrogate(c)) {
int uc = -1;
char c2;
if (Character.isHighSurrogate(c) && sp < sl &&
Character.isLowSurrogate(c2 = StringUTF16.getChar(val, sp))) {
uc = Character.toCodePoint(c, c2);
}
if (uc < 0) {
if (doReplace) {
dst[dp++] = '?';
} else {
throwUnmappable(sp - 1);
}
} else {
dst[dp++] = (byte)(0xf0 | ((uc >> 18)));
dst[dp++] = (byte)(0x80 | ((uc >> 12) & 0x3f));
dst[dp++] = (byte)(0x80 | ((uc >> 6) & 0x3f));
dst[dp++] = (byte)(0x80 | (uc & 0x3f));
sp++; // 2 chars
}
} else {
// 3 bytes, 16 bits
dst[dp++] = (byte)(0xe0 | ((c >> 12)));
dst[dp++] = (byte)(0x80 | ((c >> 6) & 0x3f));
dst[dp++] = (byte)(0x80 | (c & 0x3f));
}
}
if (dp == dst.length) {
return dst;
}
return Arrays.copyOf(dst, dp);
}
/**
* {@return the exact size required to UTF_8 encode this UTF16 string}
* @param val UTF16 encoded byte array
* @param doReplace true to replace unmappable characters
*/
private static long computeSizeUTF8_UTF16(byte[] val, boolean doReplace) {
long dp = 0L;
int sp = 0;
int sl = val.length >> 1;
while (sp < sl) {
char c = StringUTF16.getChar(val, sp++);
if (c < 0x80) {
dp++;
} else if (c < 0x800) {
dp += 2;
} else if (Character.isSurrogate(c)) {
int uc = -1;
char c2;
if (Character.isHighSurrogate(c) && sp < sl &&
Character.isLowSurrogate(c2 = StringUTF16.getChar(val, sp))) {
uc = Character.toCodePoint(c, c2);
}
if (uc < 0) {
if (doReplace) {
dp++;
} else {
throwUnmappable(sp - 1);
}
} else {
dp += 4;
sp++; // 2 chars
}
} else {
// 3 bytes, 16 bits
dp += 3;
}
}
return dp;
}
/**
* Constructs a new {@code String} by decoding the specified array of bytes
* using the specified {@linkplain java.nio.charset.Charset charset}. The
* length of the new {@code String} is a function of the charset, and hence
* may not be equal to the length of the byte array.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the given charset is unspecified. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* <p> The contents of the string are unspecified if the byte array
* is modified during string construction.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param charsetName
* The name of a supported {@linkplain java.nio.charset.Charset
* charset}
*
* @throws UnsupportedEncodingException
* If the named charset is not supported
*
* @since 1.1
*/
public String(byte[] bytes, String charsetName)
throws UnsupportedEncodingException {
this(lookupCharset(charsetName), bytes, 0, bytes.length);
}
/**
* Constructs a new {@code String} by decoding the specified array of
* bytes using the specified {@linkplain java.nio.charset.Charset charset}.
* The length of the new {@code String} is a function of the charset, and
* hence may not be equal to the length of the byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* <p> The contents of the string are unspecified if the byte array
* is modified during string construction.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param charset
* The {@linkplain java.nio.charset.Charset charset} to be used to
* decode the {@code bytes}
*
* @since 1.6
*/
public String(byte[] bytes, Charset charset) {
this(Objects.requireNonNull(charset), bytes, 0, bytes.length);
}
/**
* Constructs a new {@code String} by decoding the specified subarray of
* bytes using the {@link Charset#defaultCharset() default charset}.
* The length of the new {@code String} is a function of the charset,
* and hence may not be equal to the length of the subarray.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the default charset is unspecified. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* <p> The contents of the string are unspecified if the byte array
* is modified during string construction.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param offset
* The index of the first byte to decode
*
* @param length
* The number of bytes to decode
*
* @throws IndexOutOfBoundsException
* If {@code offset} is negative, {@code length} is negative, or
* {@code offset} is greater than {@code bytes.length - length}
*
* @since 1.1
*/
public String(byte[] bytes, int offset, int length) {
this(Charset.defaultCharset(), bytes, checkBoundsOffCount(offset, length, bytes.length), length);
}
/**
* Constructs a new {@code String} by decoding the specified array of bytes
* using the {@link Charset#defaultCharset() default charset}. The length
* of the new {@code String} is a function of the charset, and hence may not
* be equal to the length of the byte array.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the default charset is unspecified. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* <p> The contents of the string are unspecified if the byte array
* is modified during string construction.
*
* @param bytes
* The bytes to be decoded into characters
*
* @since 1.1
*/
public String(byte[] bytes) {
this(Charset.defaultCharset(), bytes, 0, bytes.length);
}
/**
* Allocates a new string that contains the sequence of characters
* currently contained in the string buffer argument. The contents of the
* string buffer are copied; subsequent modification of the string buffer
* does not affect the newly created string.
*
* @param buffer
* A {@code StringBuffer}
*/
public String(StringBuffer buffer) {
this(buffer.toString());
}
/**
* Allocates a new string that contains the sequence of characters
* currently contained in the string builder argument. The contents of the
* string builder are copied; subsequent modification of the string builder
* does not affect the newly created string.
*
* <p> The contents of the string are unspecified if the {@code StringBuilder}
* is modified during string construction.
*
* <p> This constructor is provided to ease migration to {@code
* StringBuilder}. Obtaining a string from a string builder via the {@code
* toString} method is likely to run faster and is generally preferred.
*
* @param builder
* A {@code StringBuilder}
*
* @since 1.5
*/
public String(StringBuilder builder) {
this(builder, null);
}
/**
* Returns the length of this string.
* The length is equal to the number of <a href="Character.html#unicode">Unicode
* code units</a> in the string.
*
* @return the length of the sequence of characters represented by this
* object.
*/
public int length() {
return value.length >> coder();
}
/**
* Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
*
* @return {@code true} if {@link #length()} is {@code 0}, otherwise
* {@code false}
*
* @since 1.6
*/
@Override
public boolean isEmpty() {
return value.length == 0;
}
/**
* Returns the {@code char} value at the
* specified index. An index ranges from {@code 0} to
* {@code length() - 1}. The first {@code char} value of the sequence
* is at index {@code 0}, the next at index {@code 1},
* and so on, as for array indexing.
*
* <p>If the {@code char} value specified by the index is a
* <a href="Character.html#unicode">surrogate</a>, the surrogate
* value is returned.
*
* @param index the index of the {@code char} value.
* @return the {@code char} value at the specified index of this string.
* The first {@code char} value is at index {@code 0}.
* @throws IndexOutOfBoundsException if the {@code index}
* argument is negative or not less than the length of this
* string.
*/
public char charAt(int index) {
if (isLatin1()) {
return StringLatin1.charAt(value, index);
} else {
return StringUTF16.charAt(value, index);
}
}
/**
* Returns the character (Unicode code point) at the specified
* index. The index refers to {@code char} values
* (Unicode code units) and ranges from {@code 0} to
* {@link #length()}{@code - 1}.
*
* <p> If the {@code char} value specified at the given index
* is in the high-surrogate range, the following index is less
* than the length of this {@code String}, and the
* {@code char} value at the following index is in the
* low-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
* the {@code char} value at the given index is returned.
*
* @param index the index to the {@code char} values
* @return the code point value of the character at the
* {@code index}
* @throws IndexOutOfBoundsException if the {@code index}
* argument is negative or not less than the length of this
* string.
* @since 1.5
*/
public int codePointAt(int index) {
if (isLatin1()) {
checkIndex(index, value.length);
return value[index] & 0xff;
}
int length = value.length >> 1;
checkIndex(index, length);
return StringUTF16.codePointAt(value, index, length);
}
/**
* Returns the character (Unicode code point) before the specified
* index. The index refers to {@code char} values
* (Unicode code units) and ranges from {@code 1} to {@link
* CharSequence#length() length}.
*
* <p> If the {@code char} value at {@code (index - 1)}
* is in the low-surrogate range, {@code (index - 2)} is not
* negative, and the {@code char} value at {@code (index -
* 2)} is in the high-surrogate range, then the
* supplementary code point value of the surrogate pair is
* returned. If the {@code char} value at {@code index -
* 1} is an unpaired low-surrogate or a high-surrogate, the
* surrogate value is returned.
*
* @param index the index following the code point that should be returned
* @return the Unicode code point value before the given index.
* @throws IndexOutOfBoundsException if the {@code index}
* argument is less than 1 or greater than the length
* of this string.
* @since 1.5
*/
public int codePointBefore(int index) {
int i = index - 1;
checkIndex(i, length());
if (isLatin1()) {
return (value[i] & 0xff);
}
return StringUTF16.codePointBefore(value, index);
}
/**
* Returns the number of Unicode code points in the specified text
* range of this {@code String}. The text range begins at the
* specified {@code beginIndex} and extends to the
* {@code char} at index {@code endIndex - 1}. Thus the
* length (in {@code char}s) of the text range is
* {@code endIndex-beginIndex}. Unpaired surrogates within
* the text range count as one code point each.
*
* @param beginIndex the index to the first {@code char} of
* the text range.
* @param endIndex the index after the last {@code char} of
* the text range.
* @return the number of Unicode code points in the specified text
* range
* @throws IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or {@code endIndex}
* is larger than the length of this {@code String}, or
* {@code beginIndex} is larger than {@code endIndex}.
* @since 1.5
*/
public int codePointCount(int beginIndex, int endIndex) {
Objects.checkFromToIndex(beginIndex, endIndex, length());
if (isLatin1()) {
return endIndex - beginIndex;
}
return StringUTF16.codePointCount(value, beginIndex, endIndex);
}
/**
* Returns the index within this {@code String} that is
* offset from the given {@code index} by
* {@code codePointOffset} code points. Unpaired surrogates
* within the text range given by {@code index} and
* {@code codePointOffset} count as one code point each.
*
* @param index the index to be offset
* @param codePointOffset the offset in code points
* @return the index within this {@code String}
* @throws IndexOutOfBoundsException if {@code index}
* is negative or larger than the length of this
* {@code String}, or if {@code codePointOffset} is positive
* and the substring starting with {@code index} has fewer
* than {@code codePointOffset} code points,
* or if {@code codePointOffset} is negative and the substring
* before {@code index} has fewer than the absolute value
* of {@code codePointOffset} code points.
* @since 1.5
*/
public int offsetByCodePoints(int index, int codePointOffset) {
return Character.offsetByCodePoints(this, index, codePointOffset);
}
/**
* Copies characters from this string into the destination character
* array.
* <p>
* The first character to be copied is at index {@code srcBegin};
* the last character to be copied is at index {@code srcEnd-1}
* (thus the total number of characters to be copied is
* {@code srcEnd-srcBegin}). The characters are copied into the
* subarray of {@code dst} starting at index {@code dstBegin}
* and ending at index:
* <blockquote><pre>
* dstBegin + (srcEnd-srcBegin) - 1
* </pre></blockquote>
*
* @param srcBegin index of the first character in the string
* to copy.
* @param srcEnd index after the last character in the string
* to copy.
* @param dst the destination array.
* @param dstBegin the start offset in the destination array.
* @throws IndexOutOfBoundsException If any of the following
* is true:
* <ul><li>{@code srcBegin} is negative.
* <li>{@code srcBegin} is greater than {@code srcEnd}
* <li>{@code srcEnd} is greater than the length of this
* string
* <li>{@code dstBegin} is negative
* <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
* {@code dst.length}</ul>
*/
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
checkBoundsBeginEnd(srcBegin, srcEnd, length());
checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
if (isLatin1()) {
StringLatin1.getChars(value, srcBegin, srcEnd, dst, dstBegin);
} else {
StringUTF16.getChars(value, srcBegin, srcEnd, dst, dstBegin);
}
}
/**
* Copies characters from this string into the destination byte array. Each
* byte receives the 8 low-order bits of the corresponding character. The
* eight high-order bits of each character are not copied and do not
* participate in the transfer in any way.
*
* <p> The first character to be copied is at index {@code srcBegin}; the
* last character to be copied is at index {@code srcEnd-1}. The total
* number of characters to be copied is {@code srcEnd-srcBegin}. The
* characters, converted to bytes, are copied into the subarray of {@code
* dst} starting at index {@code dstBegin} and ending at index:
*
* <blockquote><pre>
* dstBegin + (srcEnd-srcBegin) - 1
* </pre></blockquote>
*
* @deprecated This method does not properly convert characters into
* bytes. As of JDK 1.1, the preferred way to do this is via the
* {@link #getBytes()} method, which uses the {@link Charset#defaultCharset()
* default charset}.
*
* @param srcBegin
* Index of the first character in the string to copy
*
* @param srcEnd
* Index after the last character in the string to copy
*
* @param dst
* The destination array
*
* @param dstBegin
* The start offset in the destination array
*
* @throws IndexOutOfBoundsException
* If any of the following is true:
* <ul>
* <li> {@code srcBegin} is negative
* <li> {@code srcBegin} is greater than {@code srcEnd}
* <li> {@code srcEnd} is greater than the length of this String
* <li> {@code dstBegin} is negative
* <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
* dst.length}
* </ul>
*/
@Deprecated(since="1.1")
public void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) {
checkBoundsBeginEnd(srcBegin, srcEnd, length());
Objects.requireNonNull(dst);
checkBoundsOffCount(dstBegin, srcEnd - srcBegin, dst.length);
if (isLatin1()) {
StringLatin1.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
} else {
StringUTF16.getBytes(value, srcBegin, srcEnd, dst, dstBegin);
}
}
/**
* Encodes this {@code String} into a sequence of bytes using the named
* charset, storing the result into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in
* the given charset is unspecified. The {@link
* java.nio.charset.CharsetEncoder} class should be used when more control
* over the encoding process is required.
*
* @param charsetName
* The name of a supported {@linkplain java.nio.charset.Charset
* charset}
*
* @return The resultant byte array
*
* @throws UnsupportedEncodingException
* If the named charset is not supported
*
* @since 1.1
*/
public byte[] getBytes(String charsetName)
throws UnsupportedEncodingException {
return encode(lookupCharset(charsetName), coder(), value);
}
/**
* Encodes this {@code String} into a sequence of bytes using the given
* {@linkplain java.nio.charset.Charset charset}, storing the result into a
* new byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement byte array. The
* {@link java.nio.charset.CharsetEncoder} class should be used when more
* control over the encoding process is required.
*
* @param charset
* The {@linkplain java.nio.charset.Charset} to be used to encode
* the {@code String}
*
* @return The resultant byte array
*
* @since 1.6
*/
public byte[] getBytes(Charset charset) {
if (charset == null) throw new NullPointerException();
return encode(charset, coder(), value);
}
/**
* Encodes this {@code String} into a sequence of bytes using the
* {@link Charset#defaultCharset() default charset}, storing the result
* into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in
* the default charset is unspecified. The {@link
* java.nio.charset.CharsetEncoder} class should be used when more control
* over the encoding process is required.
*
* @return The resultant byte array
*
* @since 1.1
*/
public byte[] getBytes() {
return encode(Charset.defaultCharset(), coder(), value);
}
boolean bytesCompatible(Charset charset) {
if (isLatin1()) {
if (charset == ISO_8859_1.INSTANCE) {
return true; // ok, same encoding
} else if (charset == UTF_8.INSTANCE || charset == US_ASCII.INSTANCE) {
return !StringCoding.hasNegatives(value, 0, value.length); // ok, if ASCII-compatible
}
}
return false;
}
void copyToSegmentRaw(MemorySegment segment, long offset) {
MemorySegment.copy(value, 0, segment, ValueLayout.JAVA_BYTE, offset, value.length);
}
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* <p>For finer-grained String comparison, refer to
* {@link java.text.Collator}.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
return (anObject instanceof String aString)
&& (!COMPACT_STRINGS || this.coder == aString.coder)
&& StringLatin1.equals(value, aString.value);
}
/**
* Compares this string to the specified {@code StringBuffer}. The result
* is {@code true} if and only if this {@code String} represents the same
* sequence of characters as the specified {@code StringBuffer}. This method
* synchronizes on the {@code StringBuffer}.
*
* <p>For finer-grained String comparison, refer to
* {@link java.text.Collator}.
*
* @param sb
* The {@code StringBuffer} to compare this {@code String} against
*
* @return {@code true} if this {@code String} represents the same
* sequence of characters as the specified {@code StringBuffer},
* {@code false} otherwise
*
* @since 1.4
*/
public boolean contentEquals(StringBuffer sb) {
return contentEquals((CharSequence)sb);
}
private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
int len = length();
if (len != sb.length()) {
return false;
}
byte[] v1 = value;
byte[] v2 = sb.getValue();
byte coder = coder();
if (coder == sb.getCoder()) {
return v1.length <= v2.length && ArraysSupport.mismatch(v1, v2, v1.length) < 0;
} else {
if (coder != LATIN1) { // utf16 str and latin1 abs can never be "equal"
return false;
}
return StringUTF16.contentEquals(v1, v2, len);
}
}
/**
* Compares this string to the specified {@code CharSequence}. The
* result is {@code true} if and only if this {@code String} represents the
* same sequence of char values as the specified sequence. Note that if the
* {@code CharSequence} is a {@code StringBuffer} then the method
* synchronizes on it.
*
* <p>For finer-grained String comparison, refer to
* {@link java.text.Collator}.
*
* @param cs
* The sequence to compare this {@code String} against
*
* @return {@code true} if this {@code String} represents the same
* sequence of char values as the specified sequence, {@code
* false} otherwise
*
* @since 1.5
*/
public boolean contentEquals(CharSequence cs) {
// Argument is a StringBuffer, StringBuilder
if (cs instanceof AbstractStringBuilder) {
if (cs instanceof StringBuffer) {
synchronized(cs) {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
} else {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
}
// Argument is a String
if (cs instanceof String) {
return equals(cs);
}
// Argument is a generic CharSequence
int n = cs.length();
if (n != length()) {
return false;
}
byte[] val = this.value;
if (isLatin1()) {
for (int i = 0; i < n; i++) {
if ((val[i] & 0xff) != cs.charAt(i)) {
return false;
}
}
} else {
if (!StringUTF16.contentEquals(val, cs, n)) {
return false;
}
}
return true;
}
/**
* Compares this {@code String} to another {@code String}, ignoring case
* considerations. Two strings are considered equal ignoring case if they
* are of the same length and corresponding Unicode code points in the two
* strings are equal ignoring case.
*
* <p> Two Unicode code points are considered the same
* ignoring case if at least one of the following is true:
* <ul>
* <li> The two Unicode code points are the same (as compared by the
* {@code ==} operator)
* <li> Calling {@code Character.toLowerCase(Character.toUpperCase(int))}
* on each Unicode code point produces the same result
* </ul>
*
* <p>Note that this method does <em>not</em> take locale into account, and
* will result in unsatisfactory results for certain locales. The
* {@link java.text.Collator} class provides locale-sensitive comparison.
*
* @param anotherString
* The {@code String} to compare this {@code String} against
*
* @return {@code true} if the argument is not {@code null} and it
* represents an equivalent {@code String} ignoring case; {@code
* false} otherwise
*
* @see #equals(Object)
* @see #codePoints()
*/
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.length() == length())
&& regionMatches(true, 0, anotherString, 0, length());
}
/**
* Compares two strings lexicographically.
* The comparison is based on the Unicode value of each character in
* the strings. The character sequence represented by this
* {@code String} object is compared lexicographically to the
* character sequence represented by the argument string. The result is
* a negative integer if this {@code String} object
* lexicographically precedes the argument string. The result is a
* positive integer if this {@code String} object lexicographically
* follows the argument string. The result is zero if the strings
* are equal; {@code compareTo} returns {@code 0} exactly when
* the {@link #equals(Object)} method would return {@code true}.
* <p>
* This is the definition of lexicographic ordering. If two strings are
* different, then either they have different characters at some index
* that is a valid index for both strings, or their lengths are different,
* or both. If they have different characters at one or more index
* positions, let <i>k</i> be the smallest such index; then the string
* whose character at position <i>k</i> has the smaller value, as
* determined by using the {@code <} operator, lexicographically precedes the
* other string. In this case, {@code compareTo} returns the
* difference of the two character values at position {@code k} in
* the two string -- that is, the value:
* <blockquote><pre>
* this.charAt(k)-anotherString.charAt(k)
* </pre></blockquote>
* If there is no index position at which they differ, then the shorter
* string lexicographically precedes the longer string. In this case,
* {@code compareTo} returns the difference of the lengths of the
* strings -- that is, the value:
* <blockquote><pre>
* this.length()-anotherString.length()
* </pre></blockquote>
*
* <p>For finer-grained String comparison, refer to
* {@link java.text.Collator}.
*
* @param anotherString the {@code String} to be compared.
* @return the value {@code 0} if the argument string is equal to
* this string; a value less than {@code 0} if this string
* is lexicographically less than the string argument; and a
* value greater than {@code 0} if this string is
* lexicographically greater than the string argument.
*/
public int compareTo(String anotherString) {
byte[] v1 = value;
byte[] v2 = anotherString.value;
byte coder = coder();
if (coder == anotherString.coder()) {
return coder == LATIN1 ? StringLatin1.compareTo(v1, v2)
: StringUTF16.compareTo(v1, v2);
}
return coder == LATIN1 ? StringLatin1.compareToUTF16(v1, v2)
: StringUTF16.compareToLatin1(v1, v2);
}
/**
* A Comparator that orders {@code String} objects as by
* {@link #compareToIgnoreCase(String) compareToIgnoreCase}.
* This comparator is serializable.
* <p>
* Note that this Comparator does <em>not</em> take locale into account,
* and will result in an unsatisfactory ordering for certain locales.
* The {@link java.text.Collator} class provides locale-sensitive comparison.
*
* @see java.text.Collator
* @since 1.2
*/
public static final Comparator<String> CASE_INSENSITIVE_ORDER
= new CaseInsensitiveComparator();
/**
* CaseInsensitiveComparator for Strings.
*/
private static class CaseInsensitiveComparator
implements Comparator<String>, java.io.Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
@java.io.Serial
private static final long serialVersionUID = 8575799808933029326L;
public int compare(String s1, String s2) {
byte[] v1 = s1.value;
byte[] v2 = s2.value;
byte coder = s1.coder();
if (coder == s2.coder()) {
return coder == LATIN1 ? StringLatin1.compareToCI(v1, v2)
: StringUTF16.compareToCI(v1, v2);
}
return coder == LATIN1 ? StringLatin1.compareToCI_UTF16(v1, v2)
: StringUTF16.compareToCI_Latin1(v1, v2);
}
/** Replaces the de-serialized object. */
@java.io.Serial
private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
}
/**
* Compares two strings lexicographically, ignoring case
* differences. This method returns an integer whose sign is that of
* calling {@code compareTo} with case folded versions of the strings
* where case differences have been eliminated by calling
* {@code Character.toLowerCase(Character.toUpperCase(int))} on
* each Unicode code point.
* <p>
* Note that this method does <em>not</em> take locale into account,
* and will result in an unsatisfactory ordering for certain locales.
* The {@link java.text.Collator} class provides locale-sensitive comparison.
*
* @param str the {@code String} to be compared.
* @return a negative integer, zero, or a positive integer as the
* specified String is greater than, equal to, or less
* than this String, ignoring case considerations.
* @see java.text.Collator
* @see #codePoints()
* @since 1.2
*/
public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}
/**
* Tests if two string regions are equal.
* <p>
* A substring of this {@code String} object is compared to a substring
* of the argument other. The result is true if these substrings
* represent identical character sequences. The substring of this
* {@code String} object to be compared begins at index {@code toffset}
* and has length {@code len}. The substring of other to be compared
* begins at index {@code ooffset} and has length {@code len}. The
* result is {@code false} if and only if at least one of the following
* is true:
* <ul><li>{@code toffset} is negative.
* <li>{@code ooffset} is negative.
* <li>{@code toffset+len} is greater than the length of this
* {@code String} object.
* <li>{@code ooffset+len} is greater than the length of the other
* argument.
* <li>There is some nonnegative integer <i>k</i> less than {@code len}
* such that:
* {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + }
* <i>k</i>{@code )}
* </ul>
*
* <p>Note that this method does <em>not</em> take locale into account. The
* {@link java.text.Collator} class provides locale-sensitive comparison.
*
* @param toffset the starting offset of the subregion in this string.
* @param other the string argument.
* @param ooffset the starting offset of the subregion in the string
* argument.
* @param len the number of characters to compare.
* @return {@code true} if the specified subregion of this string
* exactly matches the specified subregion of the string argument;
* {@code false} otherwise.
*/
public boolean regionMatches(int toffset, String other, int ooffset, int len) {
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0) ||
(toffset > (long)length() - len) ||
(ooffset > (long)other.length() - len)) {
return false;
}
// Any strings match if len <= 0
if (len <= 0) {
return true;
}
byte[] tv = value;
byte[] ov = other.value;
byte coder = coder();
if (coder == other.coder()) {
if (coder == UTF16) {
toffset <<= UTF16;
ooffset <<= UTF16;
len <<= UTF16;
}
return ArraysSupport.mismatch(tv, toffset,
ov, ooffset, len) < 0;
} else {
if (coder == LATIN1) {
while (len-- > 0) {
if (StringLatin1.getChar(tv, toffset++) !=
StringUTF16.getChar(ov, ooffset++)) {
return false;
}
}
} else {
while (len-- > 0) {
if (StringUTF16.getChar(tv, toffset++) !=
StringLatin1.getChar(ov, ooffset++)) {
return false;
}
}
}
}
return true;
}
/**
* Tests if two string regions are equal.
* <p>
* A substring of this {@code String} object is compared to a substring
* of the argument {@code other}. The result is {@code true} if these
* substrings represent Unicode code point sequences that are the same,
* ignoring case if and only if {@code ignoreCase} is true.
* The sequences {@code tsequence} and {@code osequence} are compared,
* where {@code tsequence} is the sequence produced as if by calling
* {@code this.substring(toffset, toffset + len).codePoints()} and
* {@code osequence} is the sequence produced as if by calling
* {@code other.substring(ooffset, ooffset + len).codePoints()}.
* The result is {@code true} if and only if all of the following
* are true:
* <ul><li>{@code toffset} is non-negative.
* <li>{@code ooffset} is non-negative.
* <li>{@code toffset+len} is less than or equal to the length of this
* {@code String} object.
* <li>{@code ooffset+len} is less than or equal to the length of the other
* argument.
* <li>if {@code ignoreCase} is {@code false}, all pairs of corresponding Unicode
* code points are equal integer values; or if {@code ignoreCase} is {@code true},
* {@link Character#toLowerCase(int) Character.toLowerCase(}
* {@link Character#toUpperCase(int)}{@code )} on all pairs of Unicode code points
* results in equal integer values.
* </ul>
*
* <p>Note that this method does <em>not</em> take locale into account,
* and will result in unsatisfactory results for certain locales when
* {@code ignoreCase} is {@code true}. The {@link java.text.Collator} class
* provides locale-sensitive comparison.
*
* @param ignoreCase if {@code true}, ignore case when comparing
* characters.
* @param toffset the starting offset of the subregion in this
* string.
* @param other the string argument.
* @param ooffset the starting offset of the subregion in the string
* argument.
* @param len the number of characters (Unicode code units -
* 16bit {@code char} value) to compare.
* @return {@code true} if the specified subregion of this string
* matches the specified subregion of the string argument;
* {@code false} otherwise. Whether the matching is exact
* or case insensitive depends on the {@code ignoreCase}
* argument.
* @see #codePoints()
*/
public boolean regionMatches(boolean ignoreCase, int toffset,
String other, int ooffset, int len) {
if (!ignoreCase) {
return regionMatches(toffset, other, ooffset, len);
}
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)length() - len)
|| (ooffset > (long)other.length() - len)) {
return false;
}
byte[] tv = value;
byte[] ov = other.value;
byte coder = coder();
if (coder == other.coder()) {
return coder == LATIN1
? StringLatin1.regionMatchesCI(tv, toffset, ov, ooffset, len)
: StringUTF16.regionMatchesCI(tv, toffset, ov, ooffset, len);
}
return coder == LATIN1
? StringLatin1.regionMatchesCI_UTF16(tv, toffset, ov, ooffset, len)
: StringUTF16.regionMatchesCI_Latin1(tv, toffset, ov, ooffset, len);
}
/**
* Tests if the substring of this string beginning at the
* specified index starts with the specified prefix.
*
* @param prefix the prefix.
* @param toffset where to begin looking in this string.
* @return {@code true} if the character sequence represented by the
* argument is a prefix of the substring of this object starting
* at index {@code toffset}; {@code false} otherwise.
* The result is {@code false} if {@code toffset} is
* negative or greater than the length of this
* {@code String} object; otherwise the result is the same
* as the result of the expression
* <pre>
* this.substring(toffset).startsWith(prefix)
* </pre>
*/
public boolean startsWith(String prefix, int toffset) {
// Note: toffset might be near -1>>>1.
if (toffset < 0 || toffset > length() - prefix.length()) {
return false;
}
byte[] ta = value;
byte[] pa = prefix.value;
int po = 0;
int pc = pa.length;
byte coder = coder();
if (coder == prefix.coder()) {
if (coder == UTF16) {
toffset <<= UTF16;
}
return ArraysSupport.mismatch(ta, toffset,
pa, 0, pc) < 0;
} else {
if (coder == LATIN1) { // && pcoder == UTF16
return false;
}
// coder == UTF16 && pcoder == LATIN1)
while (po < pc) {
if (StringUTF16.getChar(ta, toffset++) != (pa[po++] & 0xff)) {
return false;
}
}
}
return true;
}
/**
* Tests if this string starts with the specified prefix.
*
* @param prefix the prefix.
* @return {@code true} if the character sequence represented by the
* argument is a prefix of the character sequence represented by
* this string; {@code false} otherwise.
* Note also that {@code true} will be returned if the
* argument is an empty string or is equal to this
* {@code String} object as determined by the
* {@link #equals(Object)} method.
* @since 1.0
*/
public boolean startsWith(String prefix) {
return startsWith(prefix, 0);
}
/**
* Tests if this string ends with the specified suffix.
*
* @param suffix the suffix.
* @return {@code true} if the character sequence represented by the
* argument is a suffix of the character sequence represented by
* this object; {@code false} otherwise. Note that the
* result will be {@code true} if the argument is the
* empty string or is equal to this {@code String} object
* as determined by the {@link #equals(Object)} method.
*/
public boolean endsWith(String suffix) {
return startsWith(suffix, length() - suffix.length());
}
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
// The hash or hashIsZero fields are subject to a benign data race,
// making it crucial to ensure that any observable result of the
// calculation in this method stays correct under any possible read of
// these fields. Necessary restrictions to allow this to be correct
// without explicit memory fences or similar concurrency primitives is
// that we can ever only write to one of these two fields for a given
// String instance, and that the computation is idempotent and derived
// from immutable state
int h = hash;
if (h == 0 && !hashIsZero) {
h = isLatin1() ? StringLatin1.hashCode(value)
: StringUTF16.hashCode(value);
if (h == 0) {
hashIsZero = true;
} else {
hash = h;
}
}
return h;
}
/**
* Returns the index within this string of the first occurrence of
* the specified character. If a character with value
* {@code ch} occurs in the character sequence represented by
* this {@code String} object, then the index (in Unicode
* code units) of the first such occurrence is returned. For
* values of {@code ch} in the range from 0 to 0xFFFF
* (inclusive), this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string, then {@code -1} is returned.
*
* @param ch a character (Unicode code point).
* @return the index of the first occurrence of the character in the
* character sequence represented by this object, or
* {@code -1} if the character does not occur.
*/
public int indexOf(int ch) {
return isLatin1() ? StringLatin1.indexOf(value, ch, 0, value.length)
: StringUTF16.indexOf(value, ch, 0, value.length >> 1);
}
/**
* Returns the index within this string of the first occurrence of the
* specified character, starting the search at the specified index.
* <p>
* If a character with value {@code ch} occurs in the
* character sequence represented by this {@code String}
* object at an index no smaller than {@code fromIndex}, then
* the index of the first such occurrence is returned. For values
* of {@code ch} in the range from 0 to 0xFFFF (inclusive),
* this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex)
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex)
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string at or after position {@code fromIndex}, then
* {@code -1} is returned.
*
* <p>
* There is no restriction on the value of {@code fromIndex}. If it
* is negative, it has the same effect as if it were zero: this entire
* string may be searched. If it is greater than the length of this
* string, it has the same effect as if it were equal to the length of
* this string: {@code -1} is returned.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* @param ch a character (Unicode code point).
* @param fromIndex the index to start the search from.
* @return the index of the first occurrence of the character in the
* character sequence represented by this object that is greater
* than or equal to {@code fromIndex}, or {@code -1}
* if the character does not occur.
*
* @apiNote
* Unlike {@link #substring(int)}, for example, this method does not throw
* an exception when {@code fromIndex} is outside the valid range.
* Rather, it returns -1 when {@code fromIndex} is larger than the length of
* the string.
* This result is, by itself, indistinguishable from a genuine absence of
* {@code ch} in the string.
* If stricter behavior is needed, {@link #indexOf(int, int, int)}
* should be considered instead.
* On a {@link String} {@code s}, for example,
* {@code s.indexOf(ch, fromIndex, s.length())} would throw if
* {@code fromIndex} were larger than the string length, or were negative.
*/
public int indexOf(int ch, int fromIndex) {
fromIndex = Math.max(fromIndex, 0);
return isLatin1() ? StringLatin1.indexOf(value, ch, Math.min(fromIndex, value.length), value.length)
: StringUTF16.indexOf(value, ch, Math.min(fromIndex, value.length >> 1), value.length >> 1);
}
/**
* Returns the index within this string of the first occurrence of the
* specified character, starting the search at {@code beginIndex} and
* stopping before {@code endIndex}.
*
* <p>If a character with value {@code ch} occurs in the
* character sequence represented by this {@code String}
* object at an index no smaller than {@code beginIndex} but smaller than
* {@code endIndex}, then
* the index of the first such occurrence is returned. For values
* of {@code ch} in the range from 0 to 0xFFFF (inclusive),
* this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == ch) && (beginIndex <= <i>k</i> < endIndex)
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == ch) && (beginIndex <= <i>k</i> < endIndex)
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string at or after position {@code beginIndex} and before position
* {@code endIndex}, then {@code -1} is returned.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* @param ch a character (Unicode code point).
* @param beginIndex the index to start the search from (included).
* @param endIndex the index to stop the search at (excluded).
* @return the index of the first occurrence of the character in the
* character sequence represented by this object that is greater
* than or equal to {@code beginIndex} and less than {@code endIndex},
* or {@code -1} if the character does not occur.
* @throws StringIndexOutOfBoundsException if {@code beginIndex}
* is negative, or {@code endIndex} is larger than the length of
* this {@code String} object, or {@code beginIndex} is larger than
* {@code endIndex}.
* @since 21
*/
public int indexOf(int ch, int beginIndex, int endIndex) {
checkBoundsBeginEnd(beginIndex, endIndex, length());
return isLatin1() ? StringLatin1.indexOf(value, ch, beginIndex, endIndex)
: StringUTF16.indexOf(value, ch, beginIndex, endIndex);
}
/**
* Returns the index within this string of the last occurrence of
* the specified character. For values of {@code ch} in the
* range from 0 to 0xFFFF (inclusive), the index (in Unicode code
* units) returned is the largest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string, then {@code -1} is returned. The
* {@code String} is searched backwards starting at the last
* character.
*
* @param ch a character (Unicode code point).
* @return the index of the last occurrence of the character in the
* character sequence represented by this object, or
* {@code -1} if the character does not occur.
*/
public int lastIndexOf(int ch) {
return lastIndexOf(ch, length() - 1);
}
/**
* Returns the index within this string of the last occurrence of
* the specified character, searching backward starting at the
* specified index. For values of {@code ch} in the range
* from 0 to 0xFFFF (inclusive), the index returned is the largest
* value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex)
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex)
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string at or before position {@code fromIndex}, then
* {@code -1} is returned.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* @param ch a character (Unicode code point).
* @param fromIndex the index to start the search from. There is no
* restriction on the value of {@code fromIndex}. If it is
* greater than or equal to the length of this string, it has
* the same effect as if it were equal to one less than the
* length of this string: this entire string may be searched.
* If it is negative, it has the same effect as if it were -1:
* -1 is returned.
* @return the index of the last occurrence of the character in the
* character sequence represented by this object that is less
* than or equal to {@code fromIndex}, or {@code -1}
* if the character does not occur before that point.
*/
public int lastIndexOf(int ch, int fromIndex) {
return isLatin1() ? StringLatin1.lastIndexOf(value, ch, fromIndex)
: StringUTF16.lastIndexOf(value, ch, fromIndex);
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring.
*
* <p>The returned index is the smallest value {@code k} for which:
* <pre>{@code
* this.startsWith(str, k)
* }</pre>
* If no such value of {@code k} exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the first occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str) {
byte coder = coder();
if (coder == str.coder()) {
return isLatin1() ? StringLatin1.indexOf(value, str.value)
: StringUTF16.indexOf(value, str.value);
}
if (coder == LATIN1) { // str.coder == UTF16
return -1;
}
return StringUTF16.indexOfLatin1(value, str.value);
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring, starting at the specified index.
*
* <p>The returned index is the smallest value {@code k} for which:
* <pre>{@code
* k >= Math.min(fromIndex, this.length()) &&
* this.startsWith(str, k)
* }</pre>
* If no such value of {@code k} exists, then {@code -1} is returned.
*
* @apiNote
* Unlike {@link #substring(int)}, for example, this method does not throw
* an exception when {@code fromIndex} is outside the valid range.
* Rather, it returns -1 when {@code fromIndex} is larger than the length of
* the string.
* This result is, by itself, indistinguishable from a genuine absence of
* {@code str} in the string.
* If stricter behavior is needed, {@link #indexOf(String, int, int)}
* should be considered instead.
* On {@link String} {@code s} and a non-empty {@code str}, for example,
* {@code s.indexOf(str, fromIndex, s.length())} would throw if
* {@code fromIndex} were larger than the string length, or were negative.
*
* @param str the substring to search for.
* @param fromIndex the index from which to start the search.
* @return the index of the first occurrence of the specified substring,
* starting at the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str, int fromIndex) {
return indexOf(value, coder(), length(), str, fromIndex);
}
/**
* Returns the index of the first occurrence of the specified substring
* within the specified index range of {@code this} string.
*
* <p>This method returns the same result as the one of the invocation
* <pre>{@code
* s.substring(beginIndex, endIndex).indexOf(str) + beginIndex
* }</pre>
* if the index returned by {@link #indexOf(String)} is non-negative,
* and returns -1 otherwise.
* (No substring is instantiated, though.)
*
* @param str the substring to search for.
* @param beginIndex the index to start the search from (included).
* @param endIndex the index to stop the search at (excluded).
* @return the index of the first occurrence of the specified substring
* within the specified index range,
* or {@code -1} if there is no such occurrence.
* @throws StringIndexOutOfBoundsException if {@code beginIndex}
* is negative, or {@code endIndex} is larger than the length of
* this {@code String} object, or {@code beginIndex} is larger than
* {@code endIndex}.
* @since 21
*/
public int indexOf(String str, int beginIndex, int endIndex) {
if (str.length() == 1) {
/* Simple optimization, can be omitted without behavioral impact */
return indexOf(str.charAt(0), beginIndex, endIndex);
}
checkBoundsBeginEnd(beginIndex, endIndex, length());
return indexOf(value, coder(), endIndex, str, beginIndex);
}
/**
* Code shared by String and AbstractStringBuilder to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param src the characters being searched.
* @param srcCoder the coder of the source string.
* @param srcCount last index (exclusive) in the source string.
* @param tgtStr the characters being searched for.
* @param fromIndex the index to begin searching from.
*/
static int indexOf(byte[] src, byte srcCoder, int srcCount,
String tgtStr, int fromIndex) {
fromIndex = Math.clamp(fromIndex, 0, srcCount);
int tgtCount = tgtStr.length();
if (tgtCount > srcCount - fromIndex) {
return -1;
}
if (tgtCount == 0) {
return fromIndex;
}
byte[] tgt = tgtStr.value;
byte tgtCoder = tgtStr.coder();
if (srcCoder == tgtCoder) {
return srcCoder == LATIN1
? StringLatin1.indexOf(src, srcCount, tgt, tgtCount, fromIndex)
: StringUTF16.indexOf(src, srcCount, tgt, tgtCount, fromIndex);
}
if (srcCoder == LATIN1) { // && tgtCoder == UTF16
return -1;
}
// srcCoder == UTF16 && tgtCoder == LATIN1) {
return StringUTF16.indexOfLatin1(src, srcCount, tgt, tgtCount, fromIndex);
}
/**
* Returns the index within this string of the last occurrence of the
* specified substring. The last occurrence of the empty string ""
* is considered to occur at the index value {@code this.length()}.
*
* <p>The returned index is the largest value {@code k} for which:
* <pre>{@code
* this.startsWith(str, k)
* }</pre>
* If no such value of {@code k} exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the last occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(String str) {
return lastIndexOf(str, length());
}
/**
* Returns the index within this string of the last occurrence of the
* specified substring, searching backward starting at the specified index.
*
* <p>The returned index is the largest value {@code k} for which:
* <pre>{@code
* k <= Math.min(fromIndex, this.length()) &&
* this.startsWith(str, k)
* }</pre>
* If no such value of {@code k} exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @param fromIndex the index to start the search from.
* @return the index of the last occurrence of the specified substring,
* searching backward from the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(String str, int fromIndex) {
return lastIndexOf(value, coder(), length(), str, fromIndex);
}
/**
* Code shared by String and AbstractStringBuilder to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param src the characters being searched.
* @param srcCoder coder handles the mapping between bytes/chars
* @param srcCount count of the source string.
* @param tgtStr the characters being searched for.
* @param fromIndex the index to begin searching from.
*/
static int lastIndexOf(byte[] src, byte srcCoder, int srcCount,
String tgtStr, int fromIndex) {
byte[] tgt = tgtStr.value;
byte tgtCoder = tgtStr.coder();
int tgtCount = tgtStr.length();
/*
* Check arguments; return immediately where possible. For
* consistency, don't check for null str.
*/
int rightIndex = srcCount - tgtCount;
if (fromIndex > rightIndex) {
fromIndex = rightIndex;
}
if (fromIndex < 0) {
return -1;
}
/* Empty string always matches. */
if (tgtCount == 0) {
return fromIndex;
}
if (srcCoder == tgtCoder) {
return srcCoder == LATIN1
? StringLatin1.lastIndexOf(src, srcCount, tgt, tgtCount, fromIndex)
: StringUTF16.lastIndexOf(src, srcCount, tgt, tgtCount, fromIndex);
}
if (srcCoder == LATIN1) { // && tgtCoder == UTF16
return -1;
}
// srcCoder == UTF16 && tgtCoder == LATIN1
return StringUTF16.lastIndexOfLatin1(src, srcCount, tgt, tgtCount, fromIndex);
}
/**
* Returns a string that is a substring of this string. The
* substring begins with the character at the specified index and
* extends to the end of this string. <p>
* Examples:
* <blockquote><pre>
* "unhappy".substring(2) returns "happy"
* "Harbison".substring(3) returns "bison"
* "emptiness".substring(9) returns "" (an empty string)
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @return the specified substring.
* @throws IndexOutOfBoundsException if
* {@code beginIndex} is negative or larger than the
* length of this {@code String} object.
*/
public String substring(int beginIndex) {
return substring(beginIndex, length());
}
/**
* Returns a string that is a substring of this string. The
* substring begins at the specified {@code beginIndex} and
* extends to the character at index {@code endIndex - 1}.
* Thus the length of the substring is {@code endIndex-beginIndex}.
* <p>
* Examples:
* <blockquote><pre>
* "hamburger".substring(4, 8) returns "urge"
* "smiles".substring(1, 5) returns "mile"
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @throws IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or
* {@code endIndex} is larger than the length of
* this {@code String} object, or
* {@code beginIndex} is larger than
* {@code endIndex}.
*/
public String substring(int beginIndex, int endIndex) {
int length = length();
checkBoundsBeginEnd(beginIndex, endIndex, length);
if (beginIndex == 0 && endIndex == length) {
return this;
}
int subLen = endIndex - beginIndex;
return isLatin1() ? StringLatin1.newString(value, beginIndex, subLen)
: StringUTF16.newString(value, beginIndex, subLen);
}
/**
* Returns a character sequence that is a subsequence of this sequence.
*
* <p> An invocation of this method of the form
*
* <blockquote><pre>
* str.subSequence(begin, end)</pre></blockquote>
*
* behaves in exactly the same way as the invocation
*
* <blockquote><pre>
* str.substring(begin, end)</pre></blockquote>
*
* @apiNote
* This method is defined so that the {@code String} class can implement
* the {@link CharSequence} interface.
*
* @param beginIndex the begin index, inclusive.
* @param endIndex the end index, exclusive.
* @return the specified subsequence.
*
* @throws IndexOutOfBoundsException
* if {@code beginIndex} or {@code endIndex} is negative,
* if {@code endIndex} is greater than {@code length()},
* or if {@code beginIndex} is greater than {@code endIndex}
*
* @since 1.4
*/
public CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
/**
* Concatenates the specified string to the end of this string.
* <p>
* If the length of the argument string is {@code 0}, then this
* {@code String} object is returned. Otherwise, a
* {@code String} object is returned that represents a character
* sequence that is the concatenation of the character sequence
* represented by this {@code String} object and the character
* sequence represented by the argument string.<p>
* Examples:
* <blockquote><pre>
* "cares".concat("s") returns "caress"
* "to".concat("get").concat("her") returns "together"
* </pre></blockquote>
*
* @param str the {@code String} that is concatenated to the end
* of this {@code String}.
* @return a string that represents the concatenation of this object's
* characters followed by the string argument's characters.
*/
public String concat(String str) {
if (str.isEmpty()) {
return this;
}
return StringConcatHelper.simpleConcat(this, str);
}
/**
* Returns a string resulting from replacing all occurrences of
* {@code oldChar} in this string with {@code newChar}.
* <p>
* If the character {@code oldChar} does not occur in the
* character sequence represented by this {@code String} object,
* then a reference to this {@code String} object is returned.
* Otherwise, a {@code String} object is returned that
* represents a character sequence identical to the character sequence
* represented by this {@code String} object, except that every
* occurrence of {@code oldChar} is replaced by an occurrence
* of {@code newChar}.
* <p>
* Examples:
* <blockquote><pre>
* "mesquite in your cellar".replace('e', 'o')
* returns "mosquito in your collar"
* "the war of baronets".replace('r', 'y')
* returns "the way of bayonets"
* "sparring with a purple porpoise".replace('p', 't')
* returns "starring with a turtle tortoise"
* "JonL".replace('q', 'x') returns "JonL" (no change)
* </pre></blockquote>
*
* @param oldChar the old character.
* @param newChar the new character.
* @return a string derived from this string by replacing every
* occurrence of {@code oldChar} with {@code newChar}.
*/
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
String ret = isLatin1() ? StringLatin1.replace(value, oldChar, newChar)
: StringUTF16.replace(value, oldChar, newChar);
if (ret != null) {
return ret;
}
}
return this;
}
/**
* Tells whether or not this string matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the
* same result as the expression
*
* <blockquote>
* {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence)
* matches(<i>regex</i>, <i>str</i>)}
* </blockquote>
*
* @param regex
* the regular expression to which this string is to be matched
*
* @return {@code true} if, and only if, this string matches the
* given regular expression
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
*/
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
/**
* Returns true if and only if this string contains the specified
* sequence of char values.
*
* @param s the sequence to search for
* @return true if this string contains {@code s}, false otherwise
* @since 1.5
*/
public boolean contains(CharSequence s) {
return indexOf(s.toString()) >= 0;
}
/**
* Replaces the first substring of this string that matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a> with the
* given replacement.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
* yields exactly the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile(String) compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
* java.util.regex.Matcher#replaceFirst(String) replaceFirst}(<i>repl</i>)
* </code>
* </blockquote>
*
*<p>
* Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
* replacement string may cause the results to be different than if it were
* being treated as a literal replacement string; see
* {@link java.util.regex.Matcher#replaceFirst}.
* Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
* meaning of these characters, if desired.
*
* @param regex
* the regular expression to which this string is to be matched
* @param replacement
* the string to be substituted for the first match
*
* @return The resulting {@code String}
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
*/
public String replaceFirst(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}
/**
* Replaces each substring of this string that matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a> with the
* given replacement.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
* yields exactly the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile(String) compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
* java.util.regex.Matcher#replaceAll(String) replaceAll}(<i>repl</i>)
* </code>
* </blockquote>
*
*<p>
* Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
* replacement string may cause the results to be different than if it were
* being treated as a literal replacement string; see
* {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
* Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
* meaning of these characters, if desired.
*
* @param regex
* the regular expression to which this string is to be matched
* @param replacement
* the string to be substituted for each match
*
* @return The resulting {@code String}
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
*/
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
/**
* Replaces each substring of this string that matches the literal target
* sequence with the specified literal replacement sequence. The
* replacement proceeds from the beginning of the string to the end, for
* example, replacing "aa" with "b" in the string "aaa" will result in
* "ba" rather than "ab".
*
* @param target The sequence of char values to be replaced
* @param replacement The replacement sequence of char values
* @return The resulting string
* @since 1.5
*/
public String replace(CharSequence target, CharSequence replacement) {
String trgtStr = target.toString();
String replStr = replacement.toString();
int thisLen = length();
int trgtLen = trgtStr.length();
int replLen = replStr.length();
if (trgtLen > 0) {
if (trgtLen == 1 && replLen == 1) {
return replace(trgtStr.charAt(0), replStr.charAt(0));
}
boolean thisIsLatin1 = this.isLatin1();
boolean trgtIsLatin1 = trgtStr.isLatin1();
boolean replIsLatin1 = replStr.isLatin1();
String ret = (thisIsLatin1 && trgtIsLatin1 && replIsLatin1)
? StringLatin1.replace(value, thisLen,
trgtStr.value, trgtLen,
replStr.value, replLen)
: StringUTF16.replace(value, thisLen, thisIsLatin1,
trgtStr.value, trgtLen, trgtIsLatin1,
replStr.value, replLen, replIsLatin1);
if (ret != null) {
return ret;
}
return this;
} else { // trgtLen == 0
int resultLen;
try {
resultLen = Math.addExact(thisLen, Math.multiplyExact(
Math.addExact(thisLen, 1), replLen));
} catch (ArithmeticException ignored) {
throw new OutOfMemoryError("Required length exceeds implementation limit");
}
StringBuilder sb = new StringBuilder(resultLen);
sb.append(replStr);
for (int i = 0; i < thisLen; ++i) {
sb.append(charAt(i)).append(replStr);
}
return sb.toString();
}
}
/**
* Splits this string around matches of the given
* <a href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> The array returned by this method contains each substring of this
* string that is terminated by another substring that matches the given
* expression or is terminated by the end of the string. The substrings in
* the array are in the order in which they occur in this string. If the
* expression does not match any part of the input then the resulting array
* has just one element, namely this string.
*
* <p> When there is a positive-width match at the beginning of this
* string then an empty leading substring is included at the beginning
* of the resulting array. A zero-width match at the beginning however
* never produces such empty leading substring.
*
* <p> The {@code limit} parameter controls the number of times the
* pattern is applied and therefore affects the length of the resulting
* array.
* <ul>
* <li><p>
* If the <i>limit</i> is positive then the pattern will be applied
* at most <i>limit</i> - 1 times, the array's length will be
* no greater than <i>limit</i>, and the array's last entry will contain
* all input beyond the last matched delimiter.</p></li>
*
* <li><p>
* If the <i>limit</i> is zero then the pattern will be applied as
* many times as possible, the array can have any length, and trailing
* empty strings will be discarded.</p></li>
*
* <li><p>
* If the <i>limit</i> is negative then the pattern will be applied
* as many times as possible and the array can have any length.</p></li>
* </ul>
*
* <p> The string {@code "boo:and:foo"}, for example, yields the
* following results with these parameters:
*
* <blockquote><table class="plain">
* <caption style="display:none">Split example showing regex, limit, and result</caption>
* <thead>
* <tr>
* <th scope="col">Regex</th>
* <th scope="col">Limit</th>
* <th scope="col">Result</th>
* </tr>
* </thead>
* <tbody>
* <tr><th scope="row" rowspan="3" style="font-weight:normal">:</th>
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">2</th>
* <td>{@code { "boo", "and:foo" }}</td></tr>
* <tr><!-- : -->
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><!-- : -->
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><th scope="row" rowspan="3" style="font-weight:normal">o</th>
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
* <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
* <tr><!-- o -->
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-2</th>
* <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
* <tr><!-- o -->
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">0</th>
* <td>{@code { "b", "", ":and:f" }}</td></tr>
* </tbody>
* </table></blockquote>
*
* <p> An invocation of this method of the form
* <i>str.</i>{@code split(}<i>regex</i>{@code ,} <i>n</i>{@code )}
* yields the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile(String) compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>, <i>n</i>)
* </code>
* </blockquote>
*
*
* @param regex
* the delimiting regular expression
*
* @param limit
* the result threshold, as described above
*
* @return the array of strings computed by splitting this string
* around matches of the given regular expression
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
*/
public String[] split(String regex, int limit) {
return split(regex, limit, false);
}
/**
* Splits this string around matches of the given regular expression and
* returns both the strings and the matching delimiters.
*
* <p> The array returned by this method contains each substring of this
* string that is terminated by another substring that matches the given
* expression or is terminated by the end of the string.
* Each substring is immediately followed by the subsequence (the delimiter)
* that matches the given expression, <em>except</em> for the last
* substring, which is not followed by anything.
* The substrings in the array and the delimiters are in the order in which
* they occur in the input.
* If the expression does not match any part of the input then the resulting
* array has just one element, namely this string.
*
* <p> When there is a positive-width match at the beginning of this
* string then an empty leading substring is included at the beginning
* of the resulting array. A zero-width match at the beginning however
* never produces such empty leading substring nor the empty delimiter.
*
* <p> The {@code limit} parameter controls the number of times the
* pattern is applied and therefore affects the length of the resulting
* array.
* <ul>
* <li> If the <i>limit</i> is positive then the pattern will be applied
* at most <i>limit</i> - 1 times, the array's length will be
* no greater than 2 × <i>limit</i> - 1, and the array's last
* entry will contain all input beyond the last matched delimiter.</li>
*
* <li> If the <i>limit</i> is zero then the pattern will be applied as
* many times as possible, the array can have any length, and trailing
* empty strings will be discarded.</li>
*
* <li> If the <i>limit</i> is negative then the pattern will be applied
* as many times as possible and the array can have any length.</li>
* </ul>
*
* <p> The input {@code "boo:::and::foo"}, for example, yields the following
* results with these parameters:
*
* <table class="plain" style="margin-left:2em;">
* <caption style="display:none">Split example showing regex, limit, and result</caption>
* <thead>
* <tr>
* <th scope="col">Regex</th>
* <th scope="col">Limit</th>
* <th scope="col">Result</th>
* </tr>
* </thead>
* <tbody>
* <tr><th scope="row" rowspan="3" style="font-weight:normal">:+</th>
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">2</th>
* <td>{@code { "boo", ":::", "and::foo" }}</td></tr>
* <tr><!-- : -->
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
* <td>{@code { "boo", ":::", "and", "::", "foo" }}</td></tr>
* <tr><!-- : -->
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-1</th>
* <td>{@code { "boo", ":::", "and", "::", "foo" }}</td></tr>
* <tr><th scope="row" rowspan="3" style="font-weight:normal">o</th>
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">5</th>
* <td>{@code { "b", "o", "", "o", ":::and::f", "o", "", "o", "" }}</td></tr>
* <tr><!-- o -->
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">-1</th>
* <td>{@code { "b", "o", "", "o", ":::and::f", "o", "", "o", "" }}</td></tr>
* <tr><!-- o -->
* <th scope="row" style="font-weight:normal; text-align:right; padding-right:1em">0</th>
* <td>{@code { "b", "o", "", "o", ":::and::f", "o", "", "o" }}</td></tr>
* </tbody>
* </table>
*
* @apiNote An invocation of this method of the form
* <i>str.</i>{@code splitWithDelimiters(}<i>regex</i>{@code ,} <i>n</i>{@code )}
* yields the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile(String) compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#splitWithDelimiters(CharSequence,int) splitWithDelimiters}(<i>str</i>, <i>n</i>)
* </code>
* </blockquote>
*
* @param regex
* the delimiting regular expression
*
* @param limit
* the result threshold, as described above
*
* @return the array of strings computed by splitting this string
* around matches of the given regular expression, alternating
* substrings and matching delimiters
*
* @since 21
*/
public String[] splitWithDelimiters(String regex, int limit) {
return split(regex, limit, true);
}
private String[] split(String regex, int limit, boolean withDelimiters) {
/* fastpath if the regex is a
* (1) one-char String and this character is not one of the
* RegEx's meta characters ".$|()[{^?*+\\", or
* (2) two-char String and the first char is the backslash and
* the second is not the ascii digit or ascii letter.
*/
char ch = 0;
if (((regex.length() == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
// All the checks above can potentially be constant folded by
// a JIT/AOT compiler when the regex is a constant string.
// That requires method inlining of the checks, which is only
// possible when the actual split logic is in a separate method
// because the large split loop can usually not be inlined.
return split(ch, limit, withDelimiters);
}
Pattern pattern = Pattern.compile(regex);
return withDelimiters
? pattern.splitWithDelimiters(this, limit)
: pattern.split(this, limit);
}
private String[] split(char ch, int limit, boolean withDelimiters) {
int matchCount = 0;
int off = 0;
int next;
boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<>();
String del = withDelimiters ? String.valueOf(ch) : null;
while ((next = indexOf(ch, off)) != -1) {
if (!limited || matchCount < limit - 1) {
list.add(substring(off, next));
if (withDelimiters) {
list.add(del);
}
off = next + 1;
++matchCount;
} else { // last one
int last = length();
list.add(substring(off, last));
off = last;
++matchCount;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[] {this};
// Add remaining segment
if (!limited || matchCount < limit)
list.add(substring(off, length()));
// Construct result
int resultSize = list.size();
if (limit == 0) {
while (resultSize > 0 && list.get(resultSize - 1).isEmpty()) {
resultSize--;
}
}
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
/**
* Splits this string around matches of the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> This method works as if by invoking the two-argument {@link
* #split(String, int) split} method with the given expression and a limit
* argument of zero. Trailing empty strings are therefore not included in
* the resulting array.
*
* <p> The string {@code "boo:and:foo"}, for example, yields the following
* results with these expressions:
*
* <blockquote><table class="plain">
* <caption style="display:none">Split examples showing regex and result</caption>
* <thead>
* <tr>
* <th scope="col">Regex</th>
* <th scope="col">Result</th>
* </tr>
* </thead>
* <tbody>
* <tr><th scope="row" style="font-weight:normal">:</th>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><th scope="row" style="font-weight:normal">o</th>
* <td>{@code { "b", "", ":and:f" }}</td></tr>
* </tbody>
* </table></blockquote>
*
*
* @param regex
* the delimiting regular expression
*
* @return the array of strings computed by splitting this string
* around matches of the given regular expression
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
*/
public String[] split(String regex) {
return split(regex, 0, false);
}
/**
* Returns a new String composed of copies of the
* {@code CharSequence elements} joined together with a copy of
* the specified {@code delimiter}.
*
* <blockquote>For example,
* <pre>{@code
* String message = String.join("-", "Java", "is", "cool");
* // message returned is: "Java-is-cool"
* }</pre></blockquote>
*
* Note that if an element is null, then {@code "null"} is added.
*
* @param delimiter the delimiter that separates each element
* @param elements the elements to join together.
*
* @return a new {@code String} that is composed of the {@code elements}
* separated by the {@code delimiter}
*
* @throws NullPointerException If {@code delimiter} or {@code elements}
* is {@code null}
*
* @see java.util.StringJoiner
* @since 1.8
*/
public static String join(CharSequence delimiter, CharSequence... elements) {
var delim = delimiter.toString();
var elems = new String[elements.length];
for (int i = 0; i < elements.length; i++) {
elems[i] = String.valueOf(elements[i]);
}
return join("", "", delim, elems, elems.length);
}
/**
* Designated join routine.
*
* @param prefix the non-null prefix
* @param suffix the non-null suffix
* @param delimiter the non-null delimiter
* @param elements the non-null array of non-null elements
* @param size the number of elements in the array (<= elements.length)
* @return the joined string
*/
@ForceInline
static String join(String prefix, String suffix, String delimiter, String[] elements, int size) {
int icoder = prefix.coder() | suffix.coder();
long len = (long) prefix.length() + suffix.length();
if (size > 1) { // when there are more than one element, size - 1 delimiters will be emitted
len += (long) (size - 1) * delimiter.length();
icoder |= delimiter.coder();
}
// assert len > 0L; // max: (long) Integer.MAX_VALUE << 32
// following loop will add max: (long) Integer.MAX_VALUE * Integer.MAX_VALUE to len
// so len can overflow at most once
for (int i = 0; i < size; i++) {
var el = elements[i];
len += el.length();
icoder |= el.coder();
}
byte coder = (byte) icoder;
// long len overflow check, char -> byte length, int len overflow check
if (len < 0L || (len <<= coder) != (int) len) {
throw new OutOfMemoryError("Requested string length exceeds VM limit");
}
byte[] value = StringConcatHelper.newArray(len);
int off = 0;
prefix.getBytes(value, off, coder); off += prefix.length();
if (size > 0) {
var el = elements[0];
el.getBytes(value, off, coder); off += el.length();
for (int i = 1; i < size; i++) {
delimiter.getBytes(value, off, coder); off += delimiter.length();
el = elements[i];
el.getBytes(value, off, coder); off += el.length();
}
}
suffix.getBytes(value, off, coder);
// assert off + suffix.length() == value.length >> coder;
return new String(value, coder);
}
/**
* Returns a new {@code String} composed of copies of the
* {@code CharSequence elements} joined together with a copy of the
* specified {@code delimiter}.
*
* <blockquote>For example,
* <pre>{@code
* List<String> strings = List.of("Java", "is", "cool");
* String message = String.join(" ", strings);
* // message returned is: "Java is cool"
*
* Set<String> strings =
* new LinkedHashSet<>(List.of("Java", "is", "very", "cool"));
* String message = String.join("-", strings);
* // message returned is: "Java-is-very-cool"
* }</pre></blockquote>
*
* Note that if an individual element is {@code null}, then {@code "null"} is added.
*
* @param delimiter a sequence of characters that is used to separate each
* of the {@code elements} in the resulting {@code String}
* @param elements an {@code Iterable} that will have its {@code elements}
* joined together.
*
* @return a new {@code String} that is composed from the {@code elements}
* argument
*
* @throws NullPointerException If {@code delimiter} or {@code elements}
* is {@code null}
*
* @see #join(CharSequence,CharSequence...)
* @see java.util.StringJoiner
* @since 1.8
*/
public static String join(CharSequence delimiter,
Iterable<? extends CharSequence> elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
var delim = delimiter.toString();
var elems = new String[8];
int size = 0;
for (CharSequence cs: elements) {
if (size >= elems.length) {
elems = Arrays.copyOf(elems, elems.length << 1);
}
elems[size++] = String.valueOf(cs);
}
return join("", "", delim, elems, size);
}
/**
* Converts all of the characters in this {@code String} to lower
* case using the rules of the given {@code Locale}. Case mapping is based
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
* class. Since case mappings are not always 1:1 char mappings, the resulting {@code String}
* and this {@code String} may differ in length.
* <p>
* Examples of lowercase mappings are in the following table:
* <table class="plain">
* <caption style="display:none">Lowercase mapping examples showing language code of locale, upper case, lower case, and description</caption>
* <thead>
* <tr>
* <th scope="col">Language Code of Locale</th>
* <th scope="col">Upper Case</th>
* <th scope="col">Lower Case</th>
* <th scope="col">Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>tr (Turkish)</td>
* <th scope="row" style="font-weight:normal; text-align:left">\u0130</th>
* <td>\u0069</td>
* <td>capital letter I with dot above -> small letter i</td>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <th scope="row" style="font-weight:normal; text-align:left">\u0049</th>
* <td>\u0131</td>
* <td>capital letter I -> small letter dotless i </td>
* </tr>
* <tr>
* <td>(all)</td>
* <th scope="row" style="font-weight:normal; text-align:left">French Fries</th>
* <td>french fries</td>
* <td>lowercased all chars in String</td>
* </tr>
* <tr>
* <td>(all)</td>
* <th scope="row" style="font-weight:normal; text-align:left">
* ΙΧΘΥΣ</th>
* <td>ιχθυσ</td>
* <td>lowercased all chars in String</td>
* </tr>
* </tbody>
* </table>
*
* @param locale use the case transformation rules for this locale
* @return the {@code String}, converted to lowercase.
* @see java.lang.String#toLowerCase()
* @see java.lang.String#toUpperCase()
* @see java.lang.String#toUpperCase(Locale)
* @since 1.1
*/
public String toLowerCase(Locale locale) {
return isLatin1() ? StringLatin1.toLowerCase(this, value, locale)
: StringUTF16.toLowerCase(this, value, locale);
}
/**
* Converts all of the characters in this {@code String} to lower
* case using the rules of the default locale. This method is equivalent to
* {@code toLowerCase(Locale.getDefault())}.
*
* @apiNote This method is locale sensitive, and may produce unexpected
* results if used for strings that are intended to be interpreted locale
* independently.
* Examples are programming language identifiers, protocol keys, and HTML
* tags.
* For instance, {@code "TITLE".toLowerCase()} in a Turkish locale
* returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the
* LATIN SMALL LETTER DOTLESS I character.
* To obtain correct results for locale insensitive strings, use
* {@code toLowerCase(Locale.ROOT)}.
*
* @return the {@code String}, converted to lowercase.
* @see java.lang.String#toLowerCase(Locale)
*/
public String toLowerCase() {
return toLowerCase(Locale.getDefault());
}
/**
* Converts all of the characters in this {@code String} to upper
* case using the rules of the given {@code Locale}. Case mapping is based
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
* class. Since case mappings are not always 1:1 char mappings, the resulting {@code String}
* and this {@code String} may differ in length.
* <p>
* Examples of locale-sensitive and 1:M case mappings are in the following table:
* <table class="plain">
* <caption style="display:none">Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.</caption>
* <thead>
* <tr>
* <th scope="col">Language Code of Locale</th>
* <th scope="col">Lower Case</th>
* <th scope="col">Upper Case</th>
* <th scope="col">Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>tr (Turkish)</td>
* <th scope="row" style="font-weight:normal; text-align:left">\u0069</th>
* <td>\u0130</td>
* <td>small letter i -> capital letter I with dot above</td>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <th scope="row" style="font-weight:normal; text-align:left">\u0131</th>
* <td>\u0049</td>
* <td>small letter dotless i -> capital letter I</td>
* </tr>
* <tr>
* <td>(all)</td>
* <th scope="row" style="font-weight:normal; text-align:left">\u00df</th>
* <td>\u0053 \u0053</td>
* <td>small letter sharp s -> two letters: SS</td>
* </tr>
* <tr>
* <td>(all)</td>
* <th scope="row" style="font-weight:normal; text-align:left">Fahrvergnügen</th>
* <td>FAHRVERGNÜGEN</td>
* <td></td>
* </tr>
* </tbody>
* </table>
* @param locale use the case transformation rules for this locale
* @return the {@code String}, converted to uppercase.
* @see java.lang.String#toUpperCase()
* @see java.lang.String#toLowerCase()
* @see java.lang.String#toLowerCase(Locale)
* @since 1.1
*/
public String toUpperCase(Locale locale) {
return isLatin1() ? StringLatin1.toUpperCase(this, value, locale)
: StringUTF16.toUpperCase(this, value, locale);
}
/**
* Converts all of the characters in this {@code String} to upper
* case using the rules of the default locale. This method is equivalent to
* {@code toUpperCase(Locale.getDefault())}.
*
* @apiNote This method is locale sensitive, and may produce unexpected
* results if used for strings that are intended to be interpreted locale
* independently.
* Examples are programming language identifiers, protocol keys, and HTML
* tags.
* For instance, {@code "title".toUpperCase()} in a Turkish locale
* returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the
* LATIN CAPITAL LETTER I WITH DOT ABOVE character.
* To obtain correct results for locale insensitive strings, use
* {@code toUpperCase(Locale.ROOT)}.
*
* @return the {@code String}, converted to uppercase.
* @see java.lang.String#toUpperCase(Locale)
*/
public String toUpperCase() {
return toUpperCase(Locale.getDefault());
}
/**
* Returns a string whose value is this string, with all leading
* and trailing space removed, where space is defined
* as any character whose codepoint is less than or equal to
* {@code 'U+0020'} (the space character).
* <p>
* If this {@code String} object represents an empty character
* sequence, or the first and last characters of character sequence
* represented by this {@code String} object both have codes
* that are not space (as defined above), then a
* reference to this {@code String} object is returned.
* <p>
* Otherwise, if all characters in this string are space (as
* defined above), then a {@code String} object representing an
* empty string is returned.
* <p>
* Otherwise, let <i>k</i> be the index of the first character in the
* string whose code is not a space (as defined above) and let
* <i>m</i> be the index of the last character in the string whose code
* is not a space (as defined above). A {@code String}
* object is returned, representing the substring of this string that
* begins with the character at index <i>k</i> and ends with the
* character at index <i>m</i>-that is, the result of
* {@code this.substring(k, m + 1)}.
* <p>
* This method may be used to trim space (as defined above) from
* the beginning and end of a string.
*
* @return a string whose value is this string, with all leading
* and trailing space removed, or this string if it
* has no leading or trailing space.
*/
public String trim() {
String ret = isLatin1() ? StringLatin1.trim(value)
: StringUTF16.trim(value);
return ret == null ? this : ret;
}
/**
* Returns a string whose value is this string, with all leading
* and trailing {@linkplain Character#isWhitespace(int) white space}
* removed.
* <p>
* If this {@code String} object represents an empty string,
* or if all code points in this string are
* {@linkplain Character#isWhitespace(int) white space}, then an empty string
* is returned.
* <p>
* Otherwise, returns a substring of this string beginning with the first
* code point that is not a {@linkplain Character#isWhitespace(int) white space}
* up to and including the last code point that is not a
* {@linkplain Character#isWhitespace(int) white space}.
* <p>
* This method may be used to strip
* {@linkplain Character#isWhitespace(int) white space} from
* the beginning and end of a string.
*
* @return a string whose value is this string, with all leading
* and trailing white space removed
*
* @see Character#isWhitespace(int)
*
* @since 11
*/
public String strip() {
String ret = isLatin1() ? StringLatin1.strip(value)
: StringUTF16.strip(value);
return ret == null ? this : ret;
}
/**
* Returns a string whose value is this string, with all leading
* {@linkplain Character#isWhitespace(int) white space} removed.
* <p>
* If this {@code String} object represents an empty string,
* or if all code points in this string are
* {@linkplain Character#isWhitespace(int) white space}, then an empty string
* is returned.
* <p>
* Otherwise, returns a substring of this string beginning with the first
* code point that is not a {@linkplain Character#isWhitespace(int) white space}
* up to and including the last code point of this string.
* <p>
* This method may be used to trim
* {@linkplain Character#isWhitespace(int) white space} from
* the beginning of a string.
*
* @return a string whose value is this string, with all leading white
* space removed
*
* @see Character#isWhitespace(int)
*
* @since 11
*/
public String stripLeading() {
String ret = isLatin1() ? StringLatin1.stripLeading(value)
: StringUTF16.stripLeading(value);
return ret == null ? this : ret;
}
/**
* Returns a string whose value is this string, with all trailing
* {@linkplain Character#isWhitespace(int) white space} removed.
* <p>
* If this {@code String} object represents an empty string,
* or if all characters in this string are
* {@linkplain Character#isWhitespace(int) white space}, then an empty string
* is returned.
* <p>
* Otherwise, returns a substring of this string beginning with the first
* code point of this string up to and including the last code point
* that is not a {@linkplain Character#isWhitespace(int) white space}.
* <p>
* This method may be used to trim
* {@linkplain Character#isWhitespace(int) white space} from
* the end of a string.
*
* @return a string whose value is this string, with all trailing white
* space removed
*
* @see Character#isWhitespace(int)
*
* @since 11
*/
public String stripTrailing() {
String ret = isLatin1() ? StringLatin1.stripTrailing(value)
: StringUTF16.stripTrailing(value);
return ret == null ? this : ret;
}
/**
* Returns {@code true} if the string is empty or contains only
* {@linkplain Character#isWhitespace(int) white space} codepoints,
* otherwise {@code false}.
*
* @return {@code true} if the string is empty or contains only
* {@linkplain Character#isWhitespace(int) white space} codepoints,
* otherwise {@code false}
*
* @see Character#isWhitespace(int)
*
* @since 11
*/
public boolean isBlank() {
return indexOfNonWhitespace() == length();
}
/**
* Returns a stream of lines extracted from this string,
* separated by line terminators.
* <p>
* A <i>line terminator</i> is one of the following:
* a line feed character {@code "\n"} (U+000A),
* a carriage return character {@code "\r"} (U+000D),
* or a carriage return followed immediately by a line feed
* {@code "\r\n"} (U+000D U+000A).
* <p>
* A <i>line</i> is either a sequence of zero or more characters
* followed by a line terminator, or it is a sequence of one or
* more characters followed by the end of the string. A
* line does not include the line terminator.
* <p>
* The stream returned by this method contains the lines from
* this string in the order in which they occur.
*
* @apiNote This definition of <i>line</i> implies that an empty
* string has zero lines and that there is no empty line
* following a line terminator at the end of a string.
*
* @implNote This method provides better performance than
* split("\R") by supplying elements lazily and
* by faster search of new line terminators.
*
* @return the stream of lines extracted from this string
*
* @since 11
*/
public Stream<String> lines() {
return isLatin1() ? StringLatin1.lines(value) : StringUTF16.lines(value);
}
/**
* Adjusts the indentation of each line of this string based on the value of
* {@code n}, and normalizes line termination characters.
* <p>
* This string is conceptually separated into lines using
* {@link String#lines()}. Each line is then adjusted as described below
* and then suffixed with a line feed {@code "\n"} (U+000A). The resulting
* lines are then concatenated and returned.
* <p>
* If {@code n > 0} then {@code n} spaces (U+0020) are inserted at the
* beginning of each line.
* <p>
* If {@code n < 0} then up to {@code n}
* {@linkplain Character#isWhitespace(int) white space characters} are removed
* from the beginning of each line. If a given line does not contain
* sufficient white space then all leading
* {@linkplain Character#isWhitespace(int) white space characters} are removed.
* Each white space character is treated as a single character. In
* particular, the tab character {@code "\t"} (U+0009) is considered a
* single character; it is not expanded.
* <p>
* If {@code n == 0} then the line remains unchanged. However, line
* terminators are still normalized.
*
* @param n number of leading
* {@linkplain Character#isWhitespace(int) white space characters}
* to add or remove
*
* @return string with indentation adjusted and line endings normalized
*
* @see String#lines()
* @see String#isBlank()
* @see Character#isWhitespace(int)
*
* @since 12
*/
public String indent(int n) {
if (isEmpty()) {
return "";
}
Stream<String> stream = lines();
if (n > 0) {
final String spaces = " ".repeat(n);
stream = stream.map(s -> spaces + s);
} else if (n == Integer.MIN_VALUE) {
stream = stream.map(s -> s.stripLeading());
} else if (n < 0) {
stream = stream.map(s -> s.substring(Math.min(-n, s.indexOfNonWhitespace())));
}
return stream.collect(Collectors.joining("\n", "", "\n"));
}
private int indexOfNonWhitespace() {
return isLatin1() ? StringLatin1.indexOfNonWhitespace(value)
: StringUTF16.indexOfNonWhitespace(value);
}
private int lastIndexOfNonWhitespace() {
return isLatin1() ? StringLatin1.lastIndexOfNonWhitespace(value)
: StringUTF16.lastIndexOfNonWhitespace(value);
}
/**
* Returns a string whose value is this string, with incidental
* {@linkplain Character#isWhitespace(int) white space} removed from
* the beginning and end of every line.
* <p>
* Incidental {@linkplain Character#isWhitespace(int) white space}
* is often present in a text block to align the content with the opening
* delimiter. For example, in the following code, dots represent incidental
* {@linkplain Character#isWhitespace(int) white space}:
* <blockquote><pre>
* String html = """
* ..............<html>
* .............. <body>
* .............. <p>Hello, world</p>
* .............. </body>
* ..............</html>
* ..............""";
* </pre></blockquote>
* This method treats the incidental
* {@linkplain Character#isWhitespace(int) white space} as indentation to be
* stripped, producing a string that preserves the relative indentation of
* the content. Using | to visualize the start of each line of the string:
* <blockquote><pre>
* |<html>
* | <body>
* | <p>Hello, world</p>
* | </body>
* |</html>
* </pre></blockquote>
* First, the individual lines of this string are extracted. A <i>line</i>
* is a sequence of zero or more characters followed by either a line
* terminator or the end of the string.
* If the string has at least one line terminator, the last line consists
* of the characters between the last terminator and the end of the string.
* Otherwise, if the string has no terminators, the last line is the start
* of the string to the end of the string, in other words, the entire
* string.
* A line does not include the line terminator.
* <p>
* Then, the <i>minimum indentation</i> (min) is determined as follows:
* <ul>
* <li><p>For each non-blank line (as defined by {@link String#isBlank()}),
* the leading {@linkplain Character#isWhitespace(int) white space}
* characters are counted.</p>
* </li>
* <li><p>The leading {@linkplain Character#isWhitespace(int) white space}
* characters on the last line are also counted even if
* {@linkplain String#isBlank() blank}.</p>
* </li>
* </ul>
* <p>The <i>min</i> value is the smallest of these counts.
* <p>
* For each {@linkplain String#isBlank() non-blank} line, <i>min</i> leading
* {@linkplain Character#isWhitespace(int) white space} characters are
* removed, and any trailing {@linkplain Character#isWhitespace(int) white
* space} characters are removed. {@linkplain String#isBlank() Blank} lines
* are replaced with the empty string.
*
* <p>
* Finally, the lines are joined into a new string, using the LF character
* {@code "\n"} (U+000A) to separate lines.
*
* @apiNote
* This method's primary purpose is to shift a block of lines as far as
* possible to the left, while preserving relative indentation. Lines
* that were indented the least will thus have no leading
* {@linkplain Character#isWhitespace(int) white space}.
* The result will have the same number of line terminators as this string.
* If this string ends with a line terminator then the result will end
* with a line terminator.
*
* @implSpec
* This method treats all {@linkplain Character#isWhitespace(int) white space}
* characters as having equal width. As long as the indentation on every
* line is consistently composed of the same character sequences, then the
* result will be as described above.
*
* @return string with incidental indentation removed and line
* terminators normalized
*
* @see String#lines()
* @see String#isBlank()
* @see String#indent(int)
* @see Character#isWhitespace(int)
*
* @since 15
*
*/
public String stripIndent() {
int length = length();
if (length == 0) {
return "";
}
char lastChar = charAt(length - 1);
boolean optOut = lastChar == '\n' || lastChar == '\r';
List<String> lines = lines().toList();
final int outdent = optOut ? 0 : outdent(lines);
return lines.stream()
.map(line -> {
int firstNonWhitespace = line.indexOfNonWhitespace();
int lastNonWhitespace = line.lastIndexOfNonWhitespace();
int incidentalWhitespace = Math.min(outdent, firstNonWhitespace);
return firstNonWhitespace > lastNonWhitespace
? "" : line.substring(incidentalWhitespace, lastNonWhitespace);
})
.collect(Collectors.joining("\n", "", optOut ? "\n" : ""));
}
private static int outdent(List<String> lines) {
// Note: outdent is guaranteed to be zero or positive number.
// If there isn't a non-blank line then the last must be blank
int outdent = Integer.MAX_VALUE;
for (String line : lines) {
int leadingWhitespace = line.indexOfNonWhitespace();
if (leadingWhitespace != line.length()) {
outdent = Integer.min(outdent, leadingWhitespace);
}
}
String lastLine = lines.get(lines.size() - 1);
if (lastLine.isBlank()) {
outdent = Integer.min(outdent, lastLine.length());
}
return outdent;
}
/**
* Returns a string whose value is this string, with escape sequences
* translated as if in a string literal.
* <p>
* Escape sequences are translated as follows;
* <table class="striped">
* <caption style="display:none">Translation</caption>
* <thead>
* <tr>
* <th scope="col">Escape</th>
* <th scope="col">Name</th>
* <th scope="col">Translation</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th scope="row">{@code \u005Cb}</th>
* <td>backspace</td>
* <td>{@code U+0008}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005Ct}</th>
* <td>horizontal tab</td>
* <td>{@code U+0009}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005Cn}</th>
* <td>line feed</td>
* <td>{@code U+000A}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005Cf}</th>
* <td>form feed</td>
* <td>{@code U+000C}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005Cr}</th>
* <td>carriage return</td>
* <td>{@code U+000D}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005Cs}</th>
* <td>space</td>
* <td>{@code U+0020}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005C"}</th>
* <td>double quote</td>
* <td>{@code U+0022}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005C'}</th>
* <td>single quote</td>
* <td>{@code U+0027}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005C\u005C}</th>
* <td>backslash</td>
* <td>{@code U+005C}</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005C0 - \u005C377}</th>
* <td>octal escape</td>
* <td>code point equivalents</td>
* </tr>
* <tr>
* <th scope="row">{@code \u005C<line-terminator>}</th>
* <td>continuation</td>
* <td>discard</td>
* </tr>
* </tbody>
* </table>
*
* @implNote
* This method does <em>not</em> translate Unicode escapes such as "{@code \u005cu2022}".
* Unicode escapes are translated by the Java compiler when reading input characters and
* are not part of the string literal specification.
*
* @throws IllegalArgumentException when an escape sequence is malformed.
*
* @return String with escape sequences translated.
*
* @jls 3.10.7 Escape Sequences
*
* @since 15
*/
public String translateEscapes() {
if (isEmpty()) {
return "";
}
char[] chars = toCharArray();
int length = chars.length;
int from = 0;
int to = 0;
while (from < length) {
char ch = chars[from++];
if (ch == '\\') {
ch = from < length ? chars[from++] : '\0';
switch (ch) {
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 's':
ch = ' ';
break;
case 't':
ch = '\t';
break;
case '\'':
case '\"':
case '\\':
// as is
break;
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
int limit = Integer.min(from + (ch <= '3' ? 2 : 1), length);
int code = ch - '0';
while (from < limit) {
ch = chars[from];
if (ch < '0' || '7' < ch) {
break;
}
from++;
code = (code << 3) | (ch - '0');
}
ch = (char)code;
break;
case '\n':
continue;
case '\r':
if (from < length && chars[from] == '\n') {
from++;
}
continue;
default: {
String msg = String.format(
"Invalid escape sequence: \\%c \\\\u%04X",
ch, (int)ch);
throw new IllegalArgumentException(msg);
}
}
}
chars[to++] = ch;
}
return new String(chars, 0, to);
}
/**
* This method allows the application of a function to {@code this}
* string. The function should expect a single String argument
* and produce an {@code R} result.
* <p>
* Any exception thrown by {@code f.apply()} will be propagated to the
* caller.
*
* @param f a function to apply
*
* @param <R> the type of the result
*
* @return the result of applying the function to this string
*
* @see java.util.function.Function
*
* @since 12
*/
public <R> R transform(Function<? super String, ? extends R> f) {
return f.apply(this);
}
/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}
/**
* Returns a stream of {@code int} zero-extending the {@code char} values
* from this sequence. Any char which maps to a {@linkplain
* Character##unicode surrogate code point} is passed through
* uninterpreted.
*
* @return an IntStream of char values from this sequence
* @since 9
*/
@Override
public IntStream chars() {
return StreamSupport.intStream(
isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
: new StringUTF16.CharsSpliterator(value, Spliterator.IMMUTABLE),
false);
}
/**
* Returns a stream of code point values from this sequence. Any surrogate
* pairs encountered in the sequence are combined as if by {@linkplain
* Character#toCodePoint Character.toCodePoint} and the result is passed
* to the stream. Any other code units, including ordinary BMP characters,
* unpaired surrogates, and undefined code units, are zero-extended to
* {@code int} values which are then passed to the stream.
*
* @return an IntStream of Unicode code points from this sequence
* @since 9
*/
@Override
public IntStream codePoints() {
return StreamSupport.intStream(
isLatin1() ? new StringLatin1.CharsSpliterator(value, Spliterator.IMMUTABLE)
: new StringUTF16.CodePointsSpliterator(value, Spliterator.IMMUTABLE),
false);
}
/**
* Converts this string to a new character array.
*
* @return a newly allocated character array whose length is the length
* of this string and whose contents are initialized to contain
* the character sequence represented by this string.
*/
public char[] toCharArray() {
return isLatin1() ? StringLatin1.toChars(value)
: StringUTF16.toChars(value);
}
/**
* Returns a formatted string using the specified format string and
* arguments.
*
* <p> The locale always used is the one returned by {@link
* java.util.Locale#getDefault(java.util.Locale.Category)
* Locale.getDefault(Locale.Category)} with
* {@link java.util.Locale.Category#FORMAT FORMAT} category specified.
*
* @param format
* A <a href="../util/Formatter.html#syntax">format string</a>
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* <cite>The Java Virtual Machine Specification</cite>.
* The behaviour on a
* {@code null} argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the <a
* href="../util/Formatter.html#detail">Details</a> section of the
* formatter class specification.
*
* @return A formatted string
*
* @see java.util.Formatter
* @since 1.5
*/
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}
/**
* Returns a formatted string using the specified locale, format string,
* and arguments.
*
* @param l
* The {@linkplain java.util.Locale locale} to apply during
* formatting. If {@code l} is {@code null} then no localization
* is applied.
*
* @param format
* A <a href="../util/Formatter.html#syntax">format string</a>
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* <cite>The Java Virtual Machine Specification</cite>.
* The behaviour on a
* {@code null} argument depends on the
* <a href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the <a
* href="../util/Formatter.html#detail">Details</a> section of the
* formatter class specification
*
* @return A formatted string
*
* @see java.util.Formatter
* @since 1.5
*/
public static String format(Locale l, String format, Object... args) {
return new Formatter(l).format(format, args).toString();
}
/**
* Formats using this string as the format string, and the supplied
* arguments.
*
* @implSpec This method is equivalent to {@code String.format(this, args)}.
*
* @param args
* Arguments referenced by the format specifiers in this string.
*
* @return A formatted string
*
* @see java.lang.String#format(String,Object...)
* @see java.util.Formatter
*
* @since 15
*
*/
public String formatted(Object... args) {
return new Formatter().format(this, args).toString();
}
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
/**
* Returns the string representation of the {@code char} array
* argument. The contents of the character array are copied; subsequent
* modification of the character array does not affect the returned
* string.
*
* <p> The contents of the string are unspecified if the character array
* is modified during string construction.
*
* @param data the character array.
* @return a {@code String} that contains the characters of the
* character array.
*/
public static String valueOf(char[] data) {
return new String(data);
}
/**
* Returns the string representation of a specific subarray of the
* {@code char} array argument.
* <p>
* The {@code offset} argument is the index of the first
* character of the subarray. The {@code count} argument
* specifies the length of the subarray. The contents of the subarray
* are copied; subsequent modification of the character array does not
* affect the returned string.
*
* <p> The contents of the string are unspecified if the character array
* is modified during string construction.
*
* @param data the character array.
* @param offset initial offset of the subarray.
* @param count length of the subarray.
* @return a {@code String} that contains the characters of the
* specified subarray of the character array.
* @throws IndexOutOfBoundsException if {@code offset} is
* negative, or {@code count} is negative, or
* {@code offset+count} is larger than
* {@code data.length}.
*/
public static String valueOf(char[] data, int offset, int count) {
return new String(data, offset, count);
}
/**
* Equivalent to {@link #valueOf(char[], int, int)}.
*
* @param data the character array.
* @param offset initial offset of the subarray.
* @param count length of the subarray.
* @return a {@code String} that contains the characters of the
* specified subarray of the character array.
* @throws IndexOutOfBoundsException if {@code offset} is
* negative, or {@code count} is negative, or
* {@code offset+count} is larger than
* {@code data.length}.
*/
public static String copyValueOf(char[] data, int offset, int count) {
return new String(data, offset, count);
}
/**
* Equivalent to {@link #valueOf(char[])}.
*
* @param data the character array.
* @return a {@code String} that contains the characters of the
* character array.
*/
public static String copyValueOf(char[] data) {
return new String(data);
}
/**
* Returns the string representation of the {@code boolean} argument.
*
* @param b a {@code boolean}.
* @return if the argument is {@code true}, a string equal to
* {@code "true"} is returned; otherwise, a string equal to
* {@code "false"} is returned.
*/
public static String valueOf(boolean b) {
return b ? "true" : "false";
}
/**
* Returns the string representation of the {@code char}
* argument.
*
* @param c a {@code char}.
* @return a string of length {@code 1} containing
* as its single character the argument {@code c}.
*/
public static String valueOf(char c) {
if (COMPACT_STRINGS && StringLatin1.canEncode(c)) {
return new String(StringLatin1.toBytes(c), LATIN1);
}
return new String(StringUTF16.toBytes(c), UTF16);
}
/**
* Returns the string representation of the {@code int} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Integer.toString} method of one argument.
*
* @param i an {@code int}.
* @return a string representation of the {@code int} argument.
* @see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
/**
* Returns the string representation of the {@code long} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Long.toString} method of one argument.
*
* @param l a {@code long}.
* @return a string representation of the {@code long} argument.
* @see java.lang.Long#toString(long)
*/
public static String valueOf(long l) {
return Long.toString(l);
}
/**
* Returns the string representation of the {@code float} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Float.toString} method of one argument.
*
* @param f a {@code float}.
* @return a string representation of the {@code float} argument.
* @see java.lang.Float#toString(float)
*/
public static String valueOf(float f) {
return Float.toString(f);
}
/**
* Returns the string representation of the {@code double} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Double.toString} method of one argument.
*
* @param d a {@code double}.
* @return a string representation of the {@code double} argument.
* @see java.lang.Double#toString(double)
*/
public static String valueOf(double d) {
return Double.toString(d);
}
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section {@jls 3.10.5} of the
* <cite>The Java Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
/**
* Returns a string whose value is the concatenation of this
* string repeated {@code count} times.
* <p>
* If this string is empty or count is zero then the empty
* string is returned.
*
* @param count number of times to repeat
*
* @return A string composed of this string repeated
* {@code count} times or the empty string if this
* string is empty or count is zero
*
* @throws IllegalArgumentException if the {@code count} is
* negative.
*
* @since 11
*/
public String repeat(int count) {
if (count < 0) {
throw new IllegalArgumentException("count is negative: " + count);
}
if (count == 1) {
return this;
}
final int len = value.length;
if (len == 0 || count == 0) {
return "";
}
if (Integer.MAX_VALUE / count < len) {
throw new OutOfMemoryError("Required length exceeds implementation limit");
}
if (len == 1) {
final byte[] single = new byte[count];
Arrays.fill(single, value[0]);
return new String(single, coder);
}
final int limit = len * count;
final byte[] multiple = new byte[limit];
System.arraycopy(value, 0, multiple, 0, len);
repeatCopyRest(multiple, 0, limit, len);
return new String(multiple, coder);
}
/**
* Used to perform copying after the initial insertion. Copying is optimized
* by using power of two duplication. First pass duplicates original copy,
* second pass then duplicates the original and the copy yielding four copies,
* third pass duplicates four copies yielding eight copies, and so on.
* Finally, the remainder is filled in with prior copies.
*
* @implNote The technique used here is significantly faster than hand-rolled
* loops or special casing small numbers due to the intensive optimization
* done by intrinsic {@code System.arraycopy}.
*
* @param buffer destination buffer
* @param offset offset in the destination buffer
* @param limit total replicated including what is already in the buffer
* @param copied number of bytes that have already in the buffer
*/
static void repeatCopyRest(byte[] buffer, int offset, int limit, int copied) {
// Initial copy is in the buffer.
for (; copied < limit - copied; copied <<= 1) {
// Power of two duplicate.
System.arraycopy(buffer, offset, buffer, offset + copied, copied);
}
// Duplicate remainder.
System.arraycopy(buffer, offset, buffer, offset + copied, limit - copied);
}
////////////////////////////////////////////////////////////////
/**
* Copy character bytes from this string into dst starting at dstBegin.
* This method doesn't perform any range checking.
*
* Invoker guarantees: dst is in UTF16 (inflate itself for asb), if two
* coders are different, and dst is big enough (range check)
*
* @param dstBegin the char index, not offset of byte[]
* @param coder the coder of dst[]
*/
void getBytes(byte[] dst, int dstBegin, byte coder) {
if (coder() == coder) {
System.arraycopy(value, 0, dst, dstBegin << coder, value.length);
} else { // this.coder == LATIN && coder == UTF16
StringLatin1.inflate(value, 0, dst, dstBegin, value.length);
}
}
/**
* Copy character bytes from this string into dst starting at dstBegin.
* This method doesn't perform any range checking.
*
* Invoker guarantees: dst is in UTF16 (inflate itself for asb), if two
* coders are different, and dst is big enough (range check)
*
* @param srcPos the char index, not offset of byte[]
* @param dstBegin the char index to start from
* @param coder the coder of dst[]
* @param length the amount of copied chars
*/
void getBytes(byte[] dst, int srcPos, int dstBegin, byte coder, int length) {
if (coder() == coder) {
System.arraycopy(value, srcPos << coder, dst, dstBegin << coder, length << coder);
} else { // this.coder == LATIN && coder == UTF16
StringLatin1.inflate(value, srcPos, dst, dstBegin, length);
}
}
/*
* Private constructor. Trailing Void argument is there for
* disambiguating it against other (public) constructors.
*
* Stores the char[] value into a byte[] that each byte represents
* the8 low-order bits of the corresponding character, if the char[]
* contains only latin1 character. Or a byte[] that stores all
* characters in their byte sequences defined by the {@code StringUTF16}.
*
* <p> The contents of the string are unspecified if the character array
* is modified during string construction.
*/
private String(char[] value, int off, int len, Void sig) {
if (len == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
if (COMPACT_STRINGS) {
byte[] val = StringUTF16.compress(value, off, len);
this.coder = StringUTF16.coderFromArrayLen(val, len);
this.value = val;
return;
}
this.coder = UTF16;
this.value = StringUTF16.toBytes(value, off, len);
}
/*
* Package private constructor. Trailing Void argument is there for
* disambiguating it against other (public) constructors.
*
* <p> The contents of the string are unspecified if the {@code StringBuilder}
* is modified during string construction.
*/
String(AbstractStringBuilder asb, Void sig) {
byte[] val = asb.getValue();
int length = asb.length();
if (asb.isLatin1()) {
this.coder = LATIN1;
this.value = Arrays.copyOfRange(val, 0, length);
} else {
// only try to compress val if some characters were deleted.
if (COMPACT_STRINGS && asb.maybeLatin1) {
this.value = StringUTF16.compress(val, 0, length);
this.coder = StringUTF16.coderFromArrayLen(this.value, length);
return;
}
this.coder = UTF16;
this.value = Arrays.copyOfRange(val, 0, length << 1);
}
}
/*
* Package private constructor which shares value array for speed.
*/
String(byte[] value, byte coder) {
this.value = value;
this.coder = coder;
}
byte coder() {
return COMPACT_STRINGS ? coder : UTF16;
}
byte[] value() {
return value;
}
boolean isLatin1() {
return COMPACT_STRINGS && coder == LATIN1;
}
@Native static final byte LATIN1 = 0;
@Native static final byte UTF16 = 1;
/*
* StringIndexOutOfBoundsException if {@code index} is
* negative or greater than or equal to {@code length}.
*/
static void checkIndex(int index, int length) {
Preconditions.checkIndex(index, length, Preconditions.SIOOBE_FORMATTER);
}
/*
* StringIndexOutOfBoundsException if {@code offset}
* is negative or greater than {@code length}.
*/
static void checkOffset(int offset, int length) {
Preconditions.checkFromToIndex(offset, length, length, Preconditions.SIOOBE_FORMATTER);
}
/*
* Check {@code offset}, {@code count} against {@code 0} and {@code length}
* bounds.
*
* @return {@code offset} if the sub-range within bounds of the range
* @throws StringIndexOutOfBoundsException
* If {@code offset} is negative, {@code count} is negative,
* or {@code offset} is greater than {@code length - count}
*/
static int checkBoundsOffCount(int offset, int count, int length) {
return Preconditions.checkFromIndexSize(offset, count, length, Preconditions.SIOOBE_FORMATTER);
}
/*
* Check {@code begin}, {@code end} against {@code 0} and {@code length}
* bounds.
*
* @throws StringIndexOutOfBoundsException
* If {@code begin} is negative, {@code begin} is greater than
* {@code end}, or {@code end} is greater than {@code length}.
*/
static void checkBoundsBeginEnd(int begin, int end, int length) {
Preconditions.checkFromToIndex(begin, end, length, Preconditions.SIOOBE_FORMATTER);
}
/**
* Returns the string representation of the {@code codePoint}
* argument.
*
* @param codePoint a {@code codePoint}.
* @return a string of length {@code 1} or {@code 2} containing
* as its single character the argument {@code codePoint}.
* @throws IllegalArgumentException if the specified
* {@code codePoint} is not a {@linkplain Character#isValidCodePoint
* valid Unicode code point}.
*/
static String valueOfCodePoint(int codePoint) {
if (COMPACT_STRINGS && StringLatin1.canEncode(codePoint)) {
return new String(StringLatin1.toBytes((char)codePoint), LATIN1);
} else if (Character.isBmpCodePoint(codePoint)) {
return new String(StringUTF16.toBytes((char)codePoint), UTF16);
} else if (Character.isSupplementaryCodePoint(codePoint)) {
return new String(StringUTF16.toBytesSupplementary(codePoint), UTF16);
}
throw new IllegalArgumentException(
format("Not a valid Unicode code point: 0x%X", codePoint));
}
/**
* Returns an {@link Optional} containing the nominal descriptor for this
* instance, which is the instance itself.
*
* @return an {@link Optional} describing the {@linkplain String} instance
* @since 12
*/
@Override
public Optional<String> describeConstable() {
return Optional.of(this);
}
/**
* Resolves this instance as a {@link ConstantDesc}, the result of which is
* the instance itself.
*
* @param lookup ignored
* @return the {@linkplain String} instance
* @since 12
*/
@Override
public String resolveConstantDesc(MethodHandles.Lookup lookup) {
return this;
}
}
| openjdk/jdk | src/java.base/share/classes/java/lang/String.java |
2,798 | /*
* Copyright (C) 2017-2023 Lightbend Inc. <https://www.lightbend.com>
*/
package akka.annotation;
import java.lang.annotation.*;
/**
* Marks APIs that are meant to evolve towards becoming stable APIs, but are not stable APIs yet.
*
* <p>Evolving interfaces MAY change from one patch release to another (i.e. 2.4.10 to 2.4.11)
* without up-front notice. A best-effort approach is taken to not cause more breakage than really
* necessary, and usual deprecation techniques are utilised while evolving these APIs, however there
* is NO strong guarantee regarding the source or binary compatibility of APIs marked using this
* annotation.
*
* <p>It MAY also change when promoting the API to stable, for example such changes may include
* removal of deprecated methods that were introduced during the evolution and final refactoring
* that were deferred because they would have introduced to much breaking changes during the
* evolution phase.
*
* <p>Promoting the API to stable MAY happen in a patch release.
*
* <p>It is encouraged to document in ScalaDoc how exactly this API is expected to evolve.
*/
@Documented
@Retention(RetentionPolicy.CLASS) // to be accessible by MiMa
@Target({
ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.TYPE,
ElementType.PACKAGE
})
public @interface ApiMayChange {
/** Reference to issue discussing the future evolvement of this API */
String issue() default "";
}
| akka/akka | akka-actor/src/main/java/akka/annotation/ApiMayChange.java |
2,799 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.json;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
/**
* The <b>Json</b> class is the entrypoint for the JSON processing features of the Selenium API.
* These features include:
*
* <ul>
* <li>Built-in JSON deserialization to primitives and collections from the standard types shown
* below.
* <li>Facilities to deserialize JSON to custom data types:
* <ul>
* <li>Classes that declare a {@code fromJson(T)} static method, where <b>T</b> is any of
* the standard types shown below.
* <li>Classes that declare a {@code fromJson(JsonInput)} static method.<br>
* <b>NOTE</b>: Objects deserialized via a {@code fromJson} static method can be
* immutable.
* <li>Classes that declare setter methods adhering to the <a
* href="https://docs.oracle.com/javase/tutorial/javabeans/writing/index.html">JavaBean</a>
* specification.<br>
* <b>NOTE</b>: Deserialized {@code JavaBean} objects are mutable, which may be
* undesirable.
* </ul>
* <li>Built-in JSON serialization from primitives and collections from the standard types shown
* below.
* <li>Facilities to serialize custom data types to JSON:
* <ul>
* <li>Classes that declare a {@code toJson()} method returning a primitive or collection
* from the standard types shown below.
* <li>Classes that declare getter methods adhering to the {@code JavaBean} specification.
* </ul>
* </ul>
*
* The standard types supported by built-in processing:
*
* <ul>
* <li><b>Numeric Types</b>:<br>
* {@link java.lang.Byte Byte}, {@link java.lang.Double Double}, {@link java.lang.Float
* Float}, {@link java.lang.Integer Integer}, {@link java.lang.Long Long}, {@link
* java.lang.Short Short}
* <li><b>Collection Types</b>:<br>
* {@link java.util.List List}, {@link java.util.Set Set}
* <li><b>Standard Java Types</b>:<br>
* {@link java.util.Map Map}, {@link java.lang.Boolean Boolean}, {@link java.lang.String
* String}, {@link java.lang.Enum Enum}, {@link java.net.URI URI}, {@link java.net.URL URL},
* {@link java.util.UUID UUID}, {@link java.time.Instant Instant}, {@link java.lang.Object
* Object}
* </ul>
*
* You can serialize objects for which no explicit coercer has been specified, and the <b>Json</b>
* API will use a generic process to provide best-effort JSON output. For the most predictable
* results, though, it's best to provide a {@code toJson()} method for the <b>Json</b> API to use
* for serialization. This is especially beneficial for objects that contain transient properties
* that should be omitted from the JSON output.
*
* <p>You can deserialize objects for which no explicit handling has been defined. Note that the
* data type of the result will be {@code Map<String,?>}, which means that you'll need to perform
* type checking and casting every time you extract an entry value from the result. For this reason,
* it's best to declare a type-specific {@code fromJson()} method in every type you need to
* deserialize.
*
* @see JsonTypeCoercer
* @see JsonInput
* @see JsonOutput
*/
public class Json {
/**
* The value of {@code Content-Type} headers for HTTP requests and responses with JSON entities
*/
public static final String JSON_UTF_8 = "application/json; charset=utf-8";
/** Specifier for {@code List<Map<String, Object>} input/output type */
public static final Type LIST_OF_MAPS_TYPE =
new TypeToken<List<Map<String, Object>>>() {}.getType();
/** Specifier for {@code Map<String, Object>} input/output type */
public static final Type MAP_TYPE = new TypeToken<Map<String, Object>>() {}.getType();
/** Specifier for {@code Object} input/output type */
public static final Type OBJECT_TYPE = new TypeToken<Object>() {}.getType();
private final JsonTypeCoercer fromJson = new JsonTypeCoercer();
/**
* Serialize the specified object to JSON string representation.<br>
* <b>NOTE</b>: This method limits traversal of nested objects to the default {@link
* JsonOutput#MAX_DEPTH maximum depth}.
*
* @param toConvert the object to be serialized
* @return JSON string representing the specified object
*/
public String toJson(Object toConvert) {
return toJson(toConvert, JsonOutput.MAX_DEPTH);
}
/**
* Serialize the specified object to JSON string representation.
*
* @param toConvert the object to be serialized
* @param maxDepth maximum depth of nested object traversal
* @return JSON string representing the specified object
* @throws JsonException if an I/O exception is encountered
*/
public String toJson(Object toConvert, int maxDepth) {
try (Writer writer = new StringWriter();
JsonOutput jsonOutput = newOutput(writer)) {
jsonOutput.write(toConvert, maxDepth);
return writer.toString();
} catch (IOException e) {
throw new JsonException(e);
}
}
/**
* Deserialize the specified JSON string into an object of the specified type.<br>
* <b>NOTE</b>: This method uses the {@link PropertySetting#BY_NAME BY_NAME} strategy to assign
* values to properties in the deserialized object.
*
* @param source serialized source as JSON string
* @param typeOfT data type for deserialization (class or {@link TypeToken})
* @return object of the specified type deserialized from [source]
* @param <T> result type (as specified by [typeOfT])
* @throws JsonException if an I/O exception is encountered
*/
public <T> T toType(String source, Type typeOfT) {
return toType(source, typeOfT, PropertySetting.BY_NAME);
}
/**
* Deserialize the specified JSON string into an object of the specified type.
*
* @param source serialized source as JSON string
* @param typeOfT data type for deserialization (class or {@link TypeToken})
* @param setter strategy used to assign values during deserialization
* @return object of the specified type deserialized from [source]
* @param <T> result type (as specified by [typeOfT])
* @throws JsonException if an I/O exception is encountered
*/
public <T> T toType(String source, Type typeOfT, PropertySetting setter) {
try (StringReader reader = new StringReader(source)) {
return toType(reader, typeOfT, setter);
} catch (JsonException e) {
throw new JsonException("Unable to parse: " + source, e);
}
}
/**
* Deserialize the JSON string supplied by the specified {@code Reader} into an object of the
* specified type.<br>
* <b>NOTE</b>: This method uses the {@link PropertySetting#BY_NAME BY_NAME} strategy to assign
* values to properties in the deserialized object.
*
* @param source {@link Reader} that supplies a serialized JSON string
* @param typeOfT data type for deserialization (class or {@link TypeToken})
* @return object of the specified type deserialized from [source]
* @param <T> result type (as specified by [typeOfT])
* @throws JsonException if an I/O exception is encountered
*/
public <T> T toType(Reader source, Type typeOfT) {
return toType(source, typeOfT, PropertySetting.BY_NAME);
}
/**
* Deserialize the JSON string supplied by the specified {@code Reader} into an object of the
* specified type.
*
* @param source {@link Reader} that supplies a serialized JSON string
* @param typeOfT data type for deserialization (class or {@link TypeToken})
* @param setter strategy used to assign values during deserialization
* @return object of the specified type deserialized from [source]
* @param <T> result type (as specified by [typeOfT])
* @throws JsonException if an I/O exception is encountered
*/
public <T> T toType(Reader source, Type typeOfT, PropertySetting setter) {
if (setter == null) {
throw new JsonException("Mechanism for setting properties must be set");
}
try (JsonInput json = newInput(source)) {
return fromJson.coerce(json, typeOfT, setter);
}
}
/**
* Create a new {@code JsonInput} object to traverse the JSON string supplied the specified {@code
* Reader}.<br>
* <b>NOTE</b>: The {@code JsonInput} object returned by this method uses the {@link
* PropertySetting#BY_NAME BY_NAME} strategy to assign values to properties objects it
* deserializes.
*
* @param from {@link Reader} that supplies a serialized JSON string
* @return {@link JsonInput} object to traverse the JSON string supplied by [from]
* @throws UncheckedIOException if an I/O exception occurs
*/
public JsonInput newInput(Reader from) throws UncheckedIOException {
return new JsonInput(from, fromJson, PropertySetting.BY_NAME);
}
/**
* Create a new {@code JsonOutput} object to produce a serialized JSON string in the specified
* {@code Appendable}.
*
* @param to {@link Appendable} that consumes a serialized JSON string
* @return {@link JsonOutput} object to product a JSON string in [to]
* @throws UncheckedIOException if an I/O exception occurs
*/
public JsonOutput newOutput(Appendable to) throws UncheckedIOException {
return new JsonOutput(to);
}
}
| SeleniumHQ/selenium | java/src/org/openqa/selenium/json/Json.java |
2,800 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-15 The Processing Foundation
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
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.
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 processing.opengl;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.PathIterator;
import java.io.IOException;
import java.net.URL;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import com.jogamp.common.util.VersionNumber;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GL2ES2;
import com.jogamp.opengl.GL2ES3;
import com.jogamp.opengl.GL2GL3;
import com.jogamp.opengl.GL3ES3;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLCapabilities;
import com.jogamp.opengl.GLCapabilitiesImmutable;
import com.jogamp.opengl.GLContext;
import com.jogamp.opengl.GLDrawable;
import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUtessellator;
import com.jogamp.opengl.glu.GLUtessellatorCallbackAdapter;
import processing.core.PApplet;
import processing.core.PGraphics;
import processing.core.PMatrix3D;
import processing.core.PSurface;
public class PJOGL extends PGL {
// OpenGL profile to use (2, 3 or 4)
public static int profile = 2;
// User-provided icons to override defaults
protected static String[] icons = null;
// The two windowing toolkits available to use in JOGL:
public static final int AWT = 0; // http://jogamp.org/wiki/index.php/Using_JOGL_in_AWT_SWT_and_Swing
public static final int NEWT = 1; // http://jogamp.org/jogl/doc/NEWT-Overview.html
// ........................................................
// Public members to access the underlying GL objects and context
/** Basic GL functionality, common to all profiles */
public GL gl;
/** GLU interface **/
public GLU glu;
/** The rendering context (holds rendering state info) */
public GLContext context;
// ........................................................
// Additional parameters
/** Time that the Processing's animation thread will wait for JOGL's rendering
* thread to be done with a single frame.
*/
protected static int DRAW_TIMEOUT_MILLIS = 500;
// ........................................................
// Protected JOGL-specific objects needed to access the GL profiles
/** The capabilities of the OpenGL rendering surface */
protected GLCapabilitiesImmutable capabilities;
/** The rendering surface */
protected GLDrawable drawable;
/** GLES2 functionality (shaders, etc) */
protected GL2ES2 gl2;
/** GL3 interface */
protected GL2GL3 gl3;
/** GL2 desktop functionality (blit framebuffer, map buffer range,
* multisampled renderbuffers) */
protected GL2 gl2x;
/** GL3ES3 interface */
protected GL3ES3 gl3es3;
/** Stores exceptions that ocurred during drawing */
protected Exception drawException;
// ........................................................
// Utility arrays to copy projection/modelview matrices to GL
protected float[] projMatrix;
protected float[] mvMatrix;
// ........................................................
// Static initialization for some parameters that need to be different for
// JOGL
static {
MIN_DIRECT_BUFFER_SIZE = 2;
INDEX_TYPE = GL.GL_UNSIGNED_SHORT;
}
///////////////////////////////////////////////////////////////
// Initialization, finalization
public PJOGL(PGraphicsOpenGL pg) {
super(pg);
glu = new GLU();
}
@Override
public Object getNative() {
return sketch.getSurface().getNative();
}
@Override
protected void setFrameRate(float fps) {}
@Override
protected void initSurface(int antialias) {}
@Override
protected void reinitSurface() {}
@Override
protected void registerListeners() {}
static public void setIcon(String... icons) {
PJOGL.icons = new String[icons.length];
PApplet.arrayCopy(icons, PJOGL.icons);
}
///////////////////////////////////////////////////////////////
// Public methods to get/set renderer's properties
public void setCaps(GLCapabilities caps) {
reqNumSamples = caps.getNumSamples();
capabilities = caps;
}
public GLCapabilitiesImmutable getCaps() {
return capabilities;
}
public void setFps(float fps) {
if (!setFps || targetFps != fps) {
if (60 < fps) {
// Disables v-sync
gl.setSwapInterval(0);
} else if (30 < fps) {
gl.setSwapInterval(1);
} else {
gl.setSwapInterval(2);
}
targetFps = currentFps = fps;
setFps = true;
}
}
@Override
protected int getDepthBits() {
return capabilities.getDepthBits();
}
@Override
protected int getStencilBits() {
return capabilities.getStencilBits();
}
@Override
protected float getPixelScale() {
PSurface surf = sketch.getSurface();
if (surf == null) {
return graphics.pixelDensity;
} else if (surf instanceof PSurfaceJOGL) {
return ((PSurfaceJOGL)surf).getPixelScale();
} else {
throw new RuntimeException("Renderer cannot find a JOGL surface");
}
}
@Override
protected void getGL(PGL pgl) {
PJOGL pjogl = (PJOGL)pgl;
this.drawable = pjogl.drawable;
this.context = pjogl.context;
this.glContext = pjogl.glContext;
setThread(pjogl.glThread);
this.gl = pjogl.gl;
this.gl2 = pjogl.gl2;
this.gl2x = pjogl.gl2x;
this.gl3 = pjogl.gl3;
this.gl3es3 = pjogl.gl3es3;
}
public void getGL(GLAutoDrawable glDrawable) {
context = glDrawable.getContext();
glContext = context.hashCode();
setThread(Thread.currentThread());
gl = context.getGL();
gl2 = gl.getGL2ES2();
try {
gl2x = gl.getGL2();
} catch (com.jogamp.opengl.GLException e) {
gl2x = null;
}
try {
gl3 = gl.getGL2GL3();
} catch (com.jogamp.opengl.GLException e) {
gl3 = null;
}
try {
gl3es3 = gl.getGL3ES3();
} catch (com.jogamp.opengl.GLException e) {
gl3es3 = null;
}
}
@Override
protected boolean canDraw() { return true; }
@Override
protected void requestFocus() {}
@Override
protected void requestDraw() {}
@Override
protected void swapBuffers() {
PSurfaceJOGL surf = (PSurfaceJOGL)sketch.getSurface();
surf.window.swapBuffers();
}
@Override
protected void initFBOLayer() {
if (0 < sketch.frameCount) {
if (isES()) initFBOLayerES();
else initFBOLayerGL();
}
}
private void initFBOLayerES() {
IntBuffer buf = allocateDirectIntBuffer(fboWidth * fboHeight);
if (hasReadBuffer()) readBuffer(BACK);
readPixelsImpl(0, 0, fboWidth, fboHeight, RGBA, UNSIGNED_BYTE, buf);
bindTexture(TEXTURE_2D, glColorTex.get(frontTex));
texSubImage2D(TEXTURE_2D, 0, 0, 0, fboWidth, fboHeight, RGBA, UNSIGNED_BYTE, buf);
bindTexture(TEXTURE_2D, glColorTex.get(backTex));
texSubImage2D(TEXTURE_2D, 0, 0, 0, fboWidth, fboHeight, RGBA, UNSIGNED_BYTE, buf);
bindTexture(TEXTURE_2D, 0);
bindFramebufferImpl(FRAMEBUFFER, 0);
}
private void initFBOLayerGL() {
// Copy the contents of the front and back screen buffers to the textures
// of the FBO, so they are properly initialized. Note that the front buffer
// of the default framebuffer (the screen) contains the previous frame:
// https://www.opengl.org/wiki/Default_Framebuffer
// so it is copied to the front texture of the FBO layer:
if (pclearColor || 0 < pgeomCount || !sketch.isLooping()) {
if (hasReadBuffer()) readBuffer(FRONT);
} else {
// ...except when the previous frame has not been cleared and nothing was
// rendered while looping. In this case the back buffer, which holds the
// initial state of the previous frame, still contains the most up-to-date
// screen state.
readBuffer(BACK);
}
bindFramebufferImpl(DRAW_FRAMEBUFFER, glColorFbo.get(0));
framebufferTexture2D(FRAMEBUFFER, COLOR_ATTACHMENT0,
TEXTURE_2D, glColorTex.get(frontTex), 0);
if (hasDrawBuffer()) drawBuffer(COLOR_ATTACHMENT0);
blitFramebuffer(0, 0, fboWidth, fboHeight,
0, 0, fboWidth, fboHeight,
COLOR_BUFFER_BIT, NEAREST);
readBuffer(BACK);
bindFramebufferImpl(DRAW_FRAMEBUFFER, glColorFbo.get(0));
framebufferTexture2D(FRAMEBUFFER, COLOR_ATTACHMENT0,
TEXTURE_2D, glColorTex.get(backTex), 0);
drawBuffer(COLOR_ATTACHMENT0);
blitFramebuffer(0, 0, fboWidth, fboHeight,
0, 0, fboWidth, fboHeight,
COLOR_BUFFER_BIT, NEAREST);
bindFramebufferImpl(FRAMEBUFFER, 0);
}
@Override
protected void beginGL() {
PMatrix3D proj = graphics.projection;
PMatrix3D mdl = graphics.modelview;
if (gl2x != null) {
if (projMatrix == null) {
projMatrix = new float[16];
}
gl2x.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
projMatrix[ 0] = proj.m00;
projMatrix[ 1] = proj.m10;
projMatrix[ 2] = proj.m20;
projMatrix[ 3] = proj.m30;
projMatrix[ 4] = proj.m01;
projMatrix[ 5] = proj.m11;
projMatrix[ 6] = proj.m21;
projMatrix[ 7] = proj.m31;
projMatrix[ 8] = proj.m02;
projMatrix[ 9] = proj.m12;
projMatrix[10] = proj.m22;
projMatrix[11] = proj.m32;
projMatrix[12] = proj.m03;
projMatrix[13] = proj.m13;
projMatrix[14] = proj.m23;
projMatrix[15] = proj.m33;
gl2x.glLoadMatrixf(projMatrix, 0);
if (mvMatrix == null) {
mvMatrix = new float[16];
}
gl2x.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
mvMatrix[ 0] = mdl.m00;
mvMatrix[ 1] = mdl.m10;
mvMatrix[ 2] = mdl.m20;
mvMatrix[ 3] = mdl.m30;
mvMatrix[ 4] = mdl.m01;
mvMatrix[ 5] = mdl.m11;
mvMatrix[ 6] = mdl.m21;
mvMatrix[ 7] = mdl.m31;
mvMatrix[ 8] = mdl.m02;
mvMatrix[ 9] = mdl.m12;
mvMatrix[10] = mdl.m22;
mvMatrix[11] = mdl.m32;
mvMatrix[12] = mdl.m03;
mvMatrix[13] = mdl.m13;
mvMatrix[14] = mdl.m23;
mvMatrix[15] = mdl.m33;
gl2x.glLoadMatrixf(mvMatrix, 0);
}
}
@Override
protected boolean hasFBOs() {
if (context.hasBasicFBOSupport()) return true;
else return super.hasFBOs();
}
@Override
protected boolean hasShaders() {
if (context.hasGLSL()) return true;
else return super.hasShaders();
}
public void init(GLAutoDrawable glDrawable) {
capabilities = glDrawable.getChosenGLCapabilities();
if (!hasFBOs()) {
throw new RuntimeException(MISSING_FBO_ERROR);
}
if (!hasShaders()) {
throw new RuntimeException(MISSING_GLSL_ERROR);
}
}
///////////////////////////////////////////////////////////
// Utility functions
@Override
protected void enableTexturing(int target) {
if (target == TEXTURE_2D) {
texturingTargets[0] = true;
} else if (target == TEXTURE_RECTANGLE) {
texturingTargets[1] = true;
}
}
@Override
protected void disableTexturing(int target) {
if (target == TEXTURE_2D) {
texturingTargets[0] = false;
} else if (target == TEXTURE_RECTANGLE) {
texturingTargets[1] = false;
}
}
/**
* Convenience method to get a legit FontMetrics object. Where possible,
* override this any renderer subclass so that you're not using what's
* returned by getDefaultToolkit() to get your metrics.
*/
@SuppressWarnings("deprecation")
private FontMetrics getFontMetrics(Font font) { // ignore
return Toolkit.getDefaultToolkit().getFontMetrics(font);
}
/**
* Convenience method to jump through some Java2D hoops and get an FRC.
*/
private FontRenderContext getFontRenderContext(Font font) { // ignore
return getFontMetrics(font).getFontRenderContext();
}
@Override
protected int getFontAscent(Object font) {
return getFontMetrics((Font) font).getAscent();
}
@Override
protected int getFontDescent(Object font) {
return getFontMetrics((Font) font).getDescent();
}
@Override
protected int getTextWidth(Object font, char[] buffer, int start, int stop) {
// maybe should use one of the newer/fancier functions for this?
int length = stop - start;
FontMetrics metrics = getFontMetrics((Font) font);
return metrics.charsWidth(buffer, start, length);
}
@Override
protected Object getDerivedFont(Object font, float size) {
return ((Font) font).deriveFont(size);
}
@Override
protected int getGLSLVersion() {
VersionNumber vn = context.getGLSLVersionNumber();
return vn.getMajor() * 100 + vn.getMinor();
}
@Override
protected String getGLSLVersionSuffix() {
VersionNumber vn = context.getGLSLVersionNumber();
if (context.isGLESProfile() && 1 < vn.getMajor()) {
return " es";
} else {
return "";
}
}
@Override
protected String[] loadVertexShader(String filename) {
return loadVertexShader(filename, getGLSLVersion(), getGLSLVersionSuffix());
}
@Override
protected String[] loadFragmentShader(String filename) {
return loadFragmentShader(filename, getGLSLVersion(), getGLSLVersionSuffix());
}
@Override
protected String[] loadVertexShader(URL url) {
return loadVertexShader(url, getGLSLVersion(), getGLSLVersionSuffix());
}
@Override
protected String[] loadFragmentShader(URL url) {
return loadFragmentShader(url, getGLSLVersion(), getGLSLVersionSuffix());
}
@Override
protected String[] loadFragmentShader(String filename, int version, String versionSuffix) {
String[] fragSrc0 = sketch.loadStrings(filename);
return preprocessFragmentSource(fragSrc0, version, versionSuffix);
}
@Override
protected String[] loadVertexShader(String filename, int version, String versionSuffix) {
String[] vertSrc0 = sketch.loadStrings(filename);
return preprocessVertexSource(vertSrc0, version, versionSuffix);
}
@Override
protected String[] loadFragmentShader(URL url, int version, String versionSuffix) {
try {
String[] fragSrc0 = PApplet.loadStrings(url.openStream());
return preprocessFragmentSource(fragSrc0, version, versionSuffix);
} catch (IOException e) {
PGraphics.showException("Cannot load fragment shader " + url.getFile());
}
return null;
}
@Override
protected String[] loadVertexShader(URL url, int version, String versionSuffix) {
try {
String[] vertSrc0 = PApplet.loadStrings(url.openStream());
return preprocessVertexSource(vertSrc0, version, versionSuffix);
} catch (IOException e) {
PGraphics.showException("Cannot load vertex shader " + url.getFile());
}
return null;
}
///////////////////////////////////////////////////////////
// Tessellator
@Override
protected Tessellator createTessellator(TessellatorCallback callback) {
return new Tessellator(callback);
}
protected static class Tessellator implements PGL.Tessellator {
protected GLUtessellator tess;
protected TessellatorCallback callback;
protected GLUCallback gluCallback;
public Tessellator(TessellatorCallback callback) {
this.callback = callback;
tess = GLU.gluNewTess();
gluCallback = new GLUCallback();
GLU.gluTessCallback(tess, GLU.GLU_TESS_BEGIN, gluCallback);
GLU.gluTessCallback(tess, GLU.GLU_TESS_END, gluCallback);
GLU.gluTessCallback(tess, GLU.GLU_TESS_VERTEX, gluCallback);
GLU.gluTessCallback(tess, GLU.GLU_TESS_COMBINE, gluCallback);
GLU.gluTessCallback(tess, GLU.GLU_TESS_ERROR, gluCallback);
}
@Override
public void setCallback(int flag) {
GLU.gluTessCallback(tess, flag, gluCallback);
}
@Override
public void setWindingRule(int rule) {
setProperty(GLU.GLU_TESS_WINDING_RULE, rule);
}
public void setProperty(int property, int value) {
GLU.gluTessProperty(tess, property, value);
}
@Override
public void beginPolygon() {
beginPolygon(null);
}
@Override
public void beginPolygon(Object data) {
GLU.gluTessBeginPolygon(tess, data);
}
@Override
public void endPolygon() {
GLU.gluTessEndPolygon(tess);
}
@Override
public void beginContour() {
GLU.gluTessBeginContour(tess);
}
@Override
public void endContour() {
GLU.gluTessEndContour(tess);
}
@Override
public void addVertex(double[] v) {
addVertex(v, 0, v);
}
@Override
public void addVertex(double[] v, int n, Object data) {
GLU.gluTessVertex(tess, v, n, data);
}
protected class GLUCallback extends GLUtessellatorCallbackAdapter {
@Override
public void begin(int type) {
callback.begin(type);
}
@Override
public void end() {
callback.end();
}
@Override
public void vertex(Object data) {
callback.vertex(data);
}
@Override
public void combine(double[] coords, Object[] data,
float[] weight, Object[] outData) {
callback.combine(coords, data, weight, outData);
}
@Override
public void error(int errnum) {
callback.error(errnum);
}
}
}
@Override
protected String tessError(int err) {
return glu.gluErrorString(err);
}
///////////////////////////////////////////////////////////
// Font outline
static {
SHAPE_TEXT_SUPPORTED = true;
SEG_MOVETO = PathIterator.SEG_MOVETO;
SEG_LINETO = PathIterator.SEG_LINETO;
SEG_QUADTO = PathIterator.SEG_QUADTO;
SEG_CUBICTO = PathIterator.SEG_CUBICTO;
SEG_CLOSE = PathIterator.SEG_CLOSE;
}
@Override
protected FontOutline createFontOutline(char ch, Object font) {
return new FontOutline(ch, (Font) font);
}
protected class FontOutline implements PGL.FontOutline {
PathIterator iter;
public FontOutline(char ch, Font font) {
char[] textArray = new char[] { ch };
FontRenderContext frc = getFontRenderContext(font);
GlyphVector gv = font.createGlyphVector(frc, textArray);
Shape shp = gv.getOutline();
iter = shp.getPathIterator(null);
}
public boolean isDone() {
return iter.isDone();
}
public int currentSegment(float[] coords) {
return iter.currentSegment(coords);
}
public void next() {
iter.next();
}
}
///////////////////////////////////////////////////////////
// Constants
static {
FALSE = GL.GL_FALSE;
TRUE = GL.GL_TRUE;
INT = GL2ES2.GL_INT;
BYTE = GL.GL_BYTE;
SHORT = GL.GL_SHORT;
FLOAT = GL.GL_FLOAT;
BOOL = GL2ES2.GL_BOOL;
UNSIGNED_INT = GL.GL_UNSIGNED_INT;
UNSIGNED_BYTE = GL.GL_UNSIGNED_BYTE;
UNSIGNED_SHORT = GL.GL_UNSIGNED_SHORT;
RGB = GL.GL_RGB;
RGBA = GL.GL_RGBA;
ALPHA = GL.GL_ALPHA;
LUMINANCE = GL.GL_LUMINANCE;
LUMINANCE_ALPHA = GL.GL_LUMINANCE_ALPHA;
UNSIGNED_SHORT_5_6_5 = GL.GL_UNSIGNED_SHORT_5_6_5;
UNSIGNED_SHORT_4_4_4_4 = GL.GL_UNSIGNED_SHORT_4_4_4_4;
UNSIGNED_SHORT_5_5_5_1 = GL.GL_UNSIGNED_SHORT_5_5_5_1;
RGBA4 = GL.GL_RGBA4;
RGB5_A1 = GL.GL_RGB5_A1;
RGB565 = GL.GL_RGB565;
RGB8 = GL.GL_RGB8;
RGBA8 = GL.GL_RGBA8;
ALPHA8 = GL.GL_ALPHA8;
READ_ONLY = GL2ES3.GL_READ_ONLY;
WRITE_ONLY = GL.GL_WRITE_ONLY;
READ_WRITE = GL2ES3.GL_READ_WRITE;
TESS_WINDING_NONZERO = GLU.GLU_TESS_WINDING_NONZERO;
TESS_WINDING_ODD = GLU.GLU_TESS_WINDING_ODD;
TESS_EDGE_FLAG = GLU.GLU_TESS_EDGE_FLAG;
GENERATE_MIPMAP_HINT = GL.GL_GENERATE_MIPMAP_HINT;
FASTEST = GL.GL_FASTEST;
NICEST = GL.GL_NICEST;
DONT_CARE = GL.GL_DONT_CARE;
VENDOR = GL.GL_VENDOR;
RENDERER = GL.GL_RENDERER;
VERSION = GL.GL_VERSION;
EXTENSIONS = GL.GL_EXTENSIONS;
SHADING_LANGUAGE_VERSION = GL2ES2.GL_SHADING_LANGUAGE_VERSION;
MAX_SAMPLES = GL.GL_MAX_SAMPLES;
SAMPLES = GL.GL_SAMPLES;
ALIASED_LINE_WIDTH_RANGE = GL.GL_ALIASED_LINE_WIDTH_RANGE;
ALIASED_POINT_SIZE_RANGE = GL.GL_ALIASED_POINT_SIZE_RANGE;
DEPTH_BITS = GL.GL_DEPTH_BITS;
STENCIL_BITS = GL.GL_STENCIL_BITS;
CCW = GL.GL_CCW;
CW = GL.GL_CW;
VIEWPORT = GL.GL_VIEWPORT;
ARRAY_BUFFER = GL.GL_ARRAY_BUFFER;
ELEMENT_ARRAY_BUFFER = GL.GL_ELEMENT_ARRAY_BUFFER;
PIXEL_PACK_BUFFER = GL2ES3.GL_PIXEL_PACK_BUFFER;
MAX_VERTEX_ATTRIBS = GL2ES2.GL_MAX_VERTEX_ATTRIBS;
STATIC_DRAW = GL.GL_STATIC_DRAW;
DYNAMIC_DRAW = GL.GL_DYNAMIC_DRAW;
STREAM_DRAW = GL2ES2.GL_STREAM_DRAW;
STREAM_READ = GL2ES3.GL_STREAM_READ;
BUFFER_SIZE = GL.GL_BUFFER_SIZE;
BUFFER_USAGE = GL.GL_BUFFER_USAGE;
POINTS = GL.GL_POINTS;
LINE_STRIP = GL.GL_LINE_STRIP;
LINE_LOOP = GL.GL_LINE_LOOP;
LINES = GL.GL_LINES;
TRIANGLE_FAN = GL.GL_TRIANGLE_FAN;
TRIANGLE_STRIP = GL.GL_TRIANGLE_STRIP;
TRIANGLES = GL.GL_TRIANGLES;
CULL_FACE = GL.GL_CULL_FACE;
FRONT = GL.GL_FRONT;
BACK = GL.GL_BACK;
FRONT_AND_BACK = GL.GL_FRONT_AND_BACK;
POLYGON_OFFSET_FILL = GL.GL_POLYGON_OFFSET_FILL;
UNPACK_ALIGNMENT = GL.GL_UNPACK_ALIGNMENT;
PACK_ALIGNMENT = GL.GL_PACK_ALIGNMENT;
TEXTURE_2D = GL.GL_TEXTURE_2D;
TEXTURE_RECTANGLE = GL2GL3.GL_TEXTURE_RECTANGLE;
TEXTURE_BINDING_2D = GL.GL_TEXTURE_BINDING_2D;
TEXTURE_BINDING_RECTANGLE = GL2GL3.GL_TEXTURE_BINDING_RECTANGLE;
MAX_TEXTURE_SIZE = GL.GL_MAX_TEXTURE_SIZE;
TEXTURE_MAX_ANISOTROPY = GL.GL_TEXTURE_MAX_ANISOTROPY_EXT;
MAX_TEXTURE_MAX_ANISOTROPY = GL.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT;
MAX_VERTEX_TEXTURE_IMAGE_UNITS = GL2ES2.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS;
MAX_TEXTURE_IMAGE_UNITS = GL2ES2.GL_MAX_TEXTURE_IMAGE_UNITS;
MAX_COMBINED_TEXTURE_IMAGE_UNITS = GL2ES2.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS;
NUM_COMPRESSED_TEXTURE_FORMATS = GL.GL_NUM_COMPRESSED_TEXTURE_FORMATS;
COMPRESSED_TEXTURE_FORMATS = GL.GL_COMPRESSED_TEXTURE_FORMATS;
NEAREST = GL.GL_NEAREST;
LINEAR = GL.GL_LINEAR;
LINEAR_MIPMAP_NEAREST = GL.GL_LINEAR_MIPMAP_NEAREST;
LINEAR_MIPMAP_LINEAR = GL.GL_LINEAR_MIPMAP_LINEAR;
CLAMP_TO_EDGE = GL.GL_CLAMP_TO_EDGE;
REPEAT = GL.GL_REPEAT;
TEXTURE0 = GL.GL_TEXTURE0;
TEXTURE1 = GL.GL_TEXTURE1;
TEXTURE2 = GL.GL_TEXTURE2;
TEXTURE3 = GL.GL_TEXTURE3;
TEXTURE_MIN_FILTER = GL.GL_TEXTURE_MIN_FILTER;
TEXTURE_MAG_FILTER = GL.GL_TEXTURE_MAG_FILTER;
TEXTURE_WRAP_S = GL.GL_TEXTURE_WRAP_S;
TEXTURE_WRAP_T = GL.GL_TEXTURE_WRAP_T;
TEXTURE_WRAP_R = GL2ES2.GL_TEXTURE_WRAP_R;
TEXTURE_CUBE_MAP = GL.GL_TEXTURE_CUBE_MAP;
TEXTURE_CUBE_MAP_POSITIVE_X = GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X;
TEXTURE_CUBE_MAP_POSITIVE_Y = GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
TEXTURE_CUBE_MAP_POSITIVE_Z = GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
TEXTURE_CUBE_MAP_NEGATIVE_X = GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
TEXTURE_CUBE_MAP_NEGATIVE_Y = GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
TEXTURE_CUBE_MAP_NEGATIVE_Z = GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
VERTEX_SHADER = GL2ES2.GL_VERTEX_SHADER;
FRAGMENT_SHADER = GL2ES2.GL_FRAGMENT_SHADER;
INFO_LOG_LENGTH = GL2ES2.GL_INFO_LOG_LENGTH;
SHADER_SOURCE_LENGTH = GL2ES2.GL_SHADER_SOURCE_LENGTH;
COMPILE_STATUS = GL2ES2.GL_COMPILE_STATUS;
LINK_STATUS = GL2ES2.GL_LINK_STATUS;
VALIDATE_STATUS = GL2ES2.GL_VALIDATE_STATUS;
SHADER_TYPE = GL2ES2.GL_SHADER_TYPE;
DELETE_STATUS = GL2ES2.GL_DELETE_STATUS;
FLOAT_VEC2 = GL2ES2.GL_FLOAT_VEC2;
FLOAT_VEC3 = GL2ES2.GL_FLOAT_VEC3;
FLOAT_VEC4 = GL2ES2.GL_FLOAT_VEC4;
FLOAT_MAT2 = GL2ES2.GL_FLOAT_MAT2;
FLOAT_MAT3 = GL2ES2.GL_FLOAT_MAT3;
FLOAT_MAT4 = GL2ES2.GL_FLOAT_MAT4;
INT_VEC2 = GL2ES2.GL_INT_VEC2;
INT_VEC3 = GL2ES2.GL_INT_VEC3;
INT_VEC4 = GL2ES2.GL_INT_VEC4;
BOOL_VEC2 = GL2ES2.GL_BOOL_VEC2;
BOOL_VEC3 = GL2ES2.GL_BOOL_VEC3;
BOOL_VEC4 = GL2ES2.GL_BOOL_VEC4;
SAMPLER_2D = GL2ES2.GL_SAMPLER_2D;
SAMPLER_CUBE = GL2ES2.GL_SAMPLER_CUBE;
LOW_FLOAT = GL2ES2.GL_LOW_FLOAT;
MEDIUM_FLOAT = GL2ES2.GL_MEDIUM_FLOAT;
HIGH_FLOAT = GL2ES2.GL_HIGH_FLOAT;
LOW_INT = GL2ES2.GL_LOW_INT;
MEDIUM_INT = GL2ES2.GL_MEDIUM_INT;
HIGH_INT = GL2ES2.GL_HIGH_INT;
CURRENT_VERTEX_ATTRIB = GL2ES2.GL_CURRENT_VERTEX_ATTRIB;
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = GL2ES2.GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING;
VERTEX_ATTRIB_ARRAY_ENABLED = GL2ES2.GL_VERTEX_ATTRIB_ARRAY_ENABLED;
VERTEX_ATTRIB_ARRAY_SIZE = GL2ES2.GL_VERTEX_ATTRIB_ARRAY_SIZE;
VERTEX_ATTRIB_ARRAY_STRIDE = GL2ES2.GL_VERTEX_ATTRIB_ARRAY_STRIDE;
VERTEX_ATTRIB_ARRAY_TYPE = GL2ES2.GL_VERTEX_ATTRIB_ARRAY_TYPE;
VERTEX_ATTRIB_ARRAY_NORMALIZED = GL2ES2.GL_VERTEX_ATTRIB_ARRAY_NORMALIZED;
VERTEX_ATTRIB_ARRAY_POINTER = GL2ES2.GL_VERTEX_ATTRIB_ARRAY_POINTER;
BLEND = GL.GL_BLEND;
ONE = GL.GL_ONE;
ZERO = GL.GL_ZERO;
SRC_ALPHA = GL.GL_SRC_ALPHA;
DST_ALPHA = GL.GL_DST_ALPHA;
ONE_MINUS_SRC_ALPHA = GL.GL_ONE_MINUS_SRC_ALPHA;
ONE_MINUS_DST_COLOR = GL.GL_ONE_MINUS_DST_COLOR;
ONE_MINUS_SRC_COLOR = GL.GL_ONE_MINUS_SRC_COLOR;
DST_COLOR = GL.GL_DST_COLOR;
SRC_COLOR = GL.GL_SRC_COLOR;
SAMPLE_ALPHA_TO_COVERAGE = GL.GL_SAMPLE_ALPHA_TO_COVERAGE;
SAMPLE_COVERAGE = GL.GL_SAMPLE_COVERAGE;
KEEP = GL.GL_KEEP;
REPLACE = GL.GL_REPLACE;
INCR = GL.GL_INCR;
DECR = GL.GL_DECR;
INVERT = GL.GL_INVERT;
INCR_WRAP = GL.GL_INCR_WRAP;
DECR_WRAP = GL.GL_DECR_WRAP;
NEVER = GL.GL_NEVER;
ALWAYS = GL.GL_ALWAYS;
EQUAL = GL.GL_EQUAL;
LESS = GL.GL_LESS;
LEQUAL = GL.GL_LEQUAL;
GREATER = GL.GL_GREATER;
GEQUAL = GL.GL_GEQUAL;
NOTEQUAL = GL.GL_NOTEQUAL;
FUNC_ADD = GL.GL_FUNC_ADD;
FUNC_MIN = GL2ES3.GL_MIN;
FUNC_MAX = GL2ES3.GL_MAX;
FUNC_REVERSE_SUBTRACT = GL.GL_FUNC_REVERSE_SUBTRACT;
FUNC_SUBTRACT = GL.GL_FUNC_SUBTRACT;
DITHER = GL.GL_DITHER;
CONSTANT_COLOR = GL2ES2.GL_CONSTANT_COLOR;
CONSTANT_ALPHA = GL2ES2.GL_CONSTANT_ALPHA;
ONE_MINUS_CONSTANT_COLOR = GL2ES2.GL_ONE_MINUS_CONSTANT_COLOR;
ONE_MINUS_CONSTANT_ALPHA = GL2ES2.GL_ONE_MINUS_CONSTANT_ALPHA;
SRC_ALPHA_SATURATE = GL.GL_SRC_ALPHA_SATURATE;
SCISSOR_TEST = GL.GL_SCISSOR_TEST;
STENCIL_TEST = GL.GL_STENCIL_TEST;
DEPTH_TEST = GL.GL_DEPTH_TEST;
DEPTH_WRITEMASK = GL.GL_DEPTH_WRITEMASK;
COLOR_BUFFER_BIT = GL.GL_COLOR_BUFFER_BIT;
DEPTH_BUFFER_BIT = GL.GL_DEPTH_BUFFER_BIT;
STENCIL_BUFFER_BIT = GL.GL_STENCIL_BUFFER_BIT;
FRAMEBUFFER = GL.GL_FRAMEBUFFER;
COLOR_ATTACHMENT0 = GL.GL_COLOR_ATTACHMENT0;
COLOR_ATTACHMENT1 = GL2ES2.GL_COLOR_ATTACHMENT1;
COLOR_ATTACHMENT2 = GL2ES2.GL_COLOR_ATTACHMENT2;
COLOR_ATTACHMENT3 = GL2ES2.GL_COLOR_ATTACHMENT3;
RENDERBUFFER = GL.GL_RENDERBUFFER;
DEPTH_ATTACHMENT = GL.GL_DEPTH_ATTACHMENT;
STENCIL_ATTACHMENT = GL.GL_STENCIL_ATTACHMENT;
READ_FRAMEBUFFER = GL.GL_READ_FRAMEBUFFER;
DRAW_FRAMEBUFFER = GL.GL_DRAW_FRAMEBUFFER;
RGBA8 = GL.GL_RGBA8;
DEPTH24_STENCIL8 = GL.GL_DEPTH24_STENCIL8;
DEPTH_COMPONENT = GL2ES2.GL_DEPTH_COMPONENT;
DEPTH_COMPONENT16 = GL.GL_DEPTH_COMPONENT16;
DEPTH_COMPONENT24 = GL.GL_DEPTH_COMPONENT24;
DEPTH_COMPONENT32 = GL.GL_DEPTH_COMPONENT32;
STENCIL_INDEX = GL2ES2.GL_STENCIL_INDEX;
STENCIL_INDEX1 = GL.GL_STENCIL_INDEX1;
STENCIL_INDEX4 = GL.GL_STENCIL_INDEX4;
STENCIL_INDEX8 = GL.GL_STENCIL_INDEX8;
DEPTH_STENCIL = GL.GL_DEPTH_STENCIL;
FRAMEBUFFER_COMPLETE = GL.GL_FRAMEBUFFER_COMPLETE;
FRAMEBUFFER_UNDEFINED = GL2ES3.GL_FRAMEBUFFER_UNDEFINED;
FRAMEBUFFER_INCOMPLETE_ATTACHMENT = GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = GL.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
FRAMEBUFFER_INCOMPLETE_DIMENSIONS = GL.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
FRAMEBUFFER_INCOMPLETE_FORMATS = GL.GL_FRAMEBUFFER_INCOMPLETE_FORMATS;
FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER = GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER;
FRAMEBUFFER_INCOMPLETE_READ_BUFFER = GL2GL3.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER;
FRAMEBUFFER_UNSUPPORTED = GL.GL_FRAMEBUFFER_UNSUPPORTED;
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = GL.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE;
FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS = GL3ES3.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS;
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = GL.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE;
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = GL.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME;
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = GL.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL;
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = GL.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE;
RENDERBUFFER_WIDTH = GL.GL_RENDERBUFFER_WIDTH;
RENDERBUFFER_HEIGHT = GL.GL_RENDERBUFFER_HEIGHT;
RENDERBUFFER_RED_SIZE = GL.GL_RENDERBUFFER_RED_SIZE;
RENDERBUFFER_GREEN_SIZE = GL.GL_RENDERBUFFER_GREEN_SIZE;
RENDERBUFFER_BLUE_SIZE = GL.GL_RENDERBUFFER_BLUE_SIZE;
RENDERBUFFER_ALPHA_SIZE = GL.GL_RENDERBUFFER_ALPHA_SIZE;
RENDERBUFFER_DEPTH_SIZE = GL.GL_RENDERBUFFER_DEPTH_SIZE;
RENDERBUFFER_STENCIL_SIZE = GL.GL_RENDERBUFFER_STENCIL_SIZE;
RENDERBUFFER_INTERNAL_FORMAT = GL.GL_RENDERBUFFER_INTERNAL_FORMAT;
MULTISAMPLE = GL.GL_MULTISAMPLE;
LINE_SMOOTH = GL.GL_LINE_SMOOTH;
POLYGON_SMOOTH = GL2GL3.GL_POLYGON_SMOOTH;
SYNC_GPU_COMMANDS_COMPLETE = GL3ES3.GL_SYNC_GPU_COMMANDS_COMPLETE;
ALREADY_SIGNALED = GL3ES3.GL_ALREADY_SIGNALED;
CONDITION_SATISFIED = GL3ES3.GL_CONDITION_SATISFIED;
}
///////////////////////////////////////////////////////////
// Special Functions
@Override
public void flush() {
gl.glFlush();
}
@Override
public void finish() {
gl.glFinish();
}
@Override
public void hint(int target, int hint) {
gl.glHint(target, hint);
}
///////////////////////////////////////////////////////////
// State and State Requests
@Override
public void enable(int value) {
if (-1 < value) {
gl.glEnable(value);
}
}
@Override
public void disable(int value) {
if (-1 < value) {
gl.glDisable(value);
}
}
@Override
public void getBooleanv(int value, IntBuffer data) {
if (-1 < value) {
if (byteBuffer.capacity() < data.capacity()) {
byteBuffer = allocateDirectByteBuffer(data.capacity());
}
gl.glGetBooleanv(value, byteBuffer);
for (int i = 0; i < data.capacity(); i++) {
data.put(i, byteBuffer.get(i));
}
} else {
fillIntBuffer(data, 0, data.capacity() - 1, 0);
}
}
@Override
public void getIntegerv(int value, IntBuffer data) {
if (-1 < value) {
gl.glGetIntegerv(value, data);
} else {
fillIntBuffer(data, 0, data.capacity() - 1, 0);
}
}
@Override
public void getFloatv(int value, FloatBuffer data) {
if (-1 < value) {
gl.glGetFloatv(value, data);
} else {
fillFloatBuffer(data, 0, data.capacity() - 1, 0);
}
}
@Override
public boolean isEnabled(int value) {
return gl.glIsEnabled(value);
}
@Override
public String getString(int name) {
return gl.glGetString(name);
}
///////////////////////////////////////////////////////////
// Error Handling
@Override
public int getError() {
return gl.glGetError();
}
@Override
public String errorString(int err) {
return glu.gluErrorString(err);
}
//////////////////////////////////////////////////////////////////////////////
// Buffer Objects
@Override
public void genBuffers(int n, IntBuffer buffers) {
gl.glGenBuffers(n, buffers);
}
@Override
public void deleteBuffers(int n, IntBuffer buffers) {
gl.glDeleteBuffers(n, buffers);
}
@Override
public void bindBuffer(int target, int buffer) {
gl.glBindBuffer(target, buffer);
}
@Override
public void bufferData(int target, int size, Buffer data, int usage) {
gl.glBufferData(target, size, data, usage);
}
@Override
public void bufferSubData(int target, int offset, int size, Buffer data) {
gl.glBufferSubData(target, offset, size, data);
}
@Override
public void isBuffer(int buffer) {
gl.glIsBuffer(buffer);
}
@Override
public void getBufferParameteriv(int target, int value, IntBuffer data) {
gl.glGetBufferParameteriv(target, value, data);
}
@Override
public ByteBuffer mapBuffer(int target, int access) {
return gl2.glMapBuffer(target, access);
}
@Override
public ByteBuffer mapBufferRange(int target, int offset, int length, int access) {
if (gl2x != null) {
return gl2x.glMapBufferRange(target, offset, length, access);
} else if (gl3 != null) {
return gl3.glMapBufferRange(target, offset, length, access);
} else {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "glMapBufferRange()"));
}
}
@Override
public void unmapBuffer(int target) {
gl2.glUnmapBuffer(target);
}
//////////////////////////////////////////////////////////////////////////////
// Synchronization
@Override
public long fenceSync(int condition, int flags) {
if (gl3es3 != null) {
return gl3es3.glFenceSync(condition, flags);
} else {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "fenceSync()"));
}
}
@Override
public void deleteSync(long sync) {
if (gl3es3 != null) {
gl3es3.glDeleteSync(sync);
} else {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "deleteSync()"));
}
}
@Override
public int clientWaitSync(long sync, int flags, long timeout) {
if (gl3es3 != null) {
return gl3es3.glClientWaitSync(sync, flags, timeout);
} else {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "clientWaitSync()"));
}
}
//////////////////////////////////////////////////////////////////////////////
// Viewport and Clipping
@Override
public void depthRangef(float n, float f) {
gl.glDepthRangef(n, f);
}
@Override
public void viewport(int x, int y, int w, int h) {
float scale = getPixelScale();
viewportImpl((int)scale * x, (int)(scale * y), (int)(scale * w), (int)(scale * h));
}
@Override
protected void viewportImpl(int x, int y, int w, int h) {
gl.glViewport(x, y, w, h);
}
//////////////////////////////////////////////////////////////////////////////
// Reading Pixels
@Override
protected void readPixelsImpl(int x, int y, int width, int height, int format, int type, Buffer buffer) {
gl.glReadPixels(x, y, width, height, format, type, buffer);
}
@Override
protected void readPixelsImpl(int x, int y, int width, int height, int format, int type, long offset) {
gl.glReadPixels(x, y, width, height, format, type, 0);
}
//////////////////////////////////////////////////////////////////////////////
// Vertices
@Override
public void vertexAttrib1f(int index, float value) {
gl2.glVertexAttrib1f(index, value);
}
@Override
public void vertexAttrib2f(int index, float value0, float value1) {
gl2.glVertexAttrib2f(index, value0, value1);
}
@Override
public void vertexAttrib3f(int index, float value0, float value1, float value2) {
gl2.glVertexAttrib3f(index, value0, value1, value2);
}
@Override
public void vertexAttrib4f(int index, float value0, float value1, float value2, float value3) {
gl2.glVertexAttrib4f(index, value0, value1, value2, value3);
}
@Override
public void vertexAttrib1fv(int index, FloatBuffer values) {
gl2.glVertexAttrib1fv(index, values);
}
@Override
public void vertexAttrib2fv(int index, FloatBuffer values) {
gl2.glVertexAttrib2fv(index, values);
}
@Override
public void vertexAttrib3fv(int index, FloatBuffer values) {
gl2.glVertexAttrib3fv(index, values);
}
@Override
public void vertexAttrib4fv(int index, FloatBuffer values) {
gl2.glVertexAttrib4fv(index, values);
}
@Override
public void vertexAttribPointer(int index, int size, int type, boolean normalized, int stride, int offset) {
gl2.glVertexAttribPointer(index, size, type, normalized, stride, offset);
}
@Override
public void enableVertexAttribArray(int index) {
gl2.glEnableVertexAttribArray(index);
}
@Override
public void disableVertexAttribArray(int index) {
gl2.glDisableVertexAttribArray(index);
}
@Override
public void drawArraysImpl(int mode, int first, int count) {
gl.glDrawArrays(mode, first, count);
}
@Override
public void drawElementsImpl(int mode, int count, int type, int offset) {
gl.glDrawElements(mode, count, type, offset);
}
//////////////////////////////////////////////////////////////////////////////
// Rasterization
@Override
public void lineWidth(float width) {
gl.glLineWidth(width);
}
@Override
public void frontFace(int dir) {
gl.glFrontFace(dir);
}
@Override
public void cullFace(int mode) {
gl.glCullFace(mode);
}
@Override
public void polygonOffset(float factor, float units) {
gl.glPolygonOffset(factor, units);
}
//////////////////////////////////////////////////////////////////////////////
// Pixel Rectangles
@Override
public void pixelStorei(int pname, int param) {
gl.glPixelStorei(pname, param);
}
///////////////////////////////////////////////////////////
// Texturing
@Override
public void texImage2D(int target, int level, int internalFormat, int width, int height, int border, int format, int type, Buffer data) {
gl.glTexImage2D(target, level, internalFormat, width, height, border, format, type, data);
}
@Override
public void copyTexImage2D(int target, int level, int internalFormat, int x, int y, int width, int height, int border) {
gl.glCopyTexImage2D(target, level, internalFormat, x, y, width, height, border);
}
@Override
public void texSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int type, Buffer data) {
gl.glTexSubImage2D(target, level, xOffset, yOffset, width, height, format, type, data);
}
@Override
public void copyTexSubImage2D(int target, int level, int xOffset, int yOffset, int x, int y, int width, int height) {
gl.glCopyTexSubImage2D(target, level, x, y, xOffset, yOffset, width, height);
}
@Override
public void compressedTexImage2D(int target, int level, int internalFormat, int width, int height, int border, int imageSize, Buffer data) {
gl.glCompressedTexImage2D(target, level, internalFormat, width, height, border, imageSize, data);
}
@Override
public void compressedTexSubImage2D(int target, int level, int xOffset, int yOffset, int width, int height, int format, int imageSize, Buffer data) {
gl.glCompressedTexSubImage2D(target, level, xOffset, yOffset, width, height, format, imageSize, data);
}
@Override
public void texParameteri(int target, int pname, int param) {
gl.glTexParameteri(target, pname, param);
}
@Override
public void texParameterf(int target, int pname, float param) {
gl.glTexParameterf(target, pname, param);
}
@Override
public void texParameteriv(int target, int pname, IntBuffer params) {
gl.glTexParameteriv(target, pname, params);
}
@Override
public void texParameterfv(int target, int pname, FloatBuffer params) {
gl.glTexParameterfv(target, pname, params);
}
@Override
public void generateMipmap(int target) {
gl.glGenerateMipmap(target);
}
@Override
public void genTextures(int n, IntBuffer textures) {
gl.glGenTextures(n, textures);
}
@Override
public void deleteTextures(int n, IntBuffer textures) {
gl.glDeleteTextures(n, textures);
}
@Override
public void getTexParameteriv(int target, int pname, IntBuffer params) {
gl.glGetTexParameteriv(target, pname, params);
}
@Override
public void getTexParameterfv(int target, int pname, FloatBuffer params) {
gl.glGetTexParameterfv(target, pname, params);
}
@Override
public boolean isTexture(int texture) {
return gl.glIsTexture(texture);
}
@Override
protected void activeTextureImpl(int texture) {
gl.glActiveTexture(texture);
}
@Override
protected void bindTextureImpl(int target, int texture) {
gl.glBindTexture(target, texture);
}
///////////////////////////////////////////////////////////
// Shaders and Programs
@Override
public int createShader(int type) {
return gl2.glCreateShader(type);
}
@Override
public void shaderSource(int shader, String source) {
gl2.glShaderSource(shader, 1, new String[] { source }, (int[]) null, 0);
}
@Override
public void compileShader(int shader) {
gl2.glCompileShader(shader);
}
@Override
public void releaseShaderCompiler() {
gl2.glReleaseShaderCompiler();
}
@Override
public void deleteShader(int shader) {
gl2.glDeleteShader(shader);
}
@Override
public void shaderBinary(int count, IntBuffer shaders, int binaryFormat, Buffer binary, int length) {
gl2.glShaderBinary(count, shaders, binaryFormat, binary, length);
}
@Override
public int createProgram() {
return gl2.glCreateProgram();
}
@Override
public void attachShader(int program, int shader) {
gl2.glAttachShader(program, shader);
}
@Override
public void detachShader(int program, int shader) {
gl2.glDetachShader(program, shader);
}
@Override
public void linkProgram(int program) {
gl2.glLinkProgram(program);
}
@Override
public void useProgram(int program) {
gl2.glUseProgram(program);
}
@Override
public void deleteProgram(int program) {
gl2.glDeleteProgram(program);
}
@Override
public String getActiveAttrib(int program, int index, IntBuffer size, IntBuffer type) {
int[] tmp = {0, 0, 0};
byte[] namebuf = new byte[1024];
gl2.glGetActiveAttrib(program, index, 1024, tmp, 0, tmp, 1, tmp, 2, namebuf, 0);
size.put(tmp[1]);
type.put(tmp[2]);
String name = new String(namebuf, 0, tmp[0]);
return name;
}
@Override
public int getAttribLocation(int program, String name) {
return gl2.glGetAttribLocation(program, name);
}
@Override
public void bindAttribLocation(int program, int index, String name) {
gl2.glBindAttribLocation(program, index, name);
}
@Override
public int getUniformLocation(int program, String name) {
return gl2.glGetUniformLocation(program, name);
}
@Override
public String getActiveUniform(int program, int index, IntBuffer size, IntBuffer type) {
int[] tmp= {0, 0, 0};
byte[] namebuf = new byte[1024];
gl2.glGetActiveUniform(program, index, 1024, tmp, 0, tmp, 1, tmp, 2, namebuf, 0);
size.put(tmp[1]);
type.put(tmp[2]);
String name = new String(namebuf, 0, tmp[0]);
return name;
}
@Override
public void uniform1i(int location, int value) {
gl2.glUniform1i(location, value);
}
@Override
public void uniform2i(int location, int value0, int value1) {
gl2.glUniform2i(location, value0, value1);
}
@Override
public void uniform3i(int location, int value0, int value1, int value2) {
gl2.glUniform3i(location, value0, value1, value2);
}
@Override
public void uniform4i(int location, int value0, int value1, int value2, int value3) {
gl2.glUniform4i(location, value0, value1, value2, value3);
}
@Override
public void uniform1f(int location, float value) {
gl2.glUniform1f(location, value);
}
@Override
public void uniform2f(int location, float value0, float value1) {
gl2.glUniform2f(location, value0, value1);
}
@Override
public void uniform3f(int location, float value0, float value1, float value2) {
gl2.glUniform3f(location, value0, value1, value2);
}
@Override
public void uniform4f(int location, float value0, float value1, float value2, float value3) {
gl2.glUniform4f(location, value0, value1, value2, value3);
}
@Override
public void uniform1iv(int location, int count, IntBuffer v) {
gl2.glUniform1iv(location, count, v);
}
@Override
public void uniform2iv(int location, int count, IntBuffer v) {
gl2.glUniform2iv(location, count, v);
}
@Override
public void uniform3iv(int location, int count, IntBuffer v) {
gl2.glUniform3iv(location, count, v);
}
@Override
public void uniform4iv(int location, int count, IntBuffer v) {
gl2.glUniform4iv(location, count, v);
}
@Override
public void uniform1fv(int location, int count, FloatBuffer v) {
gl2.glUniform1fv(location, count, v);
}
@Override
public void uniform2fv(int location, int count, FloatBuffer v) {
gl2.glUniform2fv(location, count, v);
}
@Override
public void uniform3fv(int location, int count, FloatBuffer v) {
gl2.glUniform3fv(location, count, v);
}
@Override
public void uniform4fv(int location, int count, FloatBuffer v) {
gl2.glUniform4fv(location, count, v);
}
@Override
public void uniformMatrix2fv(int location, int count, boolean transpose, FloatBuffer mat) {
gl2.glUniformMatrix2fv(location, count, transpose, mat);
}
@Override
public void uniformMatrix3fv(int location, int count, boolean transpose, FloatBuffer mat) {
gl2.glUniformMatrix3fv(location, count, transpose, mat);
}
@Override
public void uniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer mat) {
gl2.glUniformMatrix4fv(location, count, transpose, mat);
}
@Override
public void validateProgram(int program) {
gl2.glValidateProgram(program);
}
@Override
public boolean isShader(int shader) {
return gl2.glIsShader(shader);
}
@Override
public void getShaderiv(int shader, int pname, IntBuffer params) {
gl2.glGetShaderiv(shader, pname, params);
}
@Override
public void getAttachedShaders(int program, int maxCount, IntBuffer count, IntBuffer shaders) {
gl2.glGetAttachedShaders(program, maxCount, count, shaders);
}
@Override
public String getShaderInfoLog(int shader) {
int[] val = { 0 };
gl2.glGetShaderiv(shader, GL2ES2.GL_INFO_LOG_LENGTH, val, 0);
int length = val[0];
byte[] log = new byte[length];
gl2.glGetShaderInfoLog(shader, length, val, 0, log, 0);
return new String(log);
}
@Override
public String getShaderSource(int shader) {
int[] len = {0};
byte[] buf = new byte[1024];
gl2.glGetShaderSource(shader, 1024, len, 0, buf, 0);
return new String(buf, 0, len[0]);
}
@Override
public void getShaderPrecisionFormat(int shaderType, int precisionType, IntBuffer range, IntBuffer precision) {
gl2.glGetShaderPrecisionFormat(shaderType, precisionType, range, precision);
}
@Override
public void getVertexAttribfv(int index, int pname, FloatBuffer params) {
gl2.glGetVertexAttribfv(index, pname, params);
}
@Override
public void getVertexAttribiv(int index, int pname, IntBuffer params) {
gl2.glGetVertexAttribiv(index, pname, params);
}
@Override
public void getVertexAttribPointerv(int index, int pname, ByteBuffer data) {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "glGetVertexAttribPointerv()"));
}
@Override
public void getUniformfv(int program, int location, FloatBuffer params) {
gl2.glGetUniformfv(program, location, params);
}
@Override
public void getUniformiv(int program, int location, IntBuffer params) {
gl2.glGetUniformiv(program, location, params);
}
@Override
public boolean isProgram(int program) {
return gl2.glIsProgram(program);
}
@Override
public void getProgramiv(int program, int pname, IntBuffer params) {
gl2.glGetProgramiv(program, pname, params);
}
@Override
public String getProgramInfoLog(int program) {
int[] val = { 0 };
gl2.glGetProgramiv(program, GL2ES2.GL_INFO_LOG_LENGTH, val, 0);
int length = val[0];
if (0 < length) {
byte[] log = new byte[length];
gl2.glGetProgramInfoLog(program, length, val, 0, log, 0);
return new String(log);
} else {
return "Unknown error";
}
}
///////////////////////////////////////////////////////////
// Per-Fragment Operations
@Override
public void scissor(int x, int y, int w, int h) {
float scale = getPixelScale();
gl.glScissor((int)scale * x, (int)(scale * y), (int)(scale * w), (int)(scale * h));
// gl.glScissor(x, y, w, h);
}
@Override
public void sampleCoverage(float value, boolean invert) {
gl2.glSampleCoverage(value, invert);
}
@Override
public void stencilFunc(int func, int ref, int mask) {
gl2.glStencilFunc(func, ref, mask);
}
@Override
public void stencilFuncSeparate(int face, int func, int ref, int mask) {
gl2.glStencilFuncSeparate(face, func, ref, mask);
}
@Override
public void stencilOp(int sfail, int dpfail, int dppass) {
gl2.glStencilOp(sfail, dpfail, dppass);
}
@Override
public void stencilOpSeparate(int face, int sfail, int dpfail, int dppass) {
gl2.glStencilOpSeparate(face, sfail, dpfail, dppass);
}
@Override
public void depthFunc(int func) {
gl.glDepthFunc(func);
}
@Override
public void blendEquation(int mode) {
gl.glBlendEquation(mode);
}
@Override
public void blendEquationSeparate(int modeRGB, int modeAlpha) {
gl.glBlendEquationSeparate(modeRGB, modeAlpha);
}
@Override
public void blendFunc(int src, int dst) {
gl.glBlendFunc(src, dst);
}
@Override
public void blendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
gl.glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
@Override
public void blendColor(float red, float green, float blue, float alpha) {
gl2.glBlendColor(red, green, blue, alpha);
}
///////////////////////////////////////////////////////////
// Whole Framebuffer Operations
@Override
public void colorMask(boolean r, boolean g, boolean b, boolean a) {
gl.glColorMask(r, g, b, a);
}
@Override
public void depthMask(boolean mask) {
gl.glDepthMask(mask);
}
@Override
public void stencilMask(int mask) {
gl.glStencilMask(mask);
}
@Override
public void stencilMaskSeparate(int face, int mask) {
gl2.glStencilMaskSeparate(face, mask);
}
@Override
public void clearColor(float r, float g, float b, float a) {
gl.glClearColor(r, g, b, a);
}
@Override
public void clearDepth(float d) {
gl.glClearDepth(d);
}
@Override
public void clearStencil(int s) {
gl.glClearStencil(s);
}
@Override
public void clear(int buf) {
gl.glClear(buf);
}
///////////////////////////////////////////////////////////
// Framebuffers Objects
@Override
protected void bindFramebufferImpl(int target, int framebuffer) {
gl.glBindFramebuffer(target, framebuffer);
}
@Override
public void deleteFramebuffers(int n, IntBuffer framebuffers) {
gl.glDeleteFramebuffers(n, framebuffers);
}
@Override
public void genFramebuffers(int n, IntBuffer framebuffers) {
gl.glGenFramebuffers(n, framebuffers);
}
@Override
public void bindRenderbuffer(int target, int renderbuffer) {
gl.glBindRenderbuffer(target, renderbuffer);
}
@Override
public void deleteRenderbuffers(int n, IntBuffer renderbuffers) {
gl.glDeleteRenderbuffers(n, renderbuffers);
}
@Override
public void genRenderbuffers(int n, IntBuffer renderbuffers) {
gl.glGenRenderbuffers(n, renderbuffers);
}
@Override
public void renderbufferStorage(int target, int internalFormat, int width, int height) {
gl.glRenderbufferStorage(target, internalFormat, width, height);
}
@Override
public void framebufferRenderbuffer(int target, int attachment, int rendbuferfTarget, int renderbuffer) {
gl.glFramebufferRenderbuffer(target, attachment, rendbuferfTarget, renderbuffer);
}
@Override
public void framebufferTexture2D(int target, int attachment, int texTarget, int texture, int level) {
gl.glFramebufferTexture2D(target, attachment, texTarget, texture, level);
}
@Override
public int checkFramebufferStatus(int target) {
return gl.glCheckFramebufferStatus(target);
}
@Override
public boolean isFramebuffer(int framebuffer) {
return gl2.glIsFramebuffer(framebuffer);
}
@Override
public void getFramebufferAttachmentParameteriv(int target, int attachment, int pname, IntBuffer params) {
gl2.glGetFramebufferAttachmentParameteriv(target, attachment, pname, params);
}
@Override
public boolean isRenderbuffer(int renderbuffer) {
return gl2.glIsRenderbuffer(renderbuffer);
}
@Override
public void getRenderbufferParameteriv(int target, int pname, IntBuffer params) {
gl2.glGetRenderbufferParameteriv(target, pname, params);
}
@Override
public void blitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) {
if (gl2x != null) {
gl2x.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
} else if (gl3 != null) {
gl3.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
} else if (gl3es3 != null) {
gl3es3.glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
} else {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "glBlitFramebuffer()"));
}
}
@Override
public void renderbufferStorageMultisample(int target, int samples, int format, int width, int height) {
if (gl2x != null) {
gl2x.glRenderbufferStorageMultisample(target, samples, format, width, height);
} else if (gl3 != null) {
gl3.glRenderbufferStorageMultisample(target, samples, format, width, height);
} else if (gl3es3 != null) {
gl3es3.glRenderbufferStorageMultisample(target, samples, format, width, height);
} else {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "glRenderbufferStorageMultisample()"));
}
}
@Override
public void readBuffer(int buf) {
if (gl2x != null) {
gl2x.glReadBuffer(buf);
} else if (gl3 != null) {
gl3.glReadBuffer(buf);
} else if (gl3es3 != null) {
gl3es3.glReadBuffer(buf);
} else {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "glReadBuffer()"));
}
}
@Override
public void drawBuffer(int buf) {
if (gl2x != null) {
gl2x.glDrawBuffer(buf);
} else if (gl3 != null) {
gl3.glDrawBuffer(buf);
} else if (gl3es3 != null) {
IntBuffer intBuffer = IntBuffer.allocate(1);
intBuffer.put(buf);
intBuffer.rewind();
gl3es3.glDrawBuffers(1, intBuffer);
} else {
throw new RuntimeException(String.format(MISSING_GLFUNC_ERROR, "glDrawBuffer()"));
}
}
}
| processing/processing | core/src/processing/opengl/PJOGL.java |
2,823 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.dao;
/**
* Customer Schema SQL Class.
*/
public final class CustomerSchemaSql {
private CustomerSchemaSql() {
}
public static final String CREATE_SCHEMA_SQL =
"CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), "
+ "LNAME VARCHAR(100))";
public static final String DELETE_SCHEMA_SQL = "DROP TABLE CUSTOMERS";
}
| smedals/java-design-patterns | dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java |
2,830 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.dao;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
/**
* An in memory implementation of {@link CustomerDao}, which stores the customers in JVM memory and
* data is lost when the application exits.
* <br>
* This implementation is useful as temporary database or for testing.
*/
public class InMemoryCustomerDao implements CustomerDao {
private final Map<Integer, Customer> idToCustomer = new HashMap<>();
/**
* An eagerly evaluated stream of customers stored in memory.
*/
@Override
public Stream<Customer> getAll() {
return idToCustomer.values().stream();
}
@Override
public Optional<Customer> getById(final int id) {
return Optional.ofNullable(idToCustomer.get(id));
}
@Override
public boolean add(final Customer customer) {
if (getById(customer.getId()).isPresent()) {
return false;
}
idToCustomer.put(customer.getId(), customer);
return true;
}
@Override
public boolean update(final Customer customer) {
return idToCustomer.replace(customer.getId(), customer) != null;
}
@Override
public boolean delete(final Customer customer) {
return idToCustomer.remove(customer.getId()) != null;
}
}
| smedals/java-design-patterns | dao/src/main/java/com/iluwatar/dao/InMemoryCustomerDao.java |
2,842 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.bytecode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
* This class represent game objects which properties can be changed by instructions interpreted by
* virtual machine.
*/
@AllArgsConstructor
@Setter
@Getter
@Slf4j
public class Wizard {
private int health;
private int agility;
private int wisdom;
private int numberOfPlayedSounds;
private int numberOfSpawnedParticles;
public void playSound() {
LOGGER.info("Playing sound");
numberOfPlayedSounds++;
}
public void spawnParticles() {
LOGGER.info("Spawning particles");
numberOfSpawnedParticles++;
}
}
| smedals/java-design-patterns | bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java |
2,844 | // See README.md for information and build instructions.
import com.example.tutorial.protos.AddressBook;
import com.example.tutorial.protos.Person;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
class AddPerson {
// This function fills in a Person message based on user input.
static Person PromptForAddress(BufferedReader stdin,
PrintStream stdout) throws IOException {
Person.Builder person = Person.newBuilder();
stdout.print("Enter person ID: ");
person.setId(Integer.valueOf(stdin.readLine()));
stdout.print("Enter name: ");
person.setName(stdin.readLine());
stdout.print("Enter email address (blank for none): ");
String email = stdin.readLine();
if (email.length() > 0) {
person.setEmail(email);
}
while (true) {
stdout.print("Enter a phone number (or leave blank to finish): ");
String number = stdin.readLine();
if (number.length() == 0) {
break;
}
Person.PhoneNumber.Builder phoneNumber =
Person.PhoneNumber.newBuilder().setNumber(number);
stdout.print("Is this a mobile, home, or work phone? ");
String type = stdin.readLine();
if (type.equals("mobile")) {
phoneNumber.setType(Person.PhoneType.MOBILE);
} else if (type.equals("home")) {
phoneNumber.setType(Person.PhoneType.HOME);
} else if (type.equals("work")) {
phoneNumber.setType(Person.PhoneType.WORK);
} else {
stdout.println("Unknown phone type. Using default.");
}
person.addPhones(phoneNumber);
}
return person.build();
}
// Main function: Reads the entire address book from a file,
// adds one person based on user input, then writes it back out to the same
// file.
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: AddPerson ADDRESS_BOOK_FILE");
System.exit(-1);
}
AddressBook.Builder addressBook = AddressBook.newBuilder();
// Read the existing address book.
try {
FileInputStream input = new FileInputStream(args[0]);
try {
addressBook.mergeFrom(input);
} finally {
try { input.close(); } catch (Throwable ignore) {}
}
} catch (FileNotFoundException e) {
System.out.println(args[0] + ": File not found. Creating a new file.");
}
// Add an address.
addressBook.addPeople(
PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
System.out));
// Write the new address book back to disk.
FileOutputStream output = new FileOutputStream(args[0]);
try {
addressBook.build().writeTo(output);
} finally {
output.close();
}
}
}
| protocolbuffers/protobuf | examples/AddPerson.java |
2,853 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.servant;
/**
* King.
*/
public class King implements Royalty {
private boolean isDrunk;
private boolean isHungry = true;
private boolean isHappy;
private boolean complimentReceived;
@Override
public void getFed() {
isHungry = false;
}
@Override
public void getDrink() {
isDrunk = true;
}
public void receiveCompliments() {
complimentReceived = true;
}
@Override
public void changeMood() {
if (!isHungry && isDrunk) {
isHappy = true;
}
if (complimentReceived) {
isHappy = false;
}
}
@Override
public boolean getMood() {
return isHappy;
}
}
| smedals/java-design-patterns | servant/src/main/java/com/iluwatar/servant/King.java |
2,858 | /*
* 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.rest;
import org.elasticsearch.common.Strings;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.core.TimeValue;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import static org.elasticsearch.rest.RestRequest.PATH_RESTRICTED;
public class RestUtils {
/**
* Sets whether we decode a '+' in an url as a space or not.
*/
private static final boolean DECODE_PLUS_AS_SPACE = Booleans.parseBoolean(System.getProperty("es.rest.url_plus_as_space", "false"));
public static final UnaryOperator<String> REST_DECODER = RestUtils::decodeComponent;
public static void decodeQueryString(String s, int fromIndex, Map<String, String> params) {
if (fromIndex < 0) {
return;
}
if (fromIndex >= s.length()) {
return;
}
int queryStringLength = s.contains("#") ? s.indexOf('#') : s.length();
String name = null;
int pos = fromIndex; // Beginning of the unprocessed region
int i; // End of the unprocessed region
char c = 0; // Current character
for (i = fromIndex; i < queryStringLength; i++) {
c = s.charAt(i);
if (c == '=' && name == null) {
if (pos != i) {
name = decodeQueryStringParam(s.substring(pos, i));
}
pos = i + 1;
} else if (c == '&' || c == ';') {
if (name == null && pos != i) {
// We haven't seen an `=' so far but moved forward.
// Must be a param of the form '&a&' so add it with
// an empty value.
addParam(params, decodeQueryStringParam(s.substring(pos, i)), "");
} else if (name != null) {
addParam(params, name, decodeQueryStringParam(s.substring(pos, i)));
name = null;
}
pos = i + 1;
}
}
if (pos != i) { // Are there characters we haven't dealt with?
if (name == null) { // Yes and we haven't seen any `='.
addParam(params, decodeQueryStringParam(s.substring(pos, i)), "");
} else { // Yes and this must be the last value.
addParam(params, name, decodeQueryStringParam(s.substring(pos, i)));
}
} else if (name != null) { // Have we seen a name without value?
addParam(params, name, "");
}
}
private static String decodeQueryStringParam(final String s) {
return decodeComponent(s, StandardCharsets.UTF_8, true);
}
private static void addParam(Map<String, String> params, String name, String value) {
if (PATH_RESTRICTED.equalsIgnoreCase(name)) {
throw new IllegalArgumentException("parameter [" + PATH_RESTRICTED + "] is reserved and may not set");
}
params.put(name, value);
}
/**
* Decodes a bit of an URL encoded by a browser.
* <p>
* This is equivalent to calling {@link #decodeComponent(String, Charset, boolean)}
* with the UTF-8 charset (recommended to comply with RFC 3986, Section 2).
*
* @param s The string to decode (can be empty).
* @return The decoded string, or {@code s} if there's nothing to decode.
* If the string to decode is {@code null}, returns an empty string.
* @throws IllegalArgumentException if the string contains a malformed
* escape sequence.
*/
public static String decodeComponent(final String s) {
return decodeComponent(s, StandardCharsets.UTF_8, DECODE_PLUS_AS_SPACE);
}
/**
* Decodes a bit of an URL encoded by a browser.
* <p>
* The string is expected to be encoded as per RFC 3986, Section 2.
* This is the encoding used by JavaScript functions {@code encodeURI}
* and {@code encodeURIComponent}, but not {@code escape}. For example
* in this encoding, é (in Unicode {@code U+00E9} or in UTF-8
* {@code 0xC3 0xA9}) is encoded as {@code %C3%A9} or {@code %c3%a9}.
* <p>
* This is essentially equivalent to calling
* <code>{@link java.net.URLDecoder URLDecoder}.{@link
* java.net.URLDecoder#decode(String, String)}</code>
* except that it's over 2x faster and generates less garbage for the GC.
* Actually this function doesn't allocate any memory if there's nothing
* to decode, the argument itself is returned.
*
* @param s The string to decode (can be empty).
* @param charset The charset to use to decode the string (should really
* be {@link StandardCharsets#UTF_8}.
* @param plusAsSpace Whether to decode a {@code '+'} to a single space {@code ' '}
* @return The decoded string, or {@code s} if there's nothing to decode.
* If the string to decode is {@code null}, returns an empty string.
* @throws IllegalArgumentException if the string contains a malformed
* escape sequence.
*/
private static String decodeComponent(final String s, final Charset charset, boolean plusAsSpace) {
if (s == null) {
return "";
}
final int size = s.length();
if (decodingNeeded(s, size, plusAsSpace) == false) {
return s;
}
final byte[] buf = new byte[size];
int pos = decode(s, size, buf, plusAsSpace);
return new String(buf, 0, pos, charset);
}
private static boolean decodingNeeded(String s, int size, boolean plusAsSpace) {
boolean decodingNeeded = false;
for (int i = 0; i < size; i++) {
final char c = s.charAt(i);
if (c == '%') {
i++; // We can skip at least one char, e.g. `%%'.
decodingNeeded = true;
} else if (plusAsSpace && c == '+') {
decodingNeeded = true;
}
}
return decodingNeeded;
}
@SuppressWarnings("fallthrough")
private static int decode(String s, int size, byte[] buf, boolean plusAsSpace) {
int pos = 0; // position in `buf'.
for (int i = 0; i < size; i++) {
char c = s.charAt(i);
switch (c) {
case '+':
buf[pos++] = (byte) (plusAsSpace ? ' ' : '+'); // "+" -> " "
break;
case '%':
if (i == size - 1) {
throw new IllegalArgumentException("unterminated escape sequence at end of string: " + s);
}
c = s.charAt(++i);
if (c == '%') {
buf[pos++] = '%'; // "%%" -> "%"
break;
} else if (i == size - 1) {
throw new IllegalArgumentException("partial escape sequence at end of string: " + s);
}
c = decodeHexNibble(c);
final char c2 = decodeHexNibble(s.charAt(++i));
if (c == Character.MAX_VALUE || c2 == Character.MAX_VALUE) {
throw new IllegalArgumentException(
"invalid escape sequence `%" + s.charAt(i - 1) + s.charAt(i) + "' at index " + (i - 2) + " of: " + s
);
}
c = (char) (c * 16 + c2);
// Fall through.
default:
buf[pos++] = (byte) c;
break;
}
}
return pos;
}
/**
* Helper to decode half of a hexadecimal number from a string.
*
* @param c The ASCII character of the hexadecimal number to decode.
* Must be in the range {@code [0-9a-fA-F]}.
* @return The hexadecimal value represented in the ASCII character
* given, or {@link Character#MAX_VALUE} if the character is invalid.
*/
private static char decodeHexNibble(final char c) {
if ('0' <= c && c <= '9') {
return (char) (c - '0');
} else if ('a' <= c && c <= 'f') {
return (char) (c - 'a' + 10);
} else if ('A' <= c && c <= 'F') {
return (char) (c - 'A' + 10);
} else {
return Character.MAX_VALUE;
}
}
/**
* Determine if CORS setting is a regex
*
* @return a corresponding {@link Pattern} if so and o.w. null.
*/
public static Pattern checkCorsSettingForRegex(String corsSetting) {
if (corsSetting == null) {
return null;
}
int len = corsSetting.length();
boolean isRegex = len > 2 && corsSetting.startsWith("/") && corsSetting.endsWith("/");
if (isRegex) {
return Pattern.compile(corsSetting.substring(1, corsSetting.length() - 1));
}
return null;
}
/**
* Return the CORS setting as an array of origins.
*
* @param corsSetting the CORS allow origin setting as configured by the user;
* should never pass null, but we check for it anyway.
* @return an array of origins if set, otherwise {@code null}.
*/
public static String[] corsSettingAsArray(String corsSetting) {
if (Strings.isNullOrEmpty(corsSetting)) {
return new String[0];
}
return Arrays.stream(corsSetting.split(",")).map(String::trim).toArray(String[]::new);
}
/**
* Extract the trace id from the specified traceparent string.
* @see <a href="https://www.w3.org/TR/trace-context/#traceparent-header">W3 traceparent spec</a>
*
* @param traceparent The value from the {@code traceparent} HTTP header
* @return The trace id from the traceparent string, or {@code Optional.empty()} if it is not present.
*/
public static Optional<String> extractTraceId(String traceparent) {
return traceparent != null && traceparent.length() >= 55 ? Optional.of(traceparent.substring(3, 35)) : Optional.empty();
}
/**
* The name of the common {@code ?master_timeout} query parameter.
*/
public static final String REST_MASTER_TIMEOUT_PARAM = "master_timeout";
/**
* The default value for the common {@code ?master_timeout} query parameter.
*/
public static final TimeValue REST_MASTER_TIMEOUT_DEFAULT = TimeValue.timeValueSeconds(30);
/**
* Extract the {@code ?master_timeout} parameter from the request, imposing the common default of {@code 30s} in case the parameter is
* missing.
*
* @param restRequest The request from which to extract the {@code ?master_timeout} parameter
* @return the timeout from the request, with a default of {@link #REST_MASTER_TIMEOUT_DEFAULT} ({@code 30s}) if the request does not
* specify the parameter
*/
public static TimeValue getMasterNodeTimeout(RestRequest restRequest) {
assert restRequest != null;
return restRequest.paramAsTime(REST_MASTER_TIMEOUT_PARAM, REST_MASTER_TIMEOUT_DEFAULT);
}
}
| gitpod-io/elasticsearch | server/src/main/java/org/elasticsearch/rest/RestUtils.java |
2,866 | package com.genymobile.scrcpy;
import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Scanner;
public final class IO {
private IO() {
// not instantiable
}
public static void writeFully(FileDescriptor fd, ByteBuffer from) throws IOException {
// ByteBuffer position is not updated as expected by Os.write() on old Android versions, so
// count the remaining bytes manually.
// See <https://github.com/Genymobile/scrcpy/issues/291>.
int remaining = from.remaining();
while (remaining > 0) {
try {
int w = Os.write(fd, from);
if (BuildConfig.DEBUG && w < 0) {
// w should not be negative, since an exception is thrown on error
throw new AssertionError("Os.write() returned a negative value (" + w + ")");
}
remaining -= w;
} catch (ErrnoException e) {
if (e.errno != OsConstants.EINTR) {
throw new IOException(e);
}
}
}
}
public static void writeFully(FileDescriptor fd, byte[] buffer, int offset, int len) throws IOException {
writeFully(fd, ByteBuffer.wrap(buffer, offset, len));
}
public static String toString(InputStream inputStream) {
StringBuilder builder = new StringBuilder();
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine()).append('\n');
}
return builder.toString();
}
public static boolean isBrokenPipe(IOException e) {
Throwable cause = e.getCause();
return cause instanceof ErrnoException && ((ErrnoException) cause).errno == OsConstants.EPIPE;
}
}
| Genymobile/scrcpy | server/src/main/java/com/genymobile/scrcpy/IO.java |
2,871 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
// Test that Kokoro is using the expected version of Java.
import static com.google.common.truth.Truth.assertWithMessage;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class JavaVersionTest {
@Test
public void testJavaVersion() throws Exception {
String exp = System.getenv("KOKORO_JAVA_VERSION");
if(exp == null || exp.isEmpty()) {
System.err.println("No kokoro java version found, skipping check");
return;
}
// Java 8's version is read as "1.8"
if (exp.equals("8")) exp = "1.8";
String version = System.getProperty("java.version");
assertWithMessage("Expected Java " + exp + " but found Java " + version)
.that(version.startsWith(exp))
.isTrue();
}
}
| protocolbuffers/protobuf | java/internal/JavaVersionTest.java |
2,876 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.retry;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
/**
* Finds a customer, returning its ID from our records.
*
* <p>This is an imaginary operation that, for some imagined input, returns the ID for a customer.
* However, this is a "flaky" operation that is supposed to fail intermittently, but for the
* purposes of this example it fails in a programmed way depending on the constructor parameters.
*
* @author George Aristy ([email protected])
*/
public record FindCustomer(String customerId, Deque<BusinessException> errors) implements BusinessOperation<String> {
public FindCustomer(String customerId, BusinessException... errors) {
this(customerId, new ArrayDeque<>(List.of(errors)));
}
@Override
public String perform() throws BusinessException {
if (!this.errors.isEmpty()) {
throw this.errors.pop();
}
return this.customerId;
}
}
| ati-nordnet/java-design-patterns | retry/src/main/java/com/iluwatar/retry/FindCustomer.java |
2,880 | // Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
// For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
// the contiguous subarray [4,-1,2,1] has the largest sum = 6.
public class Solution {
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = dp[0];
for(int i = 1; i < nums.length; i++) {
dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(dp[i], max);
}
return max;
}
} | sungjunyoung/interviews | Company/LinkedIn/maximumSubarray.java |
2,882 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.promise;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A Promise represents a proxy for a value not necessarily known when the promise is created. It
* allows you to associate dependent promises to an asynchronous action's eventual success value or
* failure reason. This lets asynchronous methods return values like synchronous methods: instead of
* the final value, the asynchronous method returns a promise of having a value at some point in the
* future.
*
* @param <T> type of result.
*/
public class Promise<T> extends PromiseSupport<T> {
private Runnable fulfillmentAction;
private Consumer<? super Throwable> exceptionHandler;
/**
* Creates a promise that will be fulfilled in future.
*/
public Promise() {
// Empty constructor
}
/**
* Fulfills the promise with the provided value.
*
* @param value the fulfilled value that can be accessed using {@link #get()}.
*/
@Override
public void fulfill(T value) {
super.fulfill(value);
postFulfillment();
}
/**
* Fulfills the promise with exception due to error in execution.
*
* @param exception the exception will be wrapped in {@link ExecutionException} when accessing the
* value using {@link #get()}.
*/
@Override
public void fulfillExceptionally(Exception exception) {
super.fulfillExceptionally(exception);
handleException(exception);
postFulfillment();
}
private void handleException(Exception exception) {
if (exceptionHandler == null) {
return;
}
exceptionHandler.accept(exception);
}
private void postFulfillment() {
if (fulfillmentAction == null) {
return;
}
fulfillmentAction.run();
}
/**
* Executes the task using the executor in other thread and fulfills the promise returned once the
* task completes either successfully or with an exception.
*
* @param task the task that will provide the value to fulfill the promise.
* @param executor the executor in which the task should be run.
* @return a promise that represents the result of running the task provided.
*/
public Promise<T> fulfillInAsync(final Callable<T> task, Executor executor) {
executor.execute(() -> {
try {
fulfill(task.call());
} catch (Exception ex) {
fulfillExceptionally(ex);
}
});
return this;
}
/**
* Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result
* of this promise as argument to the action provided.
*
* @param action action to be executed.
* @return a new promise.
*/
public Promise<Void> thenAccept(Consumer<? super T> action) {
var dest = new Promise<Void>();
fulfillmentAction = new ConsumeAction(this, dest, action);
return dest;
}
/**
* Set the exception handler on this promise.
*
* @param exceptionHandler a consumer that will handle the exception occurred while fulfilling the
* promise.
* @return this
*/
public Promise<T> onError(Consumer<? super Throwable> exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
/**
* Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result
* of this promise as argument to the function provided.
*
* @param func function to be executed.
* @return a new promise.
*/
public <V> Promise<V> thenApply(Function<? super T, V> func) {
Promise<V> dest = new Promise<>();
fulfillmentAction = new TransformAction<>(this, dest, func);
return dest;
}
/**
* Accesses the value from source promise and calls the consumer, then fulfills the destination
* promise.
*/
private class ConsumeAction implements Runnable {
private final Promise<T> src;
private final Promise<Void> dest;
private final Consumer<? super T> action;
private ConsumeAction(Promise<T> src, Promise<Void> dest, Consumer<? super T> action) {
this.src = src;
this.dest = dest;
this.action = action;
}
@Override
public void run() {
try {
action.accept(src.get());
dest.fulfill(null);
} catch (Throwable throwable) {
dest.fulfillExceptionally((Exception) throwable.getCause());
}
}
}
/**
* Accesses the value from source promise, then fulfills the destination promise using the
* transformed value. The source value is transformed using the transformation function.
*/
private class TransformAction<V> implements Runnable {
private final Promise<T> src;
private final Promise<V> dest;
private final Function<? super T, V> func;
private TransformAction(Promise<T> src, Promise<V> dest, Function<? super T, V> func) {
this.src = src;
this.dest = dest;
this.func = func;
}
@Override
public void run() {
try {
dest.fulfill(func.apply(src.get()));
} catch (Throwable throwable) {
dest.fulfillExceptionally((Exception) throwable.getCause());
}
}
}
} | smedals/java-design-patterns | promise/src/main/java/com/iluwatar/promise/Promise.java |
2,884 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.GL31;
import com.badlogic.gdx.graphics.GL32;
/** Environment class holding references to the {@link Application}, {@link Graphics}, {@link Audio}, {@link Files} and
* {@link Input} instances. The references are held in public static fields which allows static access to all sub systems. Do not
* use Graphics in a thread that is not the rendering thread.
* <p>
* This is normally a design faux pas but in this case is better than the alternatives.
* @author mzechner */
public class Gdx {
public static Application app;
public static Graphics graphics;
public static Audio audio;
public static Input input;
public static Files files;
public static Net net;
public static GL20 gl;
public static GL20 gl20;
public static GL30 gl30;
public static GL31 gl31;
public static GL32 gl32;
}
| tommyettinger/libgdx | gdx/src/com/badlogic/gdx/Gdx.java |
2,895 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.caching.database;
import com.iluwatar.caching.UserAccount;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of DatabaseManager.
* implements base methods to work with hashMap as database.
*/
public class VirtualDb implements DbManager {
/**
* Virtual DataBase.
*/
private Map<String, UserAccount> db;
/**
* Creates new HashMap.
*/
@Override
public void connect() {
db = new HashMap<>();
}
@Override
public void disconnect() {
db = null;
}
/**
* Read from Db.
*
* @param userId {@link String}
* @return {@link UserAccount}
*/
@Override
public UserAccount readFromDb(final String userId) {
if (db.containsKey(userId)) {
return db.get(userId);
}
return null;
}
/**
* Write to DB.
*
* @param userAccount {@link UserAccount}
* @return {@link UserAccount}
*/
@Override
public UserAccount writeToDb(final UserAccount userAccount) {
db.put(userAccount.getUserId(), userAccount);
return userAccount;
}
/**
* Update reecord in DB.
*
* @param userAccount {@link UserAccount}
* @return {@link UserAccount}
*/
@Override
public UserAccount updateDb(final UserAccount userAccount) {
return writeToDb(userAccount);
}
/**
* Update.
*
* @param userAccount {@link UserAccount}
* @return {@link UserAccount}
*/
@Override
public UserAccount upsertDb(final UserAccount userAccount) {
return updateDb(userAccount);
}
}
| tyrellbaker-blip/java-design-patterns | caching/src/main/java/com/iluwatar/caching/database/VirtualDb.java |
2,901 | // Given two strings S and T, determine if they are both one edit distance apart.
public class OneEditDistance {
public boolean isOneEditDistance(String s, String t) {
//iterate through the length of the smaller string
for(int i = 0; i < Math.min(s.length(), t.length()); i++) {
//if the current characters of the two strings are not equal
if(s.charAt(i) != t.charAt(i)) {
//return true if the remainder of the two strings are equal, false otherwise
if(s.length() == t.length()) {
return s.substring(i + 1).equals(t.substring(i + 1));
} else if(s.length() < t.length()) {
//return true if the strings would be the same if you deleted a character from string t
return s.substring(i).equals(t.substring(i + 1));
} else {
//return true if the strings would be the same if you deleted a character from string s
return t.substring(i).equals(s.substring(i + 1));
}
}
}
//if all characters match for the length of the two strings check if the two strings' lengths do not differ by more than 1
return Math.abs(s.length() - t.length()) == 1;
}
}
| kdn251/interviews | leetcode/string/OneEditDistance.java |
2,906 | // Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
// You have the following 3 operations permitted on a word:
// a) Insert a character
// b) Delete a character
// c) Replace a character
public class EditDistance {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] dp = new int[m + 1][n + 1];
for(int i = 0; i <= m; i++) {
dp[i][0] = i;
}
for(int i = 0; i <= n; i++) {
dp[0][i] = i;
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(word1.charAt(i) == word2.charAt(j)) {
dp[i + 1][j + 1] = dp[i][j];
} else {
int a = dp[i][j];
int b = dp[i][j + 1];
int c = dp[i + 1][j];
dp[i + 1][j + 1] = Math.min(a, Math.min(b, c));
dp[i + 1][j + 1]++;
}
}
}
return dp[m][n];
}
}
| kdn251/interviews | leetcode/string/EditDistance.java |
2,915 | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.*;
class ForEach{
public void printList(List<String> strings){
for (String string : strings){
if (string.startsWith("XX")){
System.out.println("XX");
}
if (string.startsWith("YY")){
continue;
}
if (string.startsWith("ZZ")){
break;
}
System.out.println(string);
}
}
public void printListNoBreak(List<String> strings){
for (String string : strings){
if (string.startsWith("XX")){
System.out.println("XX");
}
if (string.startsWith("YY")){
continue;
}
System.out.println(string);
}
}
}
| NationalSecurityAgency/ghidra | Ghidra/Processors/JVM/resources/ForEach.java |
2,916 | 404: Not Found | apache/dubbo | dubbo-demo/dubbo-demo-interface/src/main/java/po/TestPO.java |
2,918 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package retrofit2.http;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import okhttp3.HttpUrl;
/**
* Use a custom HTTP verb for a request.
*
* <pre><code>
* interface Service {
* @HTTP(method = "CUSTOM", path = "custom/endpoint/")
* Call<ResponseBody> customEndpoint();
* }
* </code></pre>
*
* This annotation can also used for sending {@code DELETE} with a request body:
*
* <pre><code>
* interface Service {
* @HTTP(method = "DELETE", path = "remove/", hasBody = true)
* Call<ResponseBody> deleteObject(@Body RequestBody object);
* }
* </code></pre>
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface HTTP {
String method();
/**
* A relative or absolute path, or full URL of the endpoint. This value is optional if the first
* parameter of the method is annotated with {@link Url @Url}.
*
* <p>See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
* this is resolved against a base URL to create the full endpoint URL.
*/
String path() default "";
boolean hasBody() default false;
}
| square/retrofit | retrofit/src/main/java/retrofit2/http/HTTP.java |
2,925 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package units;
import abstractextensions.UnitExtension;
import concreteextensions.Soldier;
import java.util.Optional;
/**
* Class defining SoldierUnit.
*/
public class SoldierUnit extends Unit {
public SoldierUnit(String name) {
super(name);
}
@Override
public UnitExtension getUnitExtension(String extensionName) {
if (extensionName.equals("SoldierExtension")) {
return Optional.ofNullable(unitExtension).orElseGet(() -> new Soldier(this));
}
return super.getUnitExtension(extensionName);
}
}
| smedals/java-design-patterns | extension-objects/src/main/java/units/SoldierUnit.java |
2,926 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mediator;
/**
* Rogue party member.
*/
public class Rogue extends PartyMemberBase {
@Override
public String toString() {
return "Rogue";
}
}
| smedals/java-design-patterns | mediator/src/main/java/com/iluwatar/mediator/Rogue.java |
2,927 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mediator;
/**
* Hobbit party member.
*/
public class Hobbit extends PartyMemberBase {
@Override
public String toString() {
return "Hobbit";
}
}
| smedals/java-design-patterns | mediator/src/main/java/com/iluwatar/mediator/Hobbit.java |
2,928 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.visitor;
/**
* Sergeant.
*/
public class Sergeant extends Unit {
public Sergeant(Unit... children) {
super(children);
}
/**
* Accept a Visitor.
* @param visitor UnitVisitor to be accepted
*/
@Override
public void accept(UnitVisitor visitor) {
visitor.visit(this);
super.accept(visitor);
}
@Override
public String toString() {
return "sergeant";
}
}
| smedals/java-design-patterns | visitor/src/main/java/com/iluwatar/visitor/Sergeant.java |
2,929 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mute;
import java.io.Closeable;
/**
* Represents any resource that the application might acquire and that must be closed after it is
* utilized. Example of such resources can be a database connection, open files, sockets.
*/
public interface Resource extends Closeable {
}
| smedals/java-design-patterns | mute-idiom/src/main/java/com/iluwatar/mute/Resource.java |
2,930 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factory;
import java.util.function.Supplier;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Enumeration for different types of coins.
*/
@RequiredArgsConstructor
@Getter
public enum CoinType {
COPPER(CopperCoin::new),
GOLD(GoldCoin::new);
private final Supplier<Coin> constructor;
}
| smedals/java-design-patterns | factory/src/main/java/com/iluwatar/factory/CoinType.java |
2,931 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
The MIT License (MIT)
Copyright (c) 2016 Paul Campbell
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.iluwatar.databus;
/**
* Events are sent via the Data-Bus.
*
* @author Paul Campbell ([email protected])
*/
public interface DataType {
/**
* Returns the data-bus the event is being sent on.
*
* @return The data-bus
*/
DataBus getDataBus();
/**
* Set the data-bus the event will be sent on.
*
* @param dataBus The data-bus
*/
void setDataBus(DataBus dataBus);
}
| smedals/java-design-patterns | data-bus/src/main/java/com/iluwatar/databus/DataType.java |
2,932 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package dto;
import java.util.List;
import java.util.Optional;
/**
* DTO for cakes.
*/
public class CakeInfo {
public final Optional<Long> id;
public final CakeToppingInfo cakeToppingInfo;
public final List<CakeLayerInfo> cakeLayerInfos;
/**
* Constructor.
*/
public CakeInfo(Long id, CakeToppingInfo cakeToppingInfo, List<CakeLayerInfo> cakeLayerInfos) {
this.id = Optional.of(id);
this.cakeToppingInfo = cakeToppingInfo;
this.cakeLayerInfos = cakeLayerInfos;
}
/**
* Constructor.
*/
public CakeInfo(CakeToppingInfo cakeToppingInfo, List<CakeLayerInfo> cakeLayerInfos) {
this.id = Optional.empty();
this.cakeToppingInfo = cakeToppingInfo;
this.cakeLayerInfos = cakeLayerInfos;
}
/**
* Calculate calories.
*/
public int calculateTotalCalories() {
var total = cakeToppingInfo != null ? cakeToppingInfo.calories : 0;
total += cakeLayerInfos.stream().mapToInt(c -> c.calories).sum();
return total;
}
@Override
public String toString() {
return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.orElse(-1L),
cakeToppingInfo, cakeLayerInfos, calculateTotalCalories());
}
}
| rajprins/java-design-patterns | layers/src/main/java/dto/CakeInfo.java |
2,933 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.command;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
* Base class for spell targets.
*/
@Setter
@Slf4j
@Getter
public abstract class Target {
private Size size;
private Visibility visibility;
/**
* Print status.
*/
public void printStatus() {
LOGGER.info("{}, [size={}] [visibility={}]", this, getSize(), getVisibility());
}
/**
* Changes the size of the target.
*/
public void changeSize() {
var oldSize = getSize() == Size.NORMAL ? Size.SMALL : Size.NORMAL;
setSize(oldSize);
}
/**
* Changes the visibility of the target.
*/
public void changeVisibility() {
var visible = getVisibility() == Visibility.INVISIBLE
? Visibility.VISIBLE : Visibility.INVISIBLE;
setVisibility(visible);
}
}
| smedals/java-design-patterns | command/src/main/java/com/iluwatar/command/Target.java |
2,935 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.dirtyflag;
import java.util.ArrayList;
import java.util.List;
/**
* A middle-layer app that calls/passes along data from the back-end.
*
* @author swaisuan
*/
public class World {
private List<String> countries;
private final DataFetcher df;
public World() {
this.countries = new ArrayList<>();
this.df = new DataFetcher();
}
/**
* Calls {@link DataFetcher} to fetch data from back-end.
*
* @return List of strings
*/
public List<String> fetch() {
var data = df.fetch();
countries = data.isEmpty() ? countries : data;
return countries;
}
}
| smedals/java-design-patterns | dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java |
2,936 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.flyweight;
/**
* Interface for Potions.
*/
public interface Potion {
void drink();
}
| smedals/java-design-patterns | flyweight/src/main/java/com/iluwatar/flyweight/Potion.java |
2,937 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.iterator;
/**
* Iterator interface to be implemented by iterators over various data structures.
*
* @param <T> generically typed for various objects
*/
public interface Iterator<T> {
boolean hasNext();
T next();
}
| smedals/java-design-patterns | iterator/src/main/java/com/iluwatar/iterator/Iterator.java |
2,939 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.callback;
/**
* Callback interface.
*/
public interface Callback {
void call();
}
| smedals/java-design-patterns | callback/src/main/java/com/iluwatar/callback/Callback.java |
2,941 | package com.thealgorithms.sorts;
import static com.thealgorithms.maths.Ceil.ceil;
import static com.thealgorithms.maths.Floor.floor;
import static com.thealgorithms.searches.QuickSelect.select;
import java.util.Arrays;
/**
* A wiggle sort implementation based on John L.s' answer in
* https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity
* Also have a look at:
* https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1
* Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable
* arrays and throw an error, but there are some exceptions that won't be caught, for example [1, 2,
* 2].
*/
public class WiggleSort implements SortAlgorithm {
@Override
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
return wiggleSort(unsorted);
}
private int mapIndex(int index, int n) {
return ((2 * index + 1) % (n | 1));
}
/**
* Modified Dutch National Flag Sort. See also: sorts/DutchNationalFlagSort
*
* @param sortThis array to sort into group "greater", "equal" and "smaller" than median
* @param median defines the groups
* @param <T> extends interface Comparable
*/
private <T extends Comparable<T>> void triColorSort(T[] sortThis, T median) {
int n = sortThis.length;
int i = 0;
int j = 0;
int k = n - 1;
while (j <= k) {
if (0 < sortThis[mapIndex(j, n)].compareTo(median)) {
SortUtils.swap(sortThis, mapIndex(j, n), mapIndex(i, n));
i++;
j++;
} else if (0 > sortThis[mapIndex(j, n)].compareTo(median)) {
SortUtils.swap(sortThis, mapIndex(j, n), mapIndex(k, n));
k--;
} else {
j++;
}
}
}
private <T extends Comparable<T>> T[] wiggleSort(T[] sortThis) {
// find the median using quickSelect (if the result isn't in the array, use the next greater
// value)
T median;
median = select(Arrays.asList(sortThis), (int) floor(sortThis.length / 2.0));
int numMedians = 0;
for (T sortThi : sortThis) {
if (0 == sortThi.compareTo(median)) {
numMedians++;
}
}
// added condition preventing off-by-one errors for odd arrays.
// https://cs.stackexchange.com/questions/150886/how-to-find-wiggle-sortable-arrays-did-i-misunderstand-john-l-s-answer?noredirect=1&lq=1
if (sortThis.length % 2 == 1 && numMedians == ceil(sortThis.length / 2.0)) {
T smallestValue = select(Arrays.asList(sortThis), 0);
if (!(0 == smallestValue.compareTo(median))) {
throw new IllegalArgumentException("For odd Arrays if the median appears ceil(n/2) times, "
+ "the median has to be the smallest values in the array.");
}
}
if (numMedians > ceil(sortThis.length / 2.0)) {
throw new IllegalArgumentException("No more than half the number of values may be the same.");
}
triColorSort(sortThis, median);
return sortThis;
}
}
| satishppawar/Java | src/main/java/com/thealgorithms/sorts/WiggleSort.java |
2,943 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* OrcMage.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class OrcMage extends Mage {
private final String weapon;
public OrcMage(OrcMage orcMage) {
super(orcMage);
this.weapon = orcMage.weapon;
}
@Override
public String toString() {
return "Orcish mage attacks with " + weapon;
}
}
| smedals/java-design-patterns | prototype/src/main/java/com/iluwatar/prototype/OrcMage.java |
2,944 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.threadpool;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Abstract base class for tasks.
*/
public abstract class Task {
private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
private final int id;
private final int timeMs;
public Task(final int timeMs) {
this.id = ID_GENERATOR.incrementAndGet();
this.timeMs = timeMs;
}
public int getId() {
return id;
}
public int getTimeMs() {
return timeMs;
}
@Override
public String toString() {
return String.format("id=%d timeMs=%d", id, timeMs);
}
}
| smedals/java-design-patterns | thread-pool/src/main/java/com/iluwatar/threadpool/Task.java |
2,945 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.command;
import java.util.Deque;
import java.util.LinkedList;
import lombok.extern.slf4j.Slf4j;
/**
* Wizard is the invoker of the commands.
*/
@Slf4j
public class Wizard {
private final Deque<Runnable> undoStack = new LinkedList<>();
private final Deque<Runnable> redoStack = new LinkedList<>();
/**
* Cast spell.
*/
public void castSpell(Runnable runnable) {
runnable.run();
undoStack.offerLast(runnable);
}
/**
* Undo last spell.
*/
public void undoLastSpell() {
if (!undoStack.isEmpty()) {
var previousSpell = undoStack.pollLast();
redoStack.offerLast(previousSpell);
previousSpell.run();
}
}
/**
* Redo last spell.
*/
public void redoLastSpell() {
if (!redoStack.isEmpty()) {
var previousSpell = redoStack.pollLast();
undoStack.offerLast(previousSpell);
previousSpell.run();
}
}
@Override
public String toString() {
return "Wizard";
}
}
| smedals/java-design-patterns | command/src/main/java/com/iluwatar/command/Wizard.java |
2,947 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factorykit;
/**
* Class representing Spear.
*/
public class Spear implements Weapon {
@Override
public String toString() {
return "Spear";
}
}
| smedals/java-design-patterns | factory-kit/src/main/java/com/iluwatar/factorykit/Spear.java |
2,948 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* OrcBeast.
*/
@EqualsAndHashCode(callSuper = false)
@RequiredArgsConstructor
public class OrcBeast extends Beast {
private final String weapon;
public OrcBeast(OrcBeast orcBeast) {
super(orcBeast);
this.weapon = orcBeast.weapon;
}
@Override
public String toString() {
return "Orcish wolf attacks with " + weapon;
}
}
| smedals/java-design-patterns | prototype/src/main/java/com/iluwatar/prototype/OrcBeast.java |
2,949 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.multiton;
/**
* Each Nazgul has different {@link NazgulName}.
*/
public enum NazgulName {
KHAMUL,
MURAZOR,
DWAR,
JI_INDUR,
AKHORAHIL,
HOARMURATH,
ADUNAPHEL,
REN,
UVATHA
}
| smedals/java-design-patterns | multiton/src/main/java/com/iluwatar/multiton/NazgulName.java |
2,950 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factorykit;
/**
* Class representing Swords.
*/
public class Sword implements Weapon {
@Override
public String toString() {
return "Sword";
}
}
| smedals/java-design-patterns | factory-kit/src/main/java/com/iluwatar/factorykit/Sword.java |
2,951 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* ElfBeast.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class ElfBeast extends Beast {
private final String helpType;
public ElfBeast(ElfBeast elfBeast) {
super(elfBeast);
this.helpType = elfBeast.helpType;
}
@Override
public String toString() {
return "Elven eagle helps in " + helpType;
}
}
| smedals/java-design-patterns | prototype/src/main/java/com/iluwatar/prototype/ElfBeast.java |
2,953 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factorykit;
/**
* Interface representing weapon.
*/
public interface Weapon {
}
| smedals/java-design-patterns | factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java |
2,954 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.caching;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Enum class containing the four caching strategies implemented in the pattern.
*/
@AllArgsConstructor
@Getter
public enum CachingPolicy {
/**
* Through.
*/
THROUGH("through"),
/**
* AROUND.
*/
AROUND("around"),
/**
* BEHIND.
*/
BEHIND("behind"),
/**
* ASIDE.
*/
ASIDE("aside");
/**
* Policy value.
*/
private final String policy;
}
| smedals/java-design-patterns | caching/src/main/java/com/iluwatar/caching/CachingPolicy.java |
2,956 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.gameloop;
/**
* Enum class for game status.
*/
public enum GameStatus {
RUNNING, STOPPED
}
| smedals/java-design-patterns | game-loop/src/main/java/com/iluwatar/gameloop/GameStatus.java |
2,957 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.tablemodule;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* A user POJO that represents the data that will be read from the data source.
*/
@Setter
@Getter
@ToString
@EqualsAndHashCode
@AllArgsConstructor
public class User {
private int id;
private String username;
private String password;
}
| smedals/java-design-patterns | table-module/src/main/java/com/iluwatar/tablemodule/User.java |
2,959 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.unitofwork;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* {@link Weapon} is an entity.
*/
@Getter
@RequiredArgsConstructor
public class Weapon {
private final Integer id;
private final String name;
}
| smedals/java-design-patterns | unit-of-work/src/main/java/com/iluwatar/unitofwork/Weapon.java |
2,961 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* ElfWarlord.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class ElfWarlord extends Warlord {
private final String helpType;
public ElfWarlord(ElfWarlord elfWarlord) {
super(elfWarlord);
this.helpType = elfWarlord.helpType;
}
@Override
public String toString() {
return "Elven warlord helps in " + helpType;
}
}
| smedals/java-design-patterns | prototype/src/main/java/com/iluwatar/prototype/ElfWarlord.java |
2,962 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factorykit;
import java.util.function.Supplier;
/**
* Functional interface that allows adding builder with name to the factory.
*/
public interface Builder {
void add(WeaponType name, Supplier<Weapon> supplier);
}
| smedals/java-design-patterns | factory-kit/src/main/java/com/iluwatar/factorykit/Builder.java |
2,963 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.prototype;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
/**
* OrcWarlord.
*/
@EqualsAndHashCode(callSuper = true)
@RequiredArgsConstructor
public class OrcWarlord extends Warlord {
private final String weapon;
public OrcWarlord(OrcWarlord orcWarlord) {
super(orcWarlord);
this.weapon = orcWarlord.weapon;
}
@Override
public String toString() {
return "Orcish warlord attacks with " + weapon;
}
}
| smedals/java-design-patterns | prototype/src/main/java/com/iluwatar/prototype/OrcWarlord.java |
2,967 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.prototype;
/**
* Interface for the factory class.
*/
public interface HeroFactory {
Mage createMage();
Warlord createWarlord();
Beast createBeast();
}
| smedals/java-design-patterns | prototype/src/main/java/com/iluwatar/prototype/HeroFactory.java |
2,969 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.bridge;
import lombok.extern.slf4j.Slf4j;
/**
* FlyingEnchantment.
*/
@Slf4j
public class FlyingEnchantment implements Enchantment {
@Override
public void onActivate() {
LOGGER.info("The item begins to glow faintly.");
}
@Override
public void apply() {
LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand.");
}
@Override
public void onDeactivate() {
LOGGER.info("The item's glow fades.");
}
}
| smedals/java-design-patterns | bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java |
2,971 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.cqrs.domain.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* This is a Book entity. It is used by Hibernate for persistence. Many books can be written by one
* {@link Author}
*/
@ToString
@Setter
@Getter
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String title;
private double price;
@ManyToOne
private Author author;
/**
* Constructor.
*
* @param title title of the book
* @param price price of the book
* @param author author of the book
*/
public Book(String title, double price, Author author) {
this.title = title;
this.price = price;
this.author = author;
}
protected Book() {
}
}
| smedals/java-design-patterns | cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java |
2,974 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.flyweight;
import lombok.extern.slf4j.Slf4j;
/**
* PoisonPotion.
*/
@Slf4j
public class PoisonPotion implements Potion {
@Override
public void drink() {
LOGGER.info("Urgh! This is poisonous. (Potion={})", System.identityHashCode(this));
}
}
| smedals/java-design-patterns | flyweight/src/main/java/com/iluwatar/flyweight/PoisonPotion.java |
2,976 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.decorator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Decorator that adds a club for the troll.
*/
@Slf4j
@RequiredArgsConstructor
public class ClubbedTroll implements Troll {
private final Troll decorated;
@Override
public void attack() {
decorated.attack();
LOGGER.info("The troll swings at you with a club!");
}
@Override
public int getAttackPower() {
return decorated.getAttackPower() + 10;
}
@Override
public void fleeBattle() {
decorated.fleeBattle();
}
}
| smedals/java-design-patterns | decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java |
2,977 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.updatemethod;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract class for all the entity types.
*/
public abstract class Entity {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected int id;
@Getter
@Setter
protected int position;
public Entity(int id) {
this.id = id;
this.position = 0;
}
public abstract void update();
}
| smedals/java-design-patterns | update-method/src/main/java/com/iluwatar/updatemethod/Entity.java |
2,979 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.data;
import com.iluwatar.databus.AbstractDataType;
import com.iluwatar.databus.DataType;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* An event raised when a string message is sent.
*
* @author Paul Campbell ([email protected])
*/
@Getter
@AllArgsConstructor
public class MessageData extends AbstractDataType {
private final String message;
public static DataType of(final String message) {
return new MessageData(message);
}
}
| smedals/java-design-patterns | data-bus/src/main/java/com/iluwatar/databus/data/MessageData.java |
2,980 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.facade;
import lombok.extern.slf4j.Slf4j;
/**
* DwarvenTunnelDigger is one of the goldmine subsystems.
*/
@Slf4j
public class DwarvenTunnelDigger extends DwarvenMineWorker {
@Override
public void work() {
LOGGER.info("{} creates another promising tunnel.", name());
}
@Override
public String name() {
return "Dwarven tunnel digger";
}
}
| smedals/java-design-patterns | facade/src/main/java/com/iluwatar/facade/DwarvenTunnelDigger.java |
2,981 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.flyweight;
import lombok.extern.slf4j.Slf4j;
/**
* HealingPotion.
*/
@Slf4j
public class HealingPotion implements Potion {
@Override
public void drink() {
LOGGER.info("You feel healed. (Potion={})", System.identityHashCode(this));
}
}
| smedals/java-design-patterns | flyweight/src/main/java/com/iluwatar/flyweight/HealingPotion.java |
2,983 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.gameloop;
/**
* Update and render objects in the game. Here we add a Bullet object to the
* game system to show how the game loop works.
*/
public class GameController {
protected final Bullet bullet;
/**
* Initialize Bullet instance.
*/
public GameController() {
bullet = new Bullet();
}
/**
* Move bullet position by the provided offset.
*
* @param offset moving offset
*/
public void moveBullet(float offset) {
var currentPosition = bullet.getPosition();
bullet.setPosition(currentPosition + offset);
}
/**
* Get current position of the bullet.
*
* @return position of bullet
*/
public float getBulletPosition() {
return bullet.getPosition();
}
}
| smedals/java-design-patterns | game-loop/src/main/java/com/iluwatar/gameloop/GameController.java |
2,984 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.filterer.domain;
import java.util.function.Predicate;
/**
* Filterer helper interface.
* @param <G> type of the container-like object.
* @param <E> type of the elements contained within this container-like object.
*/
@FunctionalInterface
public interface Filterer<G, E> {
G by(Predicate<? super E> predicate);
} | smedals/java-design-patterns | filterer/src/main/java/com/iluwatar/filterer/domain/Filterer.java |
2,985 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package service;
import dto.CakeInfo;
import dto.CakeLayerInfo;
import dto.CakeToppingInfo;
import exception.CakeBakingException;
import java.util.List;
import org.springframework.stereotype.Service;
/**
* Service for cake baking operations.
*/
@Service
public interface CakeBakingService {
/**
* Bakes new cake according to parameters.
*/
void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException;
/**
* Get all cakes.
*/
List<CakeInfo> getAllCakes();
/**
* Store new cake topping.
*/
void saveNewTopping(CakeToppingInfo toppingInfo);
/**
* Get available cake toppings.
*/
List<CakeToppingInfo> getAvailableToppings();
/**
* Add new cake layer.
*/
void saveNewLayer(CakeLayerInfo layerInfo);
/**
* Get available cake layers.
*/
List<CakeLayerInfo> getAvailableLayers();
void deleteAllCakes();
void deleteAllLayers();
void deleteAllToppings();
}
| rajprins/java-design-patterns | layers/src/main/java/service/CakeBakingService.java |
2,986 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.dao;
import java.io.Serial;
/**
* Custom exception.
*/
public class CustomException extends Exception {
@Serial
private static final long serialVersionUID = 1L;
public CustomException(String message, Throwable cause) {
super(message, cause);
}
}
| rajprins/java-design-patterns | dao/src/main/java/com/iluwatar/dao/CustomException.java |
2,987 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.currying;
/**
* Enum representing different book genres.
*/
public enum Genre {
FANTASY,
HORROR,
SCIFI
}
| rajprins/java-design-patterns | currying/src/main/java/com/iluwatar/currying/Genre.java |
2,990 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.data;
import com.iluwatar.databus.AbstractDataType;
import com.iluwatar.databus.DataType;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* An event raised when applications starts, containing the start time of the application.
*
* @author Paul Campbell ([email protected])
*/
@RequiredArgsConstructor
@Getter
public class StartingData extends AbstractDataType {
private final LocalDateTime when;
public static DataType of(final LocalDateTime when) {
return new StartingData(when);
}
}
| smedals/java-design-patterns | data-bus/src/main/java/com/iluwatar/databus/data/StartingData.java |
2,991 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.objectmother;
/**
* Interface contracting Royalty Behaviour.
*/
public interface Royalty {
void makeDrunk();
void makeSober();
void makeHappy();
void makeUnhappy();
}
| smedals/java-design-patterns | object-mother/src/main/java/com/iluwatar/objectmother/Royalty.java |
2,992 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.typeobject;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
/**
* The Candy class has a field type, which represents the 'type' of candy. The objects are created
* by parsing the candy.json file.
*/
@Getter(AccessLevel.PACKAGE)
public class Candy {
enum Type {
CRUSHABLE_CANDY,
REWARD_FRUIT
}
String name;
Candy parent;
String parentName;
@Setter
private int points;
private final Type type;
Candy(String name, String parentName, Type type, int points) {
this.name = name;
this.parent = null;
this.type = type;
this.points = points;
this.parentName = parentName;
}
}
| smedals/java-design-patterns | typeobjectpattern/src/main/java/com/iluwatar/typeobject/Candy.java |
2,993 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.observer.generic;
/**
* Observer.
*
* @param <S> Observable
* @param <O> Observer
* @param <A> Action
*/
public interface Observer<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> {
void update(S subject, A argument);
}
| smedals/java-design-patterns | observer/src/main/java/com/iluwatar/observer/generic/Observer.java |
2,994 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.databus.data;
import com.iluwatar.databus.AbstractDataType;
import com.iluwatar.databus.DataType;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* An event raised when applications stops, containing the stop time of the application.
*
* @author Paul Campbell ([email protected])
*/
@RequiredArgsConstructor
@Getter
public class StoppingData extends AbstractDataType {
private final LocalDateTime when;
public static DataType of(final LocalDateTime when) {
return new StoppingData(when);
}
}
| smedals/java-design-patterns | data-bus/src/main/java/com/iluwatar/databus/data/StoppingData.java |
2,995 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.value.object;
import lombok.Value;
/**
* HeroStat is a value object.
*
* @see <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html">
* http://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html
* </a>
*/
@Value(staticConstructor = "valueOf")
class HeroStat {
int strength;
int intelligence;
int luck;
}
| smedals/java-design-patterns | value-object/src/main/java/com/iluwatar/value/object/HeroStat.java |
2,996 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.flyweight;
import lombok.extern.slf4j.Slf4j;
/**
* StrengthPotion.
*/
@Slf4j
public class StrengthPotion implements Potion {
@Override
public void drink() {
LOGGER.info("You feel strong. (Potion={})", System.identityHashCode(this));
}
}
| smedals/java-design-patterns | flyweight/src/main/java/com/iluwatar/flyweight/StrengthPotion.java |
2,997 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.converter;
/**
* User record.
*/
public record User(String firstName, String lastName, boolean active, String userId) {}
| rajprins/java-design-patterns | converter/src/main/java/com/iluwatar/converter/User.java |
2,998 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.strangler;
import lombok.extern.slf4j.Slf4j;
/**
* Old version system depends on old version source ({@link OldSource}).
*/
@Slf4j
public class OldArithmetic {
private static final String VERSION = "1.0";
private final OldSource source;
public OldArithmetic(OldSource source) {
this.source = source;
}
/**
* Accumulate sum.
* @param nums numbers need to add together
* @return accumulate sum
*/
public int sum(int... nums) {
LOGGER.info("Arithmetic sum {}", VERSION);
return source.accumulateSum(nums);
}
/**
* Accumulate multiplication.
* @param nums numbers need to multiply together
* @return accumulate multiplication
*/
public int mul(int... nums) {
LOGGER.info("Arithmetic mul {}", VERSION);
return source.accumulateMul(nums);
}
}
| smedals/java-design-patterns | strangler/src/main/java/com/iluwatar/strangler/OldArithmetic.java |
2,999 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.balking;
/**
* WashingMachineState enum describes in which state machine is, it can be enabled and ready to work
* as well as during washing.
*/
public enum WashingMachineState {
ENABLED,
WASHING
}
| smedals/java-design-patterns | balking/src/main/java/com/iluwatar/balking/WashingMachineState.java |
3,000 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.event.queue;
import javax.sound.sampled.AudioInputStream;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
* The Event Queue's queue will store the instances of this class.
*
* @author mkuprivecz
*/
@Getter
@AllArgsConstructor
public class PlayMessage {
private final AudioInputStream stream;
@Setter
private float volume;
}
| smedals/java-design-patterns | event-queue/src/main/java/com/iluwatar/event/queue/PlayMessage.java |
3,001 | package com.company;
import com.sun.org.apache.xpath.internal.SourceTree;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
/**
* Created by Renzie on 14/04/2016.
*/
public class Actiekaart {
public int speelactiekaart(String naam, Speler speler, Spel spel, int truefalse, List<String> kaarten) {
switch (naam) {
case "Heks":
heks(spel, speler);
break;
case "Kelder":
kelder(spel, speler, kaarten);
break;
case "Kerk":
kerk(spel, speler, kaarten);
break;
case "Gracht":
gracht(speler);
break;
case "Kanselier":
kanselier(speler, truefalse);
break;
case "Dorps":
dorps(speler);
break;
case "Houthakker":
houthakker(speler);
break;
case "Werkplaats":
return werkplaats();
case "Feest":
return feest(spel, speler);
case "Geldverlener":
geldverlener(spel, speler, kaarten);
break;
case "Ombouwen":
return ombouwen(spel, speler, kaarten);
case "Smederij":
smederij(speler);
break;
case "Raadzaal":
raadzaal(spel, speler);
break;
case "Festival":
festival(speler);
break;
case "Laboratorium":
laboratorium(speler);
break;
case "Markt":
markt(speler);
break;
case "Mijn":
mijn(spel, speler, kaarten);
break;
case "Avonturier":
avonturier(speler);
break;
}
return 0;
}
public List<String> speelactiekaartspecial(String naam, Spel spel, Speler speler, List<String> kaarten, int janee) {
List<String> emptylist = new ArrayList<>();
switch (naam) {
case "Dief":
return dief(spel, speler, kaarten);
case "Bibliotheek":
return bibliotheek(speler, kaarten, janee);
case "Schutterij":
return schutterij(spel, speler);
case "Bureaucraat":
return bureaucraat(spel, speler);
case "Spion":
return spion(spel, speler, janee, kaarten);
case "Troonzaal":
return troonzaal(spel, speler, kaarten);
}
return emptylist;
}
public void checkDeck(Speler speler, int aantal) {
if (speler.getDeck().size() < aantal) {
speler.leegAflegstapel();
}
}
public int overloopKaartLijst(Spel spel, Speler speler, List<String> kaarten, int maxwaarde, List<Kaart> bestemming) {
boolean selected = false;
int aantalkaarten = 0;
for (String s : kaarten) {
for (Kaart k : spel.getAlleKaarten()) {
if (Objects.equals(k.getNaam(), s) && !selected && aantalkaarten < maxwaarde) {
spel.voegKaartToe(1, k, speler.getHand(), bestemming);
aantalkaarten++;
selected = true;
}
}
selected = false;
}
return aantalkaarten;
}
public boolean heeftReactiekaart(Speler s) {
for (Kaart k : s.getHand()) {
if (Objects.equals(k.getType(), "Actie-Reactie")) {
return true;
}
}
return false;
}
public Kaart duidSpecifiekeKaartAan(String naam, Spel spel) {
for (Kaart k : spel.getAlleKaarten()) {
if (Objects.equals(k.getNaam(), naam)) {
return k;
}
}
return null;
}
public void heks(Spel spel, Speler speler) {
checkDeck(speler, 2);
speler.voegKaartToe(2, speler.getDeck(), speler.getHand()); //+2 kaarten
for (Speler s : spel.getSpelers()) { //geef de andere spelers een vloekkaart
if (!Objects.equals(s.getNaam(), speler.getNaam()) && !heeftReactiekaart(s)) {
spel.koopKaart(duidSpecifiekeKaartAan("Vloek", spel), s.getAflegstapel());
}
}
}
public void kelder(Spel spel, Speler speler, List<String> kaarten) {
//+1 actie
speler.addActie(1);
//selecteer de kaarten die je wilt afleggen
//trek x nieuwe kaarten
int aantalkaarten = overloopKaartLijst(spel, speler, kaarten, 7, speler.getAflegstapel());
checkDeck(speler, aantalkaarten);
speler.voegKaartToe(aantalkaarten, speler.getDeck(), speler.getHand());
}
public void kerk(Spel spel, Speler speler, List<String> kaarten) {
//plaats tot 4 kaarten in de vuilbak
overloopKaartLijst(spel, speler, kaarten, 4, speler.getVuilbak());
}
public void gracht(Speler speler) {
//trek 2 kaarten
checkDeck(speler, 2);
speler.voegKaartToe(2, speler.getDeck(), speler.getHand());
}
public void kanselier(Speler speler, int truefalse) {
speler.addGeld(2);//+2 geld
//je mag je deck in de aflegstapel gooien
if (truefalse == 1) {
speler.voegKaartToe(speler.getDeck().size(), speler.getDeck(), speler.getAflegstapel());
}
}
public void dorps(Speler speler) {
checkDeck(speler, 1);
speler.voegKaartToe(1, speler.getDeck(), speler.getHand());
speler.addActie(2);
}
public void houthakker(Speler speler) {
speler.addKoop(1);
speler.addGeld(2);
}
public int werkplaats() {
//neem een kaart met <=4 kost
return 4;
}
public List<String> bureaucraat(Spel spel, Speler speler) {
//krijg een zilver kaart
boolean done = false;
Kaart kaart = new Kaart();
for(Kaart k : spel.getGeldveld()){
if(Objects.equals(k.getNaam(), "Zilver") && !done){
kaart = k;
done = true;
}
}
spel.koopKaart(kaart, speler.getDeck());
//elke andere speler toont een overwinningskaart en plaatst het op zijn deck (of toont een hand zonder overwinningskaarten)
List<String> kaarten = new ArrayList();
int i = 0;
for (Speler s : spel.getSpelers()) {
if (!Objects.equals(s.getNaam(), speler.getNaam()) && !heeftReactiekaart(s)) {
List<Kaart> handspeler = new ArrayList<>();
for(Kaart k : s.getHand()){
handspeler.add(k);
}
for (Kaart k : handspeler) {
if (Objects.equals(k.getType(), "Overwinning")) {
kaarten.add(k.getNaam());
spel.voegKaartToe(1, k, s.getHand(), s.getDeck());
i++;
}
}
if (i == 0) {
for (Kaart k2 : s.getHand()) {
kaarten.add(k2.getNaam());
}
}
}
}
return kaarten;
}
public int feest(Spel spel, Speler speler) {
//deze kaart naar trash
spel.voegKaartToe(1, duidSpecifiekeKaartAan("Feest", spel), speler.getHand(), speler.getVuilbak());
//neem kaart die max 5 geld kost
return 5;
}
public List<String> schutterij(Spel spel, Speler speler) {
//+2Geld
speler.addGeld(2);
//leg kaarten af tot alle spelers 3 kaarten over heeft
List<String> legeArray = new ArrayList<>();
boolean selected = false;
List<String> kaarten = new ArrayList<>();
for (Speler s : spel.getSpelers()) {
if (!Objects.equals(s.getNaam(), speler.getNaam()) && !heeftReactiekaart(s)) {
if (s.getHand().size()>3){
for (Kaart k2 : s.getHand()) {
kaarten.add(k2.getNaam());
}
}
overloopKaartLijst(spel, s, kaarten , s.getHand().size()-3, s.getAflegstapel());
}
}
return kaarten;
}
public void geldverlener(Spel spel, Speler speler, List<String> kaarten) {
//thrash koper
//krijg +3 geld
if (Objects.equals(kaarten.get(0), "Koper")){
overloopKaartLijst(spel, speler, kaarten, 1, speler.getVuilbak());
speler.addGeld(3);
}
}
public int ombouwen(Spel spel, Speler speler, List<String> kaarten) {
//select kaart -> thrash
overloopKaartLijst(spel, speler, kaarten, 1, speler.getVuilbak());
//krijg een kaart die tot 2 meer geld kost
int trashkaartwaarde = 0;
for (Kaart k : spel.getAlleKaarten()) {
if (Objects.equals(k.getNaam(), kaarten.get(0))) {
trashkaartwaarde = k.getKost();
}
}
trashkaartwaarde = trashkaartwaarde + 2;
return trashkaartwaarde;
}
public void smederij(Speler speler) {
checkDeck(speler, 3);
speler.voegKaartToe(3, speler.getDeck(), speler.getHand());
}
public List<String> spion(Spel spel, Speler speler, int janee, List<String> kaarten) {
List<String> kaart = new ArrayList<>();
if(janee != 0){
//+1 kaart
checkDeck(speler, 1);
speler.voegKaartToe(1, speler.getDeck(), speler.getHand());
//+1 actie
speler.addActie(1);
//elke speler bekijkt de bovenste kaart van zijn deck en de speler kan beslissen of het naar de aflegstapel gaat
for (Speler s : spel.getSpelers()) {
if (!heeftReactiekaart(s) || Objects.equals(s.getNaam(), speler.getNaam())) {
checkDeck(s, 1);
Kaart k = s.getDeck().get(0);
kaart.add(s.getNaam());
kaart.add(k.getNaam());
}
}
} else {
Speler vijand = new Speler("placeholder");
for(Speler s : spel.getSpelers()){
if(!Objects.equals(s.getNaam(), speler.getNaam())){
vijand = s;
}
}
Speler huidig = new Speler("placeholder");
for(String s : kaarten){
if(Objects.equals(s, "jezelf")){
huidig = speler;
} else if(Objects.equals(s, "de vijand")){
huidig = vijand;
} else {
huidig.voegKaartToe(1, huidig.getDeck(), huidig.getAflegstapel());
}
}
}
return kaart;
}
public List<String> dief(Spel spel, Speler speler, List<String> kaarten) {
/*Each other player reveals the top 2 cards of his deck.
If they revealed any Treasure cards, they trash one of them that you choose.
You may gain any or all of these trashed cards.
They discard the other revealed cards.*/
List<String> testelenkaarten = new ArrayList<>();
for (Speler s : spel.getSpelers()) {
if (!Objects.equals(s.getNaam(), speler.getNaam()) && !heeftReactiekaart(s)) {
for (int i = 0; i < 2; i++) {
checkDeck(s, 2);
Kaart k = s.getDeck().get(i);
if (Objects.equals(k.getType(), "Geld") && !kaarten.contains(k.getNaam()) && kaarten.size() == 0) {
testelenkaarten.add(k.getNaam());
} else if (Objects.equals(k.getType(), "Geld") && kaarten.contains(k.getNaam())) {
spel.voegKaartToe(1, k, s.getDeck(), speler.getAflegstapel());
}
}
}
}
return testelenkaarten;
}
public List<String> troonzaal(Spel spel, Speler speler, List<String> kaarten) {
//kies een actiekaart
List<String> message = new ArrayList<>();
boolean done = false;
//plaats de gekozen actiekaart in de aflegstapel
for(int i=0;i<speler.getHand().size();i++){
Kaart k = speler.getHand().get(i);
if(Objects.equals(k.getNaam(), kaarten.get(0)) && !done){
spel.voegKaartToe(1, k, speler.getHand(), speler.getAflegstapel());
done = true;
}
}
return message;
}
public void raadzaal(Spel spel, Speler speler) {
//+4 kaarten
checkDeck(speler, 4);
speler.voegKaartToe(4, speler.getDeck(), speler.getHand());
//+1 koop
speler.addKoop(1);
//andere spelers trekken 1 kaart
for (Speler s : spel.getSpelers()) {
if (!Objects.equals(s.getNaam(), speler.getNaam())) {
s.voegKaartToe(1, s.getDeck(), s.getHand());
}
}
}
public void festival(Speler speler) {
//+2 acties +1 buy +2geld
speler.addActie(2);
speler.addKoop(1);
speler.addGeld(2);
}
public void laboratorium(Speler speler) {
//+2 kaarten
checkDeck(speler, 2);
speler.voegKaartToe(2, speler.getDeck(), speler.getHand());
//+1actie
speler.addActie(1);
}
public List<String> bibliotheek(Speler speler, List<String> kaarten, int eersteinstantie) {
List<String> kaart = new ArrayList<>();
boolean done = false;
if (kaarten.size() > 0) {
checkDeck(speler, 1);
speler.voegKaartToe(1, speler.getDeck(), speler.getHand());
}
if (eersteinstantie != 0) {
done = true;
}
while (speler.getHand().size() <= 7) {
checkDeck(speler, 1);
Kaart k = speler.getDeck().get(0);
if (k.getType().contains("Actie") && done) {
kaart.add(k.getNaam());
return kaart;
} else if (eersteinstantie == 0 && !done) {
speler.voegKaartToe(1, speler.getDeck(), speler.getAflegstapel());
done = true;
} else {
speler.voegKaartToe(1, speler.getDeck(), speler.getHand());
}
}
return kaart;
}
public void markt(Speler speler) {
//+1 kaart
checkDeck(speler, 1);
speler.voegKaartToe(1, speler.getDeck(), speler.getHand());
//+1geld +1 koop +1actie
speler.addGeld(1);
speler.addKoop(1);
speler.addActie(1);
}
public void mijn(Spel spel, Speler speler, List<String> kaarten) {
//thrash een geldkaart en geef de geldkaart met 1 waarde meer
int kost = 0;
boolean done = false;
for (Kaart k : spel.getGeldveld()) {
if (Objects.equals(kaarten.get(0), k.getNaam()) && Objects.equals(k.getType(), "Geld") && !done) {
overloopKaartLijst(spel, speler, kaarten, 1, speler.getVuilbak());
kost = k.getKost();
done = true;
}
}
done = false;
switch (kost) {
case 0:
for (int i = 0; i < spel.getGeldveld().size(); i++) {
if (Objects.equals(spel.getGeldveld().get(i).getNaam(), "Zilver") && !done) {
spel.koopKaart(spel.getGeldveld().get(i), speler.getHand());
done = true;
i++;
}
}
break;
case 3:
case 6:
for (int i = 0; i < spel.getGeldveld().size(); i++) {
if (Objects.equals(spel.getGeldveld().get(i).getNaam(), "Goud") && !done) {
spel.koopKaart(spel.getGeldveld().get(i), speler.getHand());
done = true;
i++;
}
}
break;
default:
break;
}
}
public void avonturier(Speler speler) {
//blijf kaarten trekken tot je 2 geldkaarten krijgt
int maxGeldKaarten = 2;
int i = 0;
while (i < maxGeldKaarten) {
checkDeck(speler, 1);
Kaart bovenliggendeKaart = speler.getDeck().get(0);
if (!Objects.equals(bovenliggendeKaart.getType(), "Geld")) {
speler.voegKaartToe(1, speler.getDeck(), speler.getAflegstapel());
} else {
speler.voegKaartToe(1, speler.getDeck(), speler.getHand());
i++;
}
}
}
} | Yentis/Dominion | Source/src/com/company/Actiekaart.java |
3,002 | package nl.topicus.eduarte.web.pages.groep;
import nl.topicus.cobra.app.PageInfo;
import nl.topicus.cobra.reflection.ReflectionUtil;
import nl.topicus.cobra.security.InPrincipal;
import nl.topicus.cobra.web.components.panels.bottomrow.BottomRowPanel;
import nl.topicus.cobra.web.components.shortcut.CobraKeyAction;
import nl.topicus.eduarte.app.EduArteContext;
import nl.topicus.eduarte.core.principals.groep.GroepenMijn;
import nl.topicus.eduarte.entities.groep.GroepDocent;
import nl.topicus.eduarte.entities.groep.GroepMentor;
import nl.topicus.eduarte.web.components.panels.bottomrow.ModuleEditPageButton;
import nl.topicus.eduarte.web.pages.IModuleEditPage;
import nl.topicus.eduarte.web.pages.SecurePage;
import nl.topicus.eduarte.zoekfilters.GroepZoekFilter;
import org.apache.wicket.Page;
@PageInfo(title = "Mijn groepen", menu = "Groep")
@InPrincipal(GroepenMijn.class)
public class MijnGroepenPage extends GroepZoekenPage
{
public MijnGroepenPage()
{
this(createFilter());
}
private static GroepZoekFilter createFilter()
{
GroepZoekFilter filter = GroepZoekenPage.getDefaultFilter();
filter.setMentorOrDocent(EduArteContext.get().getMedewerker());
filter.setMentorOrDocentRequired(true);
return filter;
}
public MijnGroepenPage(GroepZoekFilter filter)
{
super(filter);
}
@Override
protected void fillBottomRow(BottomRowPanel panel)
{
super.fillBottomRow(panel);
panel.addButton(new ModuleEditPageButton<GroepDocent>(panel, "Als docent (ont)koppelen",
CobraKeyAction.GEEN, GroepDocent.class, this)
{
private static final long serialVersionUID = 1L;
@Override
protected Page createTargetPage(
Class< ? extends IModuleEditPage<GroepDocent>> pageClass, SecurePage returnPage)
{
return (Page) ReflectionUtil.invokeConstructor(pageClass);
}
});
panel.addButton(new ModuleEditPageButton<GroepMentor>(panel, "Als mentor (ont)koppelen",
CobraKeyAction.GEEN, GroepMentor.class, this)
{
private static final long serialVersionUID = 1L;
@Override
protected Page createTargetPage(
Class< ? extends IModuleEditPage<GroepMentor>> pageClass, SecurePage returnPage)
{
return (Page) ReflectionUtil.invokeConstructor(pageClass);
}
});
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/core/src/main/java/nl/topicus/eduarte/web/pages/groep/MijnGroepenPage.java |
3,003 | /**
* Created by johan on 15-9-2016.
*/
public class h1_3_MijnEersteJavaKlasse {
public static void main(String[] args) {
System.out.println("Dit is mijn eerste java klasse!");
}
}
| johanvan75/mijneerstejavaklasse | h1_3_MijnEersteJavaKlasse.java |
3,004 | //jDownloader - Downloadmanager
//Copyright (C) 2012 JD-Team [email protected]
//
//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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "mijnbestand.nl" }, urls = { "http://(www\\.)?mijnbestand\\.nl/(B|b)estand\\-[A-Z0-9]+" }, flags = { 0 })
public class MijnBestandNl extends PluginForHost {
public MijnBestandNl(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://www.mijnbestand.nl/AV";
}
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(link.getDownloadURL());
if (br.getURL().equals("http://www.mijnbestand.nl/")) throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
String filename = br.getRegex("<title>([^<>\"]*?) downloaden</title>").getMatch(0);
if (filename == null) filename = br.getRegex("class=\"share_title\">([^<>\"]*?) delen via E\\-mail</div>").getMatch(0);
if (filename == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
link.setName(Encoding.htmlDecode(filename.trim()));
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
br.postPage(br.getURL(), "download=start");
String dllink = br.getRegex("\"((B|b)estand\\-[A-Z0-9]+\\&download=[^<>\"/]*?)\"").getMatch(0);
if (dllink == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
dllink = "http://www.mijnbestand.nl/" + dllink;
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | svn2github/jdownloader | src/jd/plugins/hoster/MijnBestandNl.java |
3,005 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package app.lawnchair.lawnicons;
public final class R {
public static final class array {
public static final int grayscale_calendar_icons=0x7f050000;
public static final int grayscale_clock_icons=0x7f050001;
}
public static final class attr {
}
public static final class color {
public static final int black=0x7f060005;
public static final int purple_200=0x7f060000;
public static final int purple_500=0x7f060001;
public static final int purple_700=0x7f060002;
public static final int teal_200=0x7f060003;
public static final int teal_700=0x7f060004;
public static final int white=0x7f060006;
}
public static final class dimen {
public static final int theme_icon_size=0x7f070000;
}
public static final class drawable {
public static final int aide=0x7f020000;
public static final int amazon_music=0x7f020001;
public static final int amazon_primevideo=0x7f020002;
public static final int amazon_shopping=0x7f020003;
public static final int android=0x7f020004;
public static final int apkeditor=0x7f020005;
public static final int apkmirror=0x7f020006;
public static final int app_icon=0x7f020007;
public static final int apple_music=0x7f020008;
public static final int aurora_store=0x7f020009;
public static final int austale=0x7f02000a;
public static final int bgbrowser=0x7f02000b;
public static final int bgram=0x7f02000c;
public static final int binance=0x7f02000d;
public static final int bitwarden=0x7f02000e;
public static final int boost=0x7f02000f;
public static final int brave_browser=0x7f020010;
public static final int bromite=0x7f020011;
public static final int browser=0x7f020012;
public static final int calculator=0x7f020013;
public static final int camera=0x7f020014;
public static final int catogram=0x7f020015;
public static final int chrome_beta=0x7f020016;
public static final int chrome_canary=0x7f020017;
public static final int chrome_dev=0x7f020018;
public static final int citymapper=0x7f020019;
public static final int clock=0x7f02001a;
public static final int coinsph=0x7f02001b;
public static final int dashlane=0x7f02001c;
public static final int dialer=0x7f02001d;
public static final int discord=0x7f02001e;
public static final int drivedroid=0x7f02001f;
public static final int ebay=0x7f020020;
public static final int ebay_kleinanzeigen=0x7f020021;
public static final int element=0x7f020022;
public static final int facebook=0x7f020023;
public static final int fdroid=0x7f020024;
public static final int files=0x7f020025;
public static final int firefox=0x7f020026;
public static final int firefox_beta=0x7f020027;
public static final int gallery=0x7f020028;
public static final int gallery_go=0x7f020029;
public static final int gcash=0x7f02002a;
public static final int genshinimpact=0x7f02002b;
public static final int gfxtool=0x7f02002c;
public static final int github=0x7f02002d;
public static final int globeone=0x7f02002e;
public static final int gmail=0x7f02002f;
public static final int google=0x7f020030;
public static final int icstudio=0x7f020031;
public static final int ime=0x7f020032;
public static final int ininal=0x7f020033;
public static final int instagram=0x7f020034;
public static final int instapaper=0x7f020035;
public static final int ios13iconpack=0x7f020036;
public static final int juicessh=0x7f020037;
public static final int magisk=0x7f020038;
public static final int maps=0x7f020039;
public static final int messages=0x7f02003a;
public static final int messenger=0x7f02003b;
public static final int mgit=0x7f02003c;
public static final int microsoft_authenticator=0x7f02003d;
public static final int microsoft_edge=0x7f02003e;
public static final int microsoft_outlook=0x7f02003f;
public static final int microsoft_todo=0x7f020040;
public static final int minecraft=0x7f020041;
public static final int mixplorer=0x7f020042;
public static final int music=0x7f020043;
public static final int musicolet=0x7f020044;
public static final int mx_player=0x7f020045;
public static final int myjio=0x7f020046;
public static final int nekogram_x=0x7f020047;
public static final int netflix=0x7f020048;
public static final int newpipe=0x7f020049;
public static final int opera_browser=0x7f02004a;
public static final int opera_gx=0x7f02004b;
public static final int oto_music=0x7f02004c;
public static final int owlgram=0x7f02004d;
public static final int phone=0x7f02004e;
public static final int pinterest=0x7f02004f;
public static final int pixellab=0x7f020050;
public static final int plus_messenger=0x7f020051;
public static final int pocket_casts=0x7f020052;
public static final int poweramp=0x7f020053;
public static final int progressbar95=0x7f020054;
public static final int protonmail=0x7f020055;
public static final int pubg=0x7f020056;
public static final int reddit=0x7f020057;
public static final int roblox=0x7f020058;
public static final int rootactivitylauncher=0x7f020059;
public static final int sai=0x7f02005a;
public static final int sbrowser=0x7f02005b;
public static final int sbrowser_beta=0x7f02005c;
public static final int shazam=0x7f02005d;
public static final int shopee=0x7f02005e;
public static final int signal=0x7f02005f;
public static final int simple_gallery_pro=0x7f020060;
public static final int simplenote=0x7f020061;
public static final int sketchware=0x7f020062;
public static final int skype=0x7f020063;
public static final int sms_organizer=0x7f020064;
public static final int snapchat=0x7f020065;
public static final int snapseed=0x7f020066;
public static final int solid_explorer=0x7f020067;
public static final int sony_headphonesconnect=0x7f020068;
public static final int soundcloud=0x7f020069;
public static final int spark_email=0x7f02006a;
public static final int speedtest_by_ookla=0x7f02006b;
public static final int spotify=0x7f02006c;
public static final int stellio=0x7f02006d;
public static final int strava=0x7f02006e;
public static final int substratum_lite=0x7f02006f;
public static final int sweech=0x7f020070;
public static final int swift_backup=0x7f020071;
public static final int sync=0x7f020072;
public static final int tapatalk_pro=0x7f020073;
public static final int taptap=0x7f020074;
public static final int telegram=0x7f020075;
public static final int telegram_x=0x7f020076;
public static final int termux=0x7f020077;
public static final int theathletic=0x7f020078;
public static final int themed_icon_1111dns=0x7f020079;
public static final int themed_icon_1gallery=0x7f02007a;
public static final int themed_icon_365_scores=0x7f02007b;
public static final int themed_icon_3dmark=0x7f02007c;
public static final int themed_icon_8ball_pool=0x7f02007d;
public static final int themed_icon_accubattery=0x7f02007e;
public static final int themed_icon_adaway=0x7f02007f;
public static final int themed_icon_addtext=0x7f020080;
public static final int themed_icon_adm=0x7f020081;
public static final int themed_icon_adobe_acrobat=0x7f020082;
public static final int themed_icon_adobe_scan=0x7f020083;
public static final int themed_icon_aegis=0x7f020084;
public static final int themed_icon_agc=0x7f020085;
public static final int themed_icon_aida64=0x7f020086;
public static final int themed_icon_aimp=0x7f020087;
public static final int themed_icon_alarmy=0x7f020088;
public static final int themed_icon_aliexpress=0x7f020089;
public static final int themed_icon_aliucord_installer=0x7f02008a;
public static final int themed_icon_alphabackup=0x7f02008b;
public static final int themed_icon_amazon_alexa=0x7f02008c;
public static final int themed_icon_amazon_kindle=0x7f02008d;
public static final int themed_icon_amazon_music=0x7f02008e;
public static final int themed_icon_amazon_photos=0x7f02008f;
public static final int themed_icon_amazon_seller=0x7f020090;
public static final int themed_icon_amazon_shopping=0x7f020091;
public static final int themed_icon_ana_vodafone=0x7f020092;
public static final int themed_icon_android=0x7f020093;
public static final int themed_icon_android_auto=0x7f020094;
public static final int themed_icon_androidbetafeedback=0x7f020095;
public static final int themed_icon_antutu=0x7f020096;
public static final int themed_icon_any=0x7f020097;
public static final int themed_icon_anythingtopip=0x7f020098;
public static final int themed_icon_aov=0x7f020099;
public static final int themed_icon_apkmirror=0x7f02009a;
public static final int themed_icon_apktoolm=0x7f02009b;
public static final int themed_icon_apni_kaksha=0x7f02009c;
public static final int themed_icon_apple_music=0x7f02009d;
public static final int themed_icon_aruba=0x7f02009e;
public static final int themed_icon_asphalt_9=0x7f02009f;
public static final int themed_icon_asus_gallery=0x7f0200a0;
public static final int themed_icon_athan=0x7f0200a1;
public static final int themed_icon_attapoll=0x7f0200a2;
public static final int themed_icon_audiomack=0x7f0200a3;
public static final int themed_icon_aurora_store=0x7f0200a4;
public static final int themed_icon_authenticator=0x7f0200a5;
public static final int themed_icon_authy=0x7f0200a6;
public static final int themed_icon_autotagger=0x7f0200a7;
public static final int themed_icon_auxio=0x7f0200a8;
public static final int themed_icon_aviata=0x7f0200a9;
public static final int themed_icon_avito=0x7f0200aa;
public static final int themed_icon_axisnet=0x7f0200ab;
public static final int themed_icon_azcecll=0x7f0200ac;
public static final int themed_icon_backdrops=0x7f0200ad;
public static final int themed_icon_bandlab=0x7f0200ae;
public static final int themed_icon_battery_guru=0x7f0200af;
public static final int themed_icon_beeline=0x7f0200b0;
public static final int themed_icon_betamaniac=0x7f0200b1;
public static final int themed_icon_betternet=0x7f0200b2;
public static final int themed_icon_bgram=0x7f0200b3;
public static final int themed_icon_bhim=0x7f0200b4;
public static final int themed_icon_bima_plus=0x7f0200b5;
public static final int themed_icon_binance=0x7f0200b6;
public static final int themed_icon_bing=0x7f0200b7;
public static final int themed_icon_bir=0x7f0200b8;
public static final int themed_icon_bird=0x7f0200b9;
public static final int themed_icon_bitwarden=0x7f0200ba;
public static final int themed_icon_blackboard=0x7f0200bb;
public static final int themed_icon_blackhole=0x7f0200bc;
public static final int themed_icon_bolt=0x7f0200bd;
public static final int themed_icon_booking=0x7f0200be;
public static final int themed_icon_boom=0x7f0200bf;
public static final int themed_icon_boost=0x7f0200c0;
public static final int themed_icon_bradesco=0x7f0200c1;
public static final int themed_icon_brave=0x7f0200c2;
public static final int themed_icon_brawl_stars=0x7f0200c3;
public static final int themed_icon_brimo=0x7f0200c4;
public static final int themed_icon_bromite=0x7f0200c5;
public static final int themed_icon_browser=0x7f0200c6;
public static final int themed_icon_bsi_mobile=0x7f0200c7;
public static final int themed_icon_btmouse=0x7f0200c8;
public static final int themed_icon_bubbleunp=0x7f0200c9;
public static final int themed_icon_by_u=0x7f0200ca;
public static final int themed_icon_c6_bank=0x7f0200cb;
public static final int themed_icon_caixa=0x7f0200cc;
public static final int themed_icon_calculator=0x7f0200cd;
public static final int themed_icon_calendar_1=0x7f0200ce;
public static final int themed_icon_calendar_10=0x7f0200cf;
public static final int themed_icon_calendar_11=0x7f0200d0;
public static final int themed_icon_calendar_12=0x7f0200d1;
public static final int themed_icon_calendar_13=0x7f0200d2;
public static final int themed_icon_calendar_14=0x7f0200d3;
public static final int themed_icon_calendar_15=0x7f0200d4;
public static final int themed_icon_calendar_16=0x7f0200d5;
public static final int themed_icon_calendar_17=0x7f0200d6;
public static final int themed_icon_calendar_18=0x7f0200d7;
public static final int themed_icon_calendar_19=0x7f0200d8;
public static final int themed_icon_calendar_2=0x7f0200d9;
public static final int themed_icon_calendar_20=0x7f0200da;
public static final int themed_icon_calendar_21=0x7f0200db;
public static final int themed_icon_calendar_22=0x7f0200dc;
public static final int themed_icon_calendar_23=0x7f0200dd;
public static final int themed_icon_calendar_24=0x7f0200de;
public static final int themed_icon_calendar_25=0x7f0200df;
public static final int themed_icon_calendar_26=0x7f0200e0;
public static final int themed_icon_calendar_27=0x7f0200e1;
public static final int themed_icon_calendar_28=0x7f0200e2;
public static final int themed_icon_calendar_29=0x7f0200e3;
public static final int themed_icon_calendar_3=0x7f0200e4;
public static final int themed_icon_calendar_30=0x7f0200e5;
public static final int themed_icon_calendar_31=0x7f0200e6;
public static final int themed_icon_calendar_4=0x7f0200e7;
public static final int themed_icon_calendar_5=0x7f0200e8;
public static final int themed_icon_calendar_6=0x7f0200e9;
public static final int themed_icon_calendar_7=0x7f0200ea;
public static final int themed_icon_calendar_8=0x7f0200eb;
public static final int themed_icon_calendar_9=0x7f0200ec;
public static final int themed_icon_camera=0x7f0200ed;
public static final int themed_icon_camera_go=0x7f0200ee;
public static final int themed_icon_camscanner=0x7f0200ef;
public static final int themed_icon_canvas=0x7f0200f0;
public static final int themed_icon_cartogram=0x7f0200f1;
public static final int themed_icon_catogram=0x7f0200f2;
public static final int themed_icon_cdek=0x7f0200f3;
public static final int themed_icon_chat=0x7f0200f4;
public static final int themed_icon_chess=0x7f0200f5;
public static final int themed_icon_chrome=0x7f0200f6;
public static final int themed_icon_chrome_beta=0x7f0200f7;
public static final int themed_icon_chrome_canary=0x7f0200f8;
public static final int themed_icon_chrome_dev=0x7f0200f9;
public static final int themed_icon_chromebeta=0x7f0200fa;
public static final int themed_icon_citymapper=0x7f0200fb;
public static final int themed_icon_clash_mini=0x7f0200fc;
public static final int themed_icon_clash_of_clans=0x7f0200fd;
public static final int themed_icon_clash_quest=0x7f0200fe;
public static final int themed_icon_clash_royale=0x7f0200ff;
public static final int themed_icon_classicpowermenu=0x7f020100;
public static final int themed_icon_clock=0x7f020101;
public static final int themed_icon_coinsph=0x7f020102;
public static final int themed_icon_coinvero=0x7f020103;
public static final int themed_icon_companion=0x7f020104;
public static final int themed_icon_contacts=0x7f020105;
public static final int themed_icon_cred=0x7f020106;
public static final int themed_icon_crypto=0x7f020107;
public static final int themed_icon_cvv=0x7f020108;
public static final int themed_icon_cx_file_manager=0x7f020109;
public static final int themed_icon_cyberghost=0x7f02010a;
public static final int themed_icon_daraz=0x7f02010b;
public static final int themed_icon_darq=0x7f02010c;
public static final int themed_icon_dashlane=0x7f02010d;
public static final int themed_icon_deck_shop=0x7f02010e;
public static final int themed_icon_deezer=0x7f02010f;
public static final int themed_icon_delivery_club=0x7f020110;
public static final int themed_icon_deviantart=0x7f020111;
public static final int themed_icon_deviceinfo=0x7f020112;
public static final int themed_icon_dialer=0x7f020113;
public static final int themed_icon_digital_wellbeing=0x7f020114;
public static final int themed_icon_diia=0x7f020115;
public static final int themed_icon_discord=0x7f020116;
public static final int themed_icon_discord_themer=0x7f020117;
public static final int themed_icon_disney_plus=0x7f020118;
public static final int themed_icon_docs_editors=0x7f020119;
public static final int themed_icon_documents=0x7f02011a;
public static final int themed_icon_doodle=0x7f02011b;
public static final int themed_icon_drive=0x7f02011c;
public static final int themed_icon_drivedroid=0x7f02011d;
public static final int themed_icon_droidcam=0x7f02011e;
public static final int themed_icon_droidify=0x7f02011f;
public static final int themed_icon_drom=0x7f020120;
public static final int themed_icon_dublgis=0x7f020121;
public static final int themed_icon_duckduckgo=0x7f020122;
public static final int themed_icon_duo=0x7f020123;
public static final int themed_icon_duolingo=0x7f020124;
public static final int themed_icon_duomobile=0x7f020125;
public static final int themed_icon_ebay=0x7f020126;
public static final int themed_icon_ebay_kleinanzeigen=0x7f020127;
public static final int themed_icon_egov=0x7f020128;
public static final int themed_icon_element=0x7f020129;
public static final int themed_icon_es_explorer=0x7f02012a;
public static final int themed_icon_espn=0x7f02012b;
public static final int themed_icon_evernote=0x7f02012c;
public static final int themed_icon_express_vpn=0x7f02012d;
public static final int themed_icon_exteragram=0x7f02012e;
public static final int themed_icon_facebook=0x7f02012f;
public static final int themed_icon_fairemail=0x7f020130;
public static final int themed_icon_family_link=0x7f020131;
public static final int themed_icon_family_link_ct=0x7f020132;
public static final int themed_icon_fasthub=0x7f020133;
public static final int themed_icon_fdroid=0x7f020134;
public static final int themed_icon_fgames_radar=0x7f020135;
public static final int themed_icon_file_manager=0x7f020136;
public static final int themed_icon_files=0x7f020137;
public static final int themed_icon_filmic_pro=0x7f020138;
public static final int themed_icon_find_my_device=0x7f020139;
public static final int themed_icon_firefox=0x7f02013a;
public static final int themed_icon_firefox_beta=0x7f02013b;
public static final int themed_icon_fitbit=0x7f02013c;
public static final int themed_icon_fiverr=0x7f02013d;
public static final int themed_icon_flashscore=0x7f02013e;
public static final int themed_icon_flipkart=0x7f02013f;
public static final int themed_icon_fm_radio=0x7f020140;
public static final int themed_icon_fng=0x7f020141;
public static final int themed_icon_focus_todo=0x7f020142;
public static final int themed_icon_fontviewer=0x7f020143;
public static final int themed_icon_foodpanda=0x7f020144;
public static final int themed_icon_four_pda=0x7f020145;
public static final int themed_icon_francokernelmanager=0x7f020146;
public static final int themed_icon_freefire=0x7f020147;
public static final int themed_icon_freefire_max=0x7f020148;
public static final int themed_icon_freezer=0x7f020149;
public static final int themed_icon_ftx=0x7f02014a;
public static final int themed_icon_fusewalls=0x7f02014b;
public static final int themed_icon_fx=0x7f02014c;
public static final int themed_icon_g_translate=0x7f02014d;
public static final int themed_icon_gallery=0x7f02014e;
public static final int themed_icon_gallery_go=0x7f02014f;
public static final int themed_icon_gapo=0x7f020150;
public static final int themed_icon_garanti=0x7f020151;
public static final int themed_icon_gboard=0x7f020152;
public static final int themed_icon_gcash=0x7f020153;
public static final int themed_icon_genius=0x7f020154;
public static final int themed_icon_genshin_impact=0x7f020155;
public static final int themed_icon_getir=0x7f020156;
public static final int themed_icon_gfit_health=0x7f020157;
public static final int themed_icon_giga_life=0x7f020158;
public static final int themed_icon_github=0x7f020159;
public static final int themed_icon_globeone=0x7f02015a;
public static final int themed_icon_glovo=0x7f02015b;
public static final int themed_icon_gmail=0x7f02015c;
public static final int themed_icon_google=0x7f02015d;
public static final int themed_icon_google_assistant=0x7f02015e;
public static final int themed_icon_google_fi=0x7f02015f;
public static final int themed_icon_google_one=0x7f020160;
public static final int themed_icon_google_opinion=0x7f020161;
public static final int themed_icon_google_tv=0x7f020162;
public static final int themed_icon_googleclassroom=0x7f020163;
public static final int themed_icon_gosuslugi=0x7f020164;
public static final int themed_icon_gpay=0x7f020165;
public static final int themed_icon_grindr=0x7f020166;
public static final int themed_icon_guitar_tuna=0x7f020167;
public static final int themed_icon_halkbank=0x7f020168;
public static final int themed_icon_hangouts=0x7f020169;
public static final int themed_icon_hbo_max=0x7f02016a;
public static final int themed_icon_hdfc_bank=0x7f02016b;
public static final int themed_icon_hearo=0x7f02016c;
public static final int themed_icon_hearthstone=0x7f02016d;
public static final int themed_icon_hh=0x7f02016e;
public static final int themed_icon_home=0x7f02016f;
public static final int themed_icon_hotstar=0x7f020170;
public static final int themed_icon_ibis_paint=0x7f020171;
public static final int themed_icon_iceraven=0x7f020172;
public static final int themed_icon_ifood=0x7f020173;
public static final int themed_icon_iherb=0x7f020174;
public static final int themed_icon_ime=0x7f020175;
public static final int themed_icon_indriver=0x7f020176;
public static final int themed_icon_infinity=0x7f020177;
public static final int themed_icon_inshot=0x7f020178;
public static final int themed_icon_instagram=0x7f020179;
public static final int themed_icon_instapaper=0x7f02017a;
public static final int themed_icon_inter=0x7f02017b;
public static final int themed_icon_intersvyaz=0x7f02017c;
public static final int themed_icon_ivi=0x7f02017d;
public static final int themed_icon_ivy_wallet=0x7f02017e;
public static final int themed_icon_j2meloader=0x7f02017f;
public static final int themed_icon_juicessh=0x7f020180;
public static final int themed_icon_k9_mail=0x7f020181;
public static final int themed_icon_kakaotalk=0x7f020182;
public static final int themed_icon_kapk=0x7f020183;
public static final int themed_icon_karwei=0x7f020184;
public static final int themed_icon_kaspi_kz=0x7f020185;
public static final int themed_icon_keep=0x7f020186;
public static final int themed_icon_khan_academy=0x7f020187;
public static final int themed_icon_kinemaster=0x7f020188;
public static final int themed_icon_kinopoisk=0x7f020189;
public static final int themed_icon_kiwi_browser=0x7f02018a;
public static final int themed_icon_klck=0x7f02018b;
public static final int themed_icon_klwp=0x7f02018c;
public static final int themed_icon_knigi=0x7f02018d;
public static final int themed_icon_kolesa=0x7f02018e;
public static final int themed_icon_komoot=0x7f02018f;
public static final int themed_icon_krisha=0x7f020190;
public static final int themed_icon_kucoin=0x7f020191;
public static final int themed_icon_kwai=0x7f020192;
public static final int themed_icon_kwgt=0x7f020193;
public static final int themed_icon_lamoda=0x7f020194;
public static final int themed_icon_lastfm=0x7f020195;
public static final int themed_icon_lawnchair=0x7f020196;
public static final int themed_icon_lazada=0x7f020197;
public static final int themed_icon_lens=0x7f020198;
public static final int themed_icon_lewdfi=0x7f020199;
public static final int themed_icon_libchecker=0x7f02019a;
public static final int themed_icon_life_is_strange=0x7f02019b;
public static final int themed_icon_lightroom=0x7f02019c;
public static final int themed_icon_line=0x7f02019d;
public static final int themed_icon_linkedin=0x7f02019e;
public static final int themed_icon_lithium=0x7f02019f;
public static final int themed_icon_litres_audio=0x7f0201a0;
public static final int themed_icon_livin_by_mandiri=0x7f0201a1;
public static final int themed_icon_lsposed=0x7f0201a2;
public static final int themed_icon_luckypatcher=0x7f0201a3;
public static final int themed_icon_lyb_kernel_manager=0x7f0201a4;
public static final int themed_icon_magisk=0x7f0201a5;
public static final int themed_icon_mail_ru=0x7f0201a6;
public static final int themed_icon_mail_ru_cloud=0x7f0201a7;
public static final int themed_icon_mal=0x7f0201a8;
public static final int themed_icon_maps=0x7f0201a9;
public static final int themed_icon_marindeck=0x7f0201aa;
public static final int themed_icon_matlog=0x7f0201ab;
public static final int themed_icon_maxim=0x7f0201ac;
public static final int themed_icon_mbank=0x7f0201ad;
public static final int themed_icon_mc_four=0x7f0201ae;
public static final int themed_icon_mdgram=0x7f0201af;
public static final int themed_icon_meet=0x7f0201b0;
public static final int themed_icon_mega=0x7f0201b1;
public static final int themed_icon_megafon=0x7f0201b2;
public static final int themed_icon_mercado_libre=0x7f0201b3;
public static final int themed_icon_messages=0x7f0201b4;
public static final int themed_icon_messenger=0x7f0201b5;
public static final int themed_icon_microsoft_authenticator=0x7f0201b6;
public static final int themed_icon_microsoft_azure=0x7f0201b7;
public static final int themed_icon_microsoft_edge=0x7f0201b8;
public static final int themed_icon_microsoft_excel=0x7f0201b9;
public static final int themed_icon_microsoft_launcher=0x7f0201ba;
public static final int themed_icon_microsoft_lens=0x7f0201bb;
public static final int themed_icon_microsoft_math=0x7f0201bc;
public static final int themed_icon_microsoft_office=0x7f0201bd;
public static final int themed_icon_microsoft_onedrive=0x7f0201be;
public static final int themed_icon_microsoft_onenote=0x7f0201bf;
public static final int themed_icon_microsoft_outlook=0x7f0201c0;
public static final int themed_icon_microsoft_planner=0x7f0201c1;
public static final int themed_icon_microsoft_powerpoint=0x7f0201c2;
public static final int themed_icon_microsoft_teams=0x7f0201c3;
public static final int themed_icon_microsoft_todo=0x7f0201c4;
public static final int themed_icon_microsoft_word=0x7f0201c5;
public static final int themed_icon_mifit=0x7f0201c6;
public static final int themed_icon_mijn_hr=0x7f0201c7;
public static final int themed_icon_minecraft=0x7f0201c8;
public static final int themed_icon_mini_metro=0x7f0201c9;
public static final int themed_icon_mixplorer=0x7f0201ca;
public static final int themed_icon_moey=0x7f0201cb;
public static final int themed_icon_monect=0x7f0201cc;
public static final int themed_icon_money_lover=0x7f0201cd;
public static final int themed_icon_mtmanager=0x7f0201ce;
public static final int themed_icon_mts=0x7f0201cf;
public static final int themed_icon_musicolet=0x7f0201d0;
public static final int themed_icon_musicspeedchanger=0x7f0201d1;
public static final int themed_icon_must=0x7f0201d2;
public static final int themed_icon_mx_player=0x7f0201d3;
public static final int themed_icon_myairtel=0x7f0201d4;
public static final int themed_icon_mybook=0x7f0201d5;
public static final int themed_icon_myjio=0x7f0201d6;
public static final int themed_icon_naptime=0x7f0201d7;
public static final int themed_icon_nekogram=0x7f0201d8;
public static final int themed_icon_netflix=0x7f0201d9;
public static final int themed_icon_newpipe=0x7f0201da;
public static final int themed_icon_news=0x7f0201db;
public static final int themed_icon_next=0x7f0201dc;
public static final int themed_icon_nfsmw=0x7f0201dd;
public static final int themed_icon_notebook=0x7f0201de;
public static final int themed_icon_notify_for_miband=0x7f0201df;
public static final int themed_icon_nova=0x7f0201e0;
public static final int themed_icon_nubank=0x7f0201e1;
public static final int themed_icon_nyx=0x7f0201e2;
public static final int themed_icon_obsidian=0x7f0201e3;
public static final int themed_icon_olx=0x7f0201e4;
public static final int themed_icon_one_dm_plus=0x7f0201e5;
public static final int themed_icon_opera=0x7f0201e6;
public static final int themed_icon_opera_beta=0x7f0201e7;
public static final int themed_icon_opera_gx=0x7f0201e8;
public static final int themed_icon_opera_mini=0x7f0201e9;
public static final int themed_icon_opera_mini_beta=0x7f0201ea;
public static final int themed_icon_osmand=0x7f0201eb;
public static final int themed_icon_osmand_plus=0x7f0201ec;
public static final int themed_icon_oto_music=0x7f0201ed;
public static final int themed_icon_otraku=0x7f0201ee;
public static final int themed_icon_overdrop=0x7f0201ef;
public static final int themed_icon_ozon=0x7f0201f0;
public static final int themed_icon_package_names=0x7f0201f1;
public static final int themed_icon_pandavpn=0x7f0201f2;
public static final int themed_icon_patreon=0x7f0201f3;
public static final int themed_icon_paypal=0x7f0201f4;
public static final int themed_icon_paypal_business=0x7f0201f5;
public static final int themed_icon_paytm=0x7f0201f6;
public static final int themed_icon_phonepe=0x7f0201f7;
public static final int themed_icon_photomath=0x7f0201f8;
public static final int themed_icon_photon_camera=0x7f0201f9;
public static final int themed_icon_photos=0x7f0201fa;
public static final int themed_icon_picpay=0x7f0201fb;
public static final int themed_icon_picsart=0x7f0201fc;
public static final int themed_icon_pikabu=0x7f0201fd;
public static final int themed_icon_pillars=0x7f0201fe;
public static final int themed_icon_pinnit=0x7f0201ff;
public static final int themed_icon_pinterest=0x7f020200;
public static final int themed_icon_pixeltips=0x7f020201;
public static final int themed_icon_pixiv=0x7f020202;
public static final int themed_icon_plato=0x7f020203;
public static final int themed_icon_play_books=0x7f020204;
public static final int themed_icon_play_games=0x7f020205;
public static final int themed_icon_play_services=0x7f020206;
public static final int themed_icon_play_store=0x7f020207;
public static final int themed_icon_pluma=0x7f020208;
public static final int themed_icon_plus_messenger=0x7f020209;
public static final int themed_icon_pocket_casts=0x7f02020a;
public static final int themed_icon_podcasts=0x7f02020b;
public static final int themed_icon_pomodo=0x7f02020c;
public static final int themed_icon_poweramp=0x7f02020d;
public static final int themed_icon_prime_video=0x7f02020e;
public static final int themed_icon_progressbar95=0x7f02020f;
public static final int themed_icon_protonmail=0x7f020210;
public static final int themed_icon_ps=0x7f020211;
public static final int themed_icon_ps_camera=0x7f020212;
public static final int themed_icon_ps_express=0x7f020213;
public static final int themed_icon_pulse_music=0x7f020214;
public static final int themed_icon_pushbullet=0x7f020215;
public static final int themed_icon_qiwi=0x7f020216;
public static final int themed_icon_qr_scan=0x7f020217;
public static final int themed_icon_quick_edit=0x7f020218;
public static final int themed_icon_quickpic=0x7f020219;
public static final int themed_icon_quickstep=0x7f02021a;
public static final int themed_icon_quizlet=0x7f02021b;
public static final int themed_icon_quora=0x7f02021c;
public static final int themed_icon_rabobank=0x7f02021d;
public static final int themed_icon_rar=0x7f02021e;
public static final int themed_icon_rave=0x7f02021f;
public static final int themed_icon_rboard=0x7f020220;
public static final int themed_icon_read_chan=0x7f020221;
public static final int themed_icon_readera=0x7f020222;
public static final int themed_icon_readwise=0x7f020223;
public static final int themed_icon_realme_link=0x7f020224;
public static final int themed_icon_recorder=0x7f020225;
public static final int themed_icon_reddit=0x7f020226;
public static final int themed_icon_redlime=0x7f020227;
public static final int themed_icon_redtulum=0x7f020228;
public static final int themed_icon_relay=0x7f020229;
public static final int themed_icon_remotedesktop=0x7f02022a;
public static final int themed_icon_retro_music=0x7f02022b;
public static final int themed_icon_revolut=0x7f02022c;
public static final int themed_icon_rl_sideswipe=0x7f02022d;
public static final int themed_icon_roblox=0x7f02022e;
public static final int themed_icon_rootactivitylauncher=0x7f02022f;
public static final int themed_icon_ru_post=0x7f020230;
public static final int themed_icon_safety=0x7f020231;
public static final int themed_icon_samsung_browser=0x7f020232;
public static final int themed_icon_samsung_browser_beta=0x7f020233;
public static final int themed_icon_santander=0x7f020234;
public static final int themed_icon_santander_way=0x7f020235;
public static final int themed_icon_sberbank=0x7f020236;
public static final int themed_icon_school_planner=0x7f020237;
public static final int themed_icon_sdmaid=0x7f020238;
public static final int themed_icon_sdmaidpro=0x7f020239;
public static final int themed_icon_settings=0x7f02023a;
public static final int themed_icon_shazam=0x7f02023b;
public static final int themed_icon_sheets=0x7f02023c;
public static final int themed_icon_shopee=0x7f02023d;
public static final int themed_icon_shopsy=0x7f02023e;
public static final int themed_icon_shortcutmaker=0x7f02023f;
public static final int themed_icon_signal=0x7f020240;
public static final int themed_icon_simple_gallery_pro=0x7f020241;
public static final int themed_icon_simplenote=0x7f020242;
public static final int themed_icon_simplereboot=0x7f020243;
public static final int themed_icon_sked=0x7f020244;
public static final int themed_icon_sky_cotl=0x7f020245;
public static final int themed_icon_skype=0x7f020246;
public static final int themed_icon_slack=0x7f020247;
public static final int themed_icon_sleep_as_android=0x7f020248;
public static final int themed_icon_slides=0x7f020249;
public static final int themed_icon_smart_audiobook_player=0x7f02024a;
public static final int themed_icon_smartbank=0x7f02024b;
public static final int themed_icon_smartpackkernelmanager=0x7f02024c;
public static final int themed_icon_smarty=0x7f02024d;
public static final int themed_icon_sms_organizer=0x7f02024e;
public static final int themed_icon_snapchat=0x7f02024f;
public static final int themed_icon_snapseed=0x7f020250;
public static final int themed_icon_sofa_score=0x7f020251;
public static final int themed_icon_solid_explorer=0x7f020252;
public static final int themed_icon_solid_soundamplifier=0x7f020253;
public static final int themed_icon_sony_headphonesconnect=0x7f020254;
public static final int themed_icon_sony_music=0x7f020255;
public static final int themed_icon_soul_knight=0x7f020256;
public static final int themed_icon_soundcloud=0x7f020257;
public static final int themed_icon_sova_v_re=0x7f020258;
public static final int themed_icon_spark_email=0x7f020259;
public static final int themed_icon_speedtest=0x7f02025a;
public static final int themed_icon_splitapk=0x7f02025b;
public static final int themed_icon_spotify=0x7f02025c;
public static final int themed_icon_starwalk=0x7f02025d;
public static final int themed_icon_steam=0x7f02025e;
public static final int themed_icon_steam_chat=0x7f02025f;
public static final int themed_icon_stellio=0x7f020260;
public static final int themed_icon_stepik=0x7f020261;
public static final int themed_icon_stickerly=0x7f020262;
public static final int themed_icon_storageisolation=0x7f020263;
public static final int themed_icon_strava=0x7f020264;
public static final int themed_icon_styx_browser=0x7f020265;
public static final int themed_icon_substratum=0x7f020266;
public static final int themed_icon_swapper=0x7f020267;
public static final int themed_icon_sweech=0x7f020268;
public static final int themed_icon_swift_backup=0x7f020269;
public static final int themed_icon_sync=0x7f02026a;
public static final int themed_icon_syncthing=0x7f02026b;
public static final int themed_icon_systemui=0x7f02026c;
public static final int themed_icon_sysuitunernoads=0x7f02026d;
public static final int themed_icon_tachiyomi=0x7f02026e;
public static final int themed_icon_tapatalk_pro=0x7f02026f;
public static final int themed_icon_tasks=0x7f020270;
public static final int themed_icon_ted=0x7f020271;
public static final int themed_icon_tele2=0x7f020272;
public static final int themed_icon_telegram=0x7f020273;
public static final int themed_icon_telegram_x=0x7f020274;
public static final int themed_icon_telegraph=0x7f020275;
public static final int themed_icon_termux=0x7f020276;
public static final int themed_icon_theathletic=0x7f020277;
public static final int themed_icon_thenks=0x7f020278;
public static final int themed_icon_tidal=0x7f020279;
public static final int themed_icon_tiktok=0x7f02027a;
public static final int themed_icon_tinder=0x7f02027b;
public static final int themed_icon_tinkoff=0x7f02027c;
public static final int themed_icon_tinkoff_accounting=0x7f02027d;
public static final int themed_icon_tinkoff_investing=0x7f02027e;
public static final int themed_icon_toolbox=0x7f02027f;
public static final int themed_icon_tor_browser=0x7f020280;
public static final int themed_icon_total_commander=0x7f020281;
public static final int themed_icon_track24=0x7f020282;
public static final int themed_icon_trebleinfo=0x7f020283;
public static final int themed_icon_trendyol=0x7f020284;
public static final int themed_icon_truecaller=0x7f020285;
public static final int themed_icon_trust_wallet=0x7f020286;
public static final int themed_icon_tt=0x7f020287;
public static final int themed_icon_tumblr=0x7f020288;
public static final int themed_icon_turkcell=0x7f020289;
public static final int themed_icon_tw=0x7f02028a;
public static final int themed_icon_twitch=0x7f02028b;
public static final int themed_icon_twitter=0x7f02028c;
public static final int themed_icon_uala=0x7f02028d;
public static final int themed_icon_uber=0x7f02028e;
public static final int themed_icon_uber_fleet=0x7f02028f;
public static final int themed_icon_uber_freight=0x7f020290;
public static final int themed_icon_uber_manager=0x7f020291;
public static final int themed_icon_uber_motorista=0x7f020292;
public static final int themed_icon_uber_orders=0x7f020293;
public static final int themed_icon_ubereats=0x7f020294;
public static final int themed_icon_ucbrowser=0x7f020295;
public static final int themed_icon_udemy=0x7f020296;
public static final int themed_icon_vanced_manager=0x7f020297;
public static final int themed_icon_vanced_music=0x7f020298;
public static final int themed_icon_vanced_youtube=0x7f020299;
public static final int themed_icon_venmo=0x7f02029a;
public static final int themed_icon_via_browser=0x7f02029b;
public static final int themed_icon_viber=0x7f02029c;
public static final int themed_icon_viper_four_android_fx=0x7f02029d;
public static final int themed_icon_vivacut=0x7f02029e;
public static final int themed_icon_vivaldi=0x7f02029f;
public static final int themed_icon_vk=0x7f0202a0;
public static final int themed_icon_vk_mail=0x7f0202a1;
public static final int themed_icon_vkontakte=0x7f0202a2;
public static final int themed_icon_vkx=0x7f0202a3;
public static final int themed_icon_vlc=0x7f0202a4;
public static final int themed_icon_vodafone=0x7f0202a5;
public static final int themed_icon_vtb_online=0x7f0202a6;
public static final int themed_icon_wall_x=0x7f0202a7;
public static final int themed_icon_wallet=0x7f0202a8;
public static final int themed_icon_wavelet=0x7f0202a9;
public static final int themed_icon_waze=0x7f0202aa;
public static final int themed_icon_wear_os=0x7f0202ab;
public static final int themed_icon_weheartit=0x7f0202ac;
public static final int themed_icon_whatsapp=0x7f0202ad;
public static final int themed_icon_whatsapp_business=0x7f0202ae;
public static final int themed_icon_wild_rift=0x7f0202af;
public static final int themed_icon_wildberries=0x7f0202b0;
public static final int themed_icon_windscribe=0x7f0202b1;
public static final int themed_icon_wish=0x7f0202b2;
public static final int themed_icon_wordweb=0x7f0202b3;
public static final int themed_icon_wps_office=0x7f0202b4;
public static final int themed_icon_xda=0x7f0202b5;
public static final int themed_icon_ximiui=0x7f0202b6;
public static final int themed_icon_xprivacylua=0x7f0202b7;
public static final int themed_icon_xprivacylua_pro=0x7f0202b8;
public static final int themed_icon_yandex_disk=0x7f0202b9;
public static final int themed_icon_yandex_eda=0x7f0202ba;
public static final int themed_icon_yandex_go=0x7f0202bb;
public static final int themed_icon_yandex_mail=0x7f0202bc;
public static final int themed_icon_yandex_maps=0x7f0202bd;
public static final int themed_icon_yandex_music=0x7f0202be;
public static final int themed_icon_yandex_translate=0x7f0202bf;
public static final int themed_icon_yeelight=0x7f0202c0;
public static final int themed_icon_yelp=0x7f0202c1;
public static final int themed_icon_yemeksepeti=0x7f0202c2;
public static final int themed_icon_ykb=0x7f0202c3;
public static final int themed_icon_ymusic=0x7f0202c4;
public static final int themed_icon_yoo_money=0x7f0202c5;
public static final int themed_icon_yota=0x7f0202c6;
public static final int themed_icon_youtube=0x7f0202c7;
public static final int themed_icon_youtube_music=0x7f0202c8;
public static final int themed_icon_youtube_tv=0x7f0202c9;
public static final int themed_icon_yuola=0x7f0202ca;
public static final int themed_icon_zalo=0x7f0202cb;
public static final int themed_icon_zarchiver=0x7f0202cc;
public static final int themed_icon_zedge=0x7f0202cd;
public static final int themed_icons_tt=0x7f0202ce;
public static final int tiktok=0x7f0202cf;
public static final int toolbox=0x7f0202d0;
public static final int tor_browser=0x7f0202d1;
public static final int torbrowser=0x7f0202d2;
public static final int twitch=0x7f0202d3;
public static final int twitter=0x7f0202d4;
public static final int vancedmanager=0x7f0202d5;
public static final int vectorasset=0x7f0202d6;
public static final int via_browser=0x7f0202d7;
public static final int vlc=0x7f0202d8;
public static final int whatsapp=0x7f0202d9;
public static final int whatsapp_business=0x7f0202da;
public static final int xda=0x7f0202db;
public static final int yeelight=0x7f0202dc;
public static final int ymusic=0x7f0202dd;
public static final int youtube_vanced=0x7f0202de;
public static final int ytmusic_vanced=0x7f0202df;
public static final int zarchiver=0x7f0202e0;
}
public static final class mipmap {
public static final int ic_launcher=0x7f030000;
public static final int ic_launcher_background=0x7f030001;
public static final int ic_launcher_foreground=0x7f030002;
public static final int ic_launcher_round=0x7f030003;
}
public static final class string {
public static final int app_name=0x7f080000;
public static final int search_bar_hint=0x7f080001;
}
public static final class style {
public static final int Theme_Lawnicons=0x7f090000;
}
public static final class xml {
public static final int grayscale_icon_map=0x7f040000;
}
}
| ios7jbpro/lawnicons | gen/app/lawnchair/lawnicons/R.java |
3,006 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import org.havi.ui.*;
import java.awt.*;
import org.dvb.ui.*;
/**
* Oefening Blz 44: MijnComponent
* @author student: Jolita Grazyte
*/
//Klasse van HComponent overerven
public class MijnComponent extends HComponent{
//Plaats en locatie instellen in de constructor
public MijnComponent(int posX, int posY, int width, int height){
this.setBounds(posX, posY, width, height);
}
public void paint(Graphics g){
g.setColor(new DVBColor(0, 0, 0, 100));
g.fillRoundRect(25, 95, 200, 100, 40, 40);
g.setColor(new DVBColor(0, 0, 179, 150));
g.fillRoundRect(20, 100, 200, 100, 40, 40);
g.setColor(new DVBColor(255, 255, 0, 175));
g.drawString("Mijn Component", 45, 160);
}
}
| MTA-Digital-Broadcast-2/O-Van-den-Broeck-Jeroen-Gurbuz-Hasan-Project-MHP | Gurbuz_Hasan/Labojava/Blz44/src/hellotvxlet/MijnComponent.java |
3,007 | package be.pxl.vraag1;
/*
Daan Vankerkom
1 TIN J
*/
public final class Landmijn extends WereldObject {
public final static int MINSCHADE = 10;
public final static int MAXSCHADE = 100;
private int schade;
private boolean actief;
public Landmijn(int schade) {
if (schade < MINSCHADE) {
this.schade = MINSCHADE;
} else if (schade > MAXSCHADE) {
this.schade = MAXSCHADE;
} else {
this.schade = schade;
}
this.actief = true;
}
public int getSchade() {
return schade;
}
public boolean isActief() {
return actief;
}
public void ontplof() {
actief = false;
}
@Override
public String toString() {
if (actief) {
return "Actieve landmijn " + schade + " schade";
}else{
return "Ontplofte landmijn";
}
}
}
| JoachimVeulemans/PXL-DIGITAL | PXL_DIGITAL_JAAR_1/Java Essentials/TiX/PXL_examen_2016_eerste-zit/vraag1/Landmijn.java |
3,008 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hellotvxlet;
import java.util.TimerTask;
/**
*
* @author student
*/
public class MijnTimerTask extends TimerTask {
HelloTVXlet xl;
public void setCB(HelloTVXlet xl)
{
this.xl=xl;
}
public void run() {
xl.callback();
}
}
| ksoontjens/2017_11_Van_Belle_Lander_Willems_Bjarne | src/hellotvxlet/MijnTimerTask.java |
3,009 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package wereld;
import java.awt.Color;
/**
* Superklasse voor BozelType, TargetType en MateriaalType.
*
* @author Frederic Everaert
*/
public class MijnType {
protected float krachtdrempel;
protected float sterkte;
protected Color kleur;
protected WereldModel model;
private boolean breekbaar;
public MijnType(WereldModel model) {
this.model = model;
breekbaar = true;
}
public float getKrachtdrempel(){
return krachtdrempel;
}
public void setKrachtdrempel(float krachtdrempel){
this.krachtdrempel = krachtdrempel;
model.fireStateChanged();
}
public float getSterkte(){
return sterkte;
}
public void setSterkte(float sterkte){
this.sterkte = sterkte;
model.fireStateChanged();
}
public Color getKleur(){
return kleur;
}
public void setKleur(Color kleur){
this.kleur = kleur;
model.fireStateChanged();
}
public boolean isBreekbaar(){
return breekbaar;
}
public void setBreekbaar(boolean b){
breekbaar = b;
model.fireStateChanged();
}
}
| feveraer/Bozels | src/wereld/MijnType.java |
3,010 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class MijnGUI {
private JPanel MijnPanel;
private JButton klikButton;
private JTextField textField1;
private JButton button1;
private JTextArea textArea1;
private JButton button2;
public MijnGUI() {
klikButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File selectedFile;
JFileChooser fileChooser = new JFileChooser();
int reply = fileChooser.showOpenDialog(null);
if (reply == JFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
textField1.setText(selectedFile.getAbsolutePath());
} else {
textField1.setText("No file selected");
textField1.setBackground(Color.RED);
}
}
});
button1.addActionListener(new ActionListener() {
/**
* Invoked when an action occurs.
*
* @param e the event to be processed
*/
@Override
public void actionPerformed(ActionEvent e) {
readFile();
}
});
}
private void readFile(){
String line;
try {
BufferedReader inFile = new BufferedReader(new FileReader(textField1.getText()));
while ((line = inFile.readLine()) != null) {
textArea1.append(line + "\n");
}
inFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("MijnGUI");
frame.setContentPane(new MijnGUI().MijnPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
| hanbioinformatica/owe5a | GUImodule/src/MijnGUI.java |
3,011 | /*
Copyright 2006-2023 by Dave Dyer
This file is part of the Boardspace project.
Boardspace 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.
Boardspace 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 Boardspace.
If not, see https://www.gnu.org/licenses/.
*/
package mijnlieff;
import lib.DrawableImageStack;
import lib.ImageLoader;
import lib.OStack;
import lib.Random;
import mijnlieff.MijnlieffConstants.MColor;
import mijnlieff.MijnlieffConstants.MijnlieffId;
import online.game.chip;
import common.CommonConfig;
class ChipStack extends OStack<MijnlieffChip>
{
public MijnlieffChip[] newComponentArray(int n) { return(new MijnlieffChip[n]); }
}
/**
* this is a specialization of {@link chip} to represent the stones used by pushfight;
* and also other tiles, borders and other images that are used to draw the board.
*
* @author ddyer
*
*/
public class MijnlieffChip extends chip<MijnlieffChip> implements CommonConfig
{
private static Random r = new Random(5312324); // this gives each chip a unique random value for Digest()
private static DrawableImageStack otherChips = new DrawableImageStack();
private static boolean imagesLoaded = false;
public MijnlieffId id;
public MColor color;
public String contentsString() { return(id==null ? file : id.name()); }
// constructor for the chips on the board, which are the only things that are digestable.
private MijnlieffChip(String na,double[]sc,MColor mc,MijnlieffId con)
{
scale=sc;
file = na;
id = con;
color = mc;
if(con!=null) { con.chip = this; }
randomv = r.nextLong();
otherChips.push(this);
}
// constructor for all the other random artwork.
private MijnlieffChip(String na,double[]sc)
{
scale=sc;
file = na;
otherChips.push(this);
}
public int chipNumber() { return(id==null?-1:id.ordinal()); }
static double ChipScale[] = {0.5,0.5,1.0};
static public MijnlieffChip Dark_push = new MijnlieffChip("dark-push",ChipScale,MColor.Dark,MijnlieffId.Dark_Push);
static public MijnlieffChip Dark_pull = new MijnlieffChip("dark-pull",ChipScale,MColor.Dark,MijnlieffId.Dark_Pull);
static public MijnlieffChip Dark_diagonal = new MijnlieffChip("dark-diagonal",ChipScale,MColor.Dark,MijnlieffId.Dark_Diagonal);
static public MijnlieffChip Dark_orthogonal = new MijnlieffChip("dark-orthogonal",ChipScale,MColor.Dark,MijnlieffId.Dark_Orthogonal);
static public MijnlieffChip Light_push = new MijnlieffChip("light-push",ChipScale,MColor.Light,MijnlieffId.Light_Push);
static public MijnlieffChip Light_pull = new MijnlieffChip("light-pull",ChipScale,MColor.Light,MijnlieffId.Light_Pull);
static public MijnlieffChip Light_diagonal = new MijnlieffChip("light-diagonal",ChipScale,MColor.Light,MijnlieffId.Light_Diagonal);
static public MijnlieffChip Light_orthogonal = new MijnlieffChip("light-orthogonal",ChipScale,MColor.Light,MijnlieffId.Light_Orthogonal);
// indexes into the balls array, usually called the rack
static final MijnlieffChip getChip(int n) { return(MijnlieffId.values()[n].chip); }
/* plain images with no mask can be noted by naming them -nomask */
static public MijnlieffChip backgroundTile = new MijnlieffChip("background-tile-nomask",null);
static public MijnlieffChip backgroundReviewTile = new MijnlieffChip("background-review-tile-nomask",null);
public static MijnlieffChip Icon = new MijnlieffChip("hex-icon-nomask",null);
static private double noScale[] = {0.50,0.50,1};
static public MijnlieffChip board = new MijnlieffChip("board",noScale);
/**
* this is a fairly standard preloadImages method, called from the
* game initialization. It loads the images into the stack of
* chips we've built
* @param forcan the canvas for which we are loading the images.
* @param Dir the directory to find the image files.
*/
public static void preloadImages(ImageLoader forcan,String Dir)
{ if(!imagesLoaded)
{ imagesLoaded = forcan.load_masked_images(Dir,otherChips);
}
}
}
| ddyer0/boardspace.net | client/boardspace-java/boardspace-games/mijnlieff/MijnlieffChip.java |
3,012 | package db;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import domain.TweeSteden;
public class Databank {
private String fileName;
private Map<Object, Object> mijnmap = new HashMap<>();
private Object afstanden;
public Databank() {
this("google_afstanden.txt");
}
public Databank(String filename) {
setFileName(filename);
loadData();
}
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
// TODO Read the information from a line and add it to your
// afstanden
String stadVan = null;
String stadNaar = null;
double km = 0;
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
lijnScanner.close();
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
private void voegToe(TweeSteden afstand, double km) {
if (afstand == null
// Add a distance only if no duplicate exists already
) {
throw new IllegalArgumentException();
}
// Add the distance to afstanden
}
private String getFileName() {
return fileName;
}
private void setFileName(String fileName) {
this.fileName = fileName;
}
public Map<TweeSteden, Double> getAfstanden() {
// TODO
return null;
}
}
| martijnmeeldijk/TI-oplossingen | Semester_2/OOP/Labo Hashmap/src/db/Databank.java |