repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
doomdagger/CompetitionHub
src/main/java/com/djtu/signExam/service/news/impl/NewsServiceImpl.java
2526
package com.djtu.signExam.service.news.impl; import com.djtu.signExam.dao.impl.TNewsDao; import com.djtu.signExam.dao.support.IOperators; import com.djtu.signExam.dao.support.Pageable; import com.djtu.signExam.dao.support.SQLWrapper; import com.djtu.signExam.dao.support.Sortable; import com.djtu.signExam.model.TNews; import com.djtu.signExam.service.news.NewsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * Created by root on 14-7-24. */ @Component("newsService") public class NewsServiceImpl implements NewsService { @Autowired public TNewsDao tNewsDao; @Override public List<TNews> getNewsByPage(String userId,Pageable pageable) { //sort by istop and createtime,and select the current user's issue SQLWrapper sqlWrapper = SQLWrapper.instance().selectAll().where().eq("sk_t_userAdmin",userId).orderBy(Sortable.inSort("is_top", IOperators.SORT.DESC)).orderBy(Sortable.inSort("createtime", IOperators.SORT.DESC)); //set pageCount pageable.setPageCount(tNewsDao.getPageCount(pageable.getPageSize(), tNewsDao.getCountByWrapper(sqlWrapper)));//no select in page return tNewsDao.findAllByWrapper(sqlWrapper.limit(pageable)); } @Override public List<TNews> getAllNewsByPage(Pageable pageable) { //sort by istop and createtime SQLWrapper sqlWrapper = SQLWrapper.instance().selectAll().orderBy(Sortable.inSort("is_top", IOperators.SORT.DESC)).orderBy(Sortable.inSort("createtime", IOperators.SORT.DESC)); //set pageCount pageable.setPageCount(tNewsDao.getPageCount(pageable.getPageSize(), tNewsDao.getCountByWrapper(sqlWrapper))); return tNewsDao.findAllByWrapper(sqlWrapper.limit(pageable)); } @Override public TNews getNewsById(String id) { return tNewsDao.findOneById(id); } @Override public boolean updateNews(TNews tNews) { SQLWrapper sqlWrapper = SQLWrapper.instance().update(tNews); return tNewsDao.updateByWrapper(sqlWrapper); } @Override public boolean deleteNewsById(String id) { return tNewsDao.deleteById(id); } @Override public boolean addNews(TNews tNews) { Object key = tNewsDao.add(tNews); if(key == null || key == ""){ return false; } return true; } @Override public int getPageCount(int pageSize) { return tNewsDao.getPageCount(pageSize); } }
gpl-2.0
bairutai/SinaWeibo
src/com/convenientbanner/transforms/RotateUpTransformer.java
516
package com.convenientbanner.transforms; import android.view.View; public class RotateUpTransformer extends ABaseTransformer { private static final float ROT_MOD = -15f; @Override protected void onTransform(View view, float position) { final float width = view.getWidth(); final float rotation = ROT_MOD * position; view.setPivotX(width * 0.5f); view.setPivotY(0f); view.setTranslationX(0f); view.setRotation(rotation); } @Override protected boolean isPagingEnabled() { return true; } }
gpl-2.0
yokwe/finance
Stock/src/yokwe/finance/stock/iex/cloud/Context.java
680
package yokwe.finance.stock.iex.cloud; public class Context { public final Type type; public final Version version; public final String url; public Context(Type type, Version version) { this.type = type; this.version = version; this.url = String.format("%s/%s", type.url, version.url); } @Override public String toString() { return String.format("%s %s %s", type.toString(), version.toString(), url); } public String getURL(String method) { return String.format("%s%s?token=%s", url, method, type.token.secret); } public String getURLAsCSV(String method) { return String.format("%s%s?token=%s&format=csv", url, method, type.token.secret); } }
gpl-2.0
concord-consortium/mw
src/org/concord/mw2d/ui/RemovalIcon.java
1944
/* * Copyright (C) 2006 The Concord Consortium, Inc., * 25 Love Lane, Concord, MA 01742 * * 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 * * END LICENSE */ package org.concord.mw2d.ui; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Stroke; import javax.swing.Icon; class RemovalIcon implements Icon { private final static Stroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, new float[] { 1.0f }, 0.0f); private Icon icon0; RemovalIcon(Icon icon0) { this.icon0 = icon0; } public int getIconWidth() { return icon0.getIconWidth(); } public int getIconHeight() { return icon0.getIconHeight(); } public void paintIcon(Component c, Graphics g, int x, int y) { icon0.paintIcon(c, g, x, y); Color oldColor = g.getColor(); Stroke oldStroke = ((Graphics2D) g).getStroke(); g.setColor(Color.black); ((Graphics2D) g).setStroke(dashed); g.drawRect(x, y, getIconWidth(), getIconHeight()); g.drawLine(x, y + getIconHeight(), x + getIconWidth(), y); g.drawLine(x, y, x + getIconWidth(), y + getIconHeight()); g.setColor(oldColor); ((Graphics2D) g).setStroke(oldStroke); } }
gpl-2.0
mim-dev/MIMRest
mimrest/src/main/java/com/mim_development/android/mimrest/model/services/base/http/request/HttpRequest.java
5840
package com.mim_development.android.mimrest.model.services.base.http.request; import com.mim_development.android.mimrest.model.services.base.http.connection.HttpConnection; import com.mim_development.android.mimrest.model.services.base.operation.HttpVerbs; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Http request elements for http calls with a defined payload. Class is immutable. */ public class HttpRequest { private HttpConnection connection; private Map<String, String> headers; private int connectionTimeoutInMillis; private HttpVerbs verb; private Map<String, String> parameters; /** * Instance construction with requisite dependencies and properties * @param connection - connection elements. * @param verb - HTTP verb. * @param headers - HTTP headers added to the HTTP call. * @param connectionTimeoutInMillis - number of milliseconds to wait for the connection to complete. * @param parameters - HTTP query string parameters. The parameters should be plain text, they will be URL encoded within this constructor. */ public HttpRequest( final HttpConnection connection, final HttpVerbs verb, final Map<String, String> headers, final int connectionTimeoutInMillis, final Map<String, String> parameters) { this.connection = connection; this.headers = headers; this.connectionTimeoutInMillis = connectionTimeoutInMillis; this.verb = verb; this.parameters = new HashMap<>(parameters.size()); for (String key : parameters.keySet()) { String encodedKey; try { encodedKey = URLEncoder.encode(key, "UTF-8"); } catch (UnsupportedEncodingException e) { encodedKey = key; } String encodedValue; String value = parameters.get(key); try { encodedValue = URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { encodedValue = value; } this.parameters.put(encodedKey, encodedValue); } } /** * Provides the payload to be included with the execution of the HTTP request. * @return - binary representation of the payload to be included with the HTTP request */ protected String getConnectionString() { return connection.toString(); } /** * Provides the HTTP headers added to the HTTP request. * @return - binary representation of the payload to be included with the HTTP request */ protected Map<String, String> getHeaders() { Map<String, String> result = new HashMap<>(headers.size()); result.putAll(headers); return result; } /** * Provides the number of milliseconds to wait for the connection to complete. * @return - the number of milliseconds to wait for the connection to complete. */ public int getConnectionTimeoutInMillis() { return connectionTimeoutInMillis; } /** * Provides the HTTP verb used to execute the HTTP request. * @return - the HTTP verb used to execute the request. */ protected String getVerb() { return verb.name(); } /** * Provides the query string parameters to be included with the execution of the HTTP request. * @return - query string parameters to be included with the HTTP request. */ protected Map<String, String> getParameters() { Map<String, String> parameterCopy = new HashMap<>(parameters.size()); parameterCopy.putAll(parameters); return parameterCopy; } protected String buildQueryString(){ String queryString; Map<String, String> parameters = getParameters(); if(parameters != null && parameters.size() > 0){ StringBuffer stringBuffer = new StringBuffer(); Set<String> keyList = parameters.keySet(); String[] keys = new String[keyList.size()]; keys = parameters.keySet().toArray(keys); stringBuffer.append("?"); stringBuffer.append(keys[0]); stringBuffer.append("="); stringBuffer.append(parameters.get(keys[0])); for(int keyIndex= 1; keyIndex < keys.length; keyIndex++){ stringBuffer.append("&"); stringBuffer.append(keys[keyIndex]); stringBuffer.append("="); stringBuffer.append(parameters.get(keys[keyIndex])); } queryString = stringBuffer.toString(); } else{ queryString = ""; } return queryString; } /** * Adds HTTP connection headers. * @param connection - the connection information to be used during the execution of the request. */ protected void addHeaders(HttpURLConnection connection) { Map<String, String> headers = getHeaders(); if(headers != null) { for (String headerName : headers.keySet()) { connection.setRequestProperty(headerName, headers.get(headerName)); } } } public HttpURLConnection getHttpURLConnection() throws IOException { URL url = new URL(getConnectionString() + buildQueryString()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(getVerb()); addHeaders(connection); connection.setConnectTimeout(getConnectionTimeoutInMillis()); connection.setDoInput(true); return connection; } }
gpl-2.0
martinm2w/intellinx
intellinx-commons/src/com/intellinx/us/ps/algorithms/Mathematics.java
20354
package com.intellinx.us.ps.algorithms; import java.text.DecimalFormat; import com.intellinx.us.ps.algorithms.mathematics.Division; import com.intellinx.us.ps.algorithms.mathematics.Knapsack; import com.intellinx.us.ps.algorithms.mathematics.Multiplication; /** * * @author RenatoM * */ public class Mathematics { private static final DecimalFormat FORMAT = new DecimalFormat("#.######"); public static void main(String[] args) { // MULTIPLICATION { int a = 12; int b = 14; System.out.println("Multiplication using a loop."); long before = System.nanoTime(); long result = Multiplication.multiplyUsingLoop(a, b); long after = System.nanoTime(); long check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using recursion."); before = System.nanoTime(); result = Multiplication.multiplyUsingRecursion(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using shifts."); before = System.nanoTime(); result = Multiplication.multiplyUsingShift(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using logs."); before = System.nanoTime(); result = Multiplication.multiplyUsingLogs(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.out.println(); System.gc(); } { int a = -74; int b = 62; System.out.println("Multiplication using a loop."); long before = System.nanoTime(); long result = Multiplication.multiplyUsingLoop(a, b); long after = System.nanoTime(); long check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using recursion."); before = System.nanoTime(); result = Multiplication.multiplyUsingRecursion(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using shifts."); before = System.nanoTime(); result = Multiplication.multiplyUsingShift(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using logs."); before = System.nanoTime(); result = Multiplication.multiplyUsingLogs(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.out.println(); System.gc(); } { int a = 84; int b = -79; System.out.println("Multiplication using a loop."); long before = System.nanoTime(); long result = Multiplication.multiplyUsingLoop(a, b); long after = System.nanoTime(); long check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using recursion."); before = System.nanoTime(); result = Multiplication.multiplyUsingRecursion(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using shifts."); before = System.nanoTime(); result = Multiplication.multiplyUsingShift(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using logs."); before = System.nanoTime(); result = Multiplication.multiplyUsingLogs(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.out.println(); System.gc(); } { int a = -92; int b = -87; System.out.println("Multiplication using a loop."); long before = System.nanoTime(); long result = Multiplication.multiplyUsingLoop(a, b); long after = System.nanoTime(); long check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using recursion."); before = System.nanoTime(); result = Multiplication.multiplyUsingRecursion(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using shifts."); before = System.nanoTime(); result = Multiplication.multiplyUsingShift(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Multiplication using logs."); before = System.nanoTime(); result = Multiplication.multiplyUsingLogs(a, b); after = System.nanoTime(); check = Multiplication.multiplication(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "x" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.out.println(); System.gc(); } // DIVISION { int a = 9; int b = 3; System.out.println("Division using a loop."); long before = System.nanoTime(); long result = Division.divisionUsingLoop(a, b); long after = System.nanoTime(); long check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using recursion."); before = System.nanoTime(); result = Division.divisionUsingRecursion(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using shifts."); before = System.nanoTime(); result = Division.divisionUsingShift(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using logs."); before = System.nanoTime(); result = Division.divisionUsingLogs(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using multiplication."); before = System.nanoTime(); result = Division.divisionUsingMultiplication(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.out.println(); System.gc(); } { int a = -54; int b = 6; System.out.println("Division using a loop."); long before = System.nanoTime(); long result = Division.divisionUsingLoop(a, b); long after = System.nanoTime(); long check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using recursion."); before = System.nanoTime(); result = Division.divisionUsingRecursion(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using shifts."); before = System.nanoTime(); result = Division.divisionUsingShift(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using logs."); before = System.nanoTime(); result = Division.divisionUsingLogs(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using multiplication."); before = System.nanoTime(); result = Division.divisionUsingMultiplication(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.out.println(); System.gc(); } { int a = 98; int b = -7; System.out.println("Division using a loop."); long before = System.nanoTime(); long result = Division.divisionUsingLoop(a, b); long after = System.nanoTime(); long check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using recursion."); before = System.nanoTime(); result = Division.divisionUsingRecursion(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using shifts."); before = System.nanoTime(); result = Division.divisionUsingShift(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using logs."); before = System.nanoTime(); result = Division.divisionUsingLogs(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using multiplication."); before = System.nanoTime(); result = Division.divisionUsingMultiplication(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.out.println(); System.gc(); } { int a = -568; int b = -15; System.out.println("Division using a loop."); long before = System.nanoTime(); long result = Division.divisionUsingLoop(a, b); long after = System.nanoTime(); long check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using recursion."); before = System.nanoTime(); result = Division.divisionUsingRecursion(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using shifts."); before = System.nanoTime(); result = Division.divisionUsingShift(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using logs."); before = System.nanoTime(); result = Division.divisionUsingLogs(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); System.out.println("Division using multiplication."); before = System.nanoTime(); result = Division.divisionUsingMultiplication(a, b); after = System.nanoTime(); check = Division.division(a, b); if (result != check) System.out.println("ERROR with a=" + a + " b=" + b + " result=" + result + " check=" + check); else System.out.println(a + "/" + b + "=" + result); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.out.println(); System.gc(); } { int[] values = { 7, 4, 8, 6, 2, 5 }; int[] weights = { 2, 3, 5, 4, 2, 3 }; int capacity = 9; System.out.println("Knapsack problem."); long before = System.nanoTime(); int[] result = Knapsack.zeroOneKnapsack(values, weights, capacity); long after = System.nanoTime(); System.out.println("result=" + getIntegerString(result)); System.out.println("Computed in " + FORMAT.format(after - before) + " ns"); System.gc(); } } private static final String getIntegerString(int[] result) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < result.length; i++) { int v = result[i]; builder.append(v); if (i != result.length - 1) builder.append(", "); } return builder.toString(); } }
gpl-2.0
underplex/tickay
src/main/java/com/underplex/tickay/info/AmericaGameInfo.java
758
package com.underplex.tickay.info; import com.underplex.tickay.game.AmericaGame; import com.underplex.tickay.jaxbinfo.AmericaGameEntryInfo; /** * Immutable wrapper for the game currently being played. * <p> * Many of the most important functions of this are taken from * {@link GameInfo GameInfo}. * * @author Brandon Irvine * */ public class AmericaGameInfo extends GameInfo { private AmericaGame americaSource; /** * Constructor used by simulator. */ public AmericaGameInfo(AmericaGame source) { super(source); this.americaSource = source; } /** * Returns immutable game entry representing record of the game. * */ public AmericaGameEntryInfo getGameEntry() { return this.americaSource.getGameEntry().info(); } }
gpl-2.0
lsilvestre/Jogre
api/test/src/org/jogre/common/comm/CommTest.java
2095
/* * JOGRE (Java Online Gaming Real-time Engine) - API * Copyright (C) 2004 Bob Marks (marksie531@yahoo.com) * http://jogre.sourceforge.org * * 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 org.jogre.common.comm; import junit.framework.TestCase; /** * Collection of simple test on Comm objects. * * @author Bob Marks * @version Beta 0.3 */ public class CommTest extends TestCase { /** * Test CommAdminClientData comm object - Test 1. * * @throws Exception */ public void testCommAdminClientData1 () throws Exception { String [][] data = {{"bob", "bob123"}, {"sharon", "sharon123"}, {"dave", "dave123"}}; CommAdminClientData comm1 = new CommAdminClientData (data, "users"); String str1 = comm1.toString(); CommAdminClientData comm2 = new CommAdminClientData (comm1.flatten()); String str2 = comm2.toString(); assertEquals (str1, str2); // test flatten methods are same } /** * Test CommAdminClientData comm object - Test 2. * * @throws Exception */ public void testCommAdminClientData2 () throws Exception { String [] reqData = {"jimmy", "jimmy123"}; CommAdminClientData comm1 = new CommAdminClientData (reqData, "users", CommAdminClientData.NEW); String str1 = comm1.toString(); CommAdminClientData comm2 = new CommAdminClientData (comm1.flatten()); String str2 = comm2.toString(); assertEquals (str1, str2); // test flatten methods are same } }
gpl-2.0
Team-OfferManager/ebay-jaxb-bindings
src/main/java/de/idealo/offers/imports/offermanager/ebay/api/binding/jaxb/finding/ErrorData.java
7074
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2014.11.20 um 01:49:01 PM CET // package de.idealo.offers.imports.offermanager.ebay.api.binding.jaxb.finding; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * * A container for error details. * * * <p>Java-Klasse für ErrorData complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="ErrorData"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="errorId" type="{http://www.w3.org/2001/XMLSchema}long"/&gt; * &lt;element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="severity" type="{http://www.ebay.com/marketplace/search/v1/services}ErrorSeverity"/&gt; * &lt;element name="category" type="{http://www.ebay.com/marketplace/search/v1/services}ErrorCategory"/&gt; * &lt;element name="message" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="subdomain" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="exceptionId" type="{http://www.w3.org/2001/XMLSchema}token" minOccurs="0"/&gt; * &lt;element name="parameter" type="{http://www.ebay.com/marketplace/search/v1/services}ErrorParameter" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ErrorData", propOrder = { "errorId", "domain", "severity", "category", "message", "subdomain", "exceptionId", "parameter" }) public class ErrorData { protected long errorId; @XmlElement(required = true) protected String domain; @XmlElement(required = true) @XmlSchemaType(name = "string") protected ErrorSeverity severity; @XmlElement(required = true) @XmlSchemaType(name = "string") protected ErrorCategory category; @XmlElement(required = true) protected String message; protected String subdomain; @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String exceptionId; @XmlElement(nillable = true) protected List<ErrorParameter> parameter; /** * Ruft den Wert der errorId-Eigenschaft ab. * */ public long getErrorId() { return errorId; } /** * Legt den Wert der errorId-Eigenschaft fest. * */ public void setErrorId(long value) { this.errorId = value; } /** * Ruft den Wert der domain-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getDomain() { return domain; } /** * Legt den Wert der domain-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setDomain(String value) { this.domain = value; } /** * Ruft den Wert der severity-Eigenschaft ab. * * @return * possible object is * {@link ErrorSeverity } * */ public ErrorSeverity getSeverity() { return severity; } /** * Legt den Wert der severity-Eigenschaft fest. * * @param value * allowed object is * {@link ErrorSeverity } * */ public void setSeverity(ErrorSeverity value) { this.severity = value; } /** * Ruft den Wert der category-Eigenschaft ab. * * @return * possible object is * {@link ErrorCategory } * */ public ErrorCategory getCategory() { return category; } /** * Legt den Wert der category-Eigenschaft fest. * * @param value * allowed object is * {@link ErrorCategory } * */ public void setCategory(ErrorCategory value) { this.category = value; } /** * Ruft den Wert der message-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getMessage() { return message; } /** * Legt den Wert der message-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setMessage(String value) { this.message = value; } /** * Ruft den Wert der subdomain-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getSubdomain() { return subdomain; } /** * Legt den Wert der subdomain-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setSubdomain(String value) { this.subdomain = value; } /** * Ruft den Wert der exceptionId-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getExceptionId() { return exceptionId; } /** * Legt den Wert der exceptionId-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setExceptionId(String value) { this.exceptionId = value; } /** * Gets the value of the parameter property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parameter property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParameter().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ErrorParameter } * * */ public List<ErrorParameter> getParameter() { if (parameter == null) { parameter = new ArrayList<ErrorParameter>(); } return this.parameter; } }
gpl-2.0
52North/SensorPlanningService
52n-sps-api/src/main/java/org/n52/sps/tasking/TaskingRequestStatus.java
2234
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * 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. */ package org.n52.sps.tasking; import net.opengis.sps.x20.TaskingRequestStatusCodeEnumerationType; public enum TaskingRequestStatus { ACCEPTED(TaskingRequestStatusCodeEnumerationType.ACCEPTED), PENDING(TaskingRequestStatusCodeEnumerationType.PENDING), REJECTED(TaskingRequestStatusCodeEnumerationType.REJECTED); private TaskingRequestStatusCodeEnumerationType.Enum status; TaskingRequestStatus(TaskingRequestStatusCodeEnumerationType.Enum status) { this.status = status; } public TaskingRequestStatusCodeEnumerationType.Enum getStatus() { return status; } public static TaskingRequestStatus getTaskingRequestStatus(String status) { return valueOf(status.toUpperCase()); } @Override public String toString() { return status.toString(); } }
gpl-2.0
ilaclaus/TFM-Storyteller
Código del Proyecto/src/personajes/Princesa.java
3917
package personajes; import jade.core.AID; import jade.core.behaviours.Behaviour; import jade.core.behaviours.CyclicBehaviour; import jade.domain.DFService; import jade.domain.FIPAException; import jade.domain.FIPAAgentManagement.DFAgentDescription; import jade.domain.FIPAAgentManagement.ServiceDescription; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; public class Princesa extends Personaje { private AID padre; private AID dragon; public Princesa() { super(100, "Castillo"); } protected void setup(){ avisarInicio(); localizarPersonaje(); Object[] args = getArguments(); if (args != null && args.length > 0) { padre = new AID((String) args[0], AID.ISLOCALNAME); getLogger().info("La Princesa " + getAID().getLocalName() + " despierta."); System.out.println(marcaDeClase() + " La Princesa " + getAID().getLocalName() + " despierta. \n"); DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); ServiceDescription sd = new ServiceDescription(); sd.setType("Secuestro"); sd.setName("JADE-Secuestro"); dfd.addServices(sd); try{ DFService.register(this, dfd); } catch (FIPAException fe){ fe.printStackTrace(); } /* addBehaviour(new MoverSecuestrada()); addBehaviour(new AvisaAPadre()); addBehaviour(new Rescatada()); */ comportamientoPaseo(); } else { getLogger().info("La Princesa " + getAID().getLocalName() + " no tiene padre. No hay a quien pedir rescate."); System.out.println(marcaDeClase() + " La Princesa no tiene padre. No hay a quien pedir rescate. \n"); doDelete(); } } protected void takeDown() { getLogger().info("La Princesa " + getAID().getLocalName() + " pone fin a su aventura."); System.out.println(marcaDeClase() + " La Princesa " + getLocalName() + " pone fin a su aventura. \n"); } private class MoverSecuestrada extends CyclicBehaviour { public void action() { MessageTemplate mt = MessageTemplate.and( MessageTemplate.MatchPerformative(ACLMessage.REQUEST), MessageTemplate.MatchConversationId("Mover-Princesa")); ACLMessage receive = myAgent.receive(mt); if ( receive != null ) { moverSecuestrado(receive.getContent()); ACLMessage reply = receive.createReply(); myAgent.send(reply); } else block(); } } private class AvisaAPadre extends Behaviour { private ACLMessage receive; public void action() { MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchConversationId("Te secuestro"), MessageTemplate.MatchPerformative(ACLMessage.INFORM)); receive = receive(mt); if ( receive != null ) { try{ DFService.deregister(myAgent); }catch (FIPAException fe){ fe.printStackTrace(); } dragon = receive.getSender(); send(receive.createReply()); getLogger().info("La Princesa " + getAID().getLocalName() + " ha sido secuestrada."); System.out.println(marcaDeClase() + " La Princesa " + myAgent.getLocalName() + " ha sido secuestrada. \n"); ACLMessage inform = new ACLMessage(ACLMessage.REQUEST); inform.setConversationId("Ayuda"); inform.setReplyWith("request" + System.currentTimeMillis()); inform.addReceiver(padre); inform.setContent(dragon.getLocalName()); myAgent.send(inform); } else block(); } @Override public boolean done() { return receive != null; } } private class Rescatada extends Behaviour { ACLMessage receive; public void action() { MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchConversationId("Rescatada"), MessageTemplate.MatchPerformative(ACLMessage.INFORM)); receive = receive(mt); if ( receive != null ) myAgent.doDelete(); else block(); } public boolean done() { return receive != null; } } }
gpl-2.0
sunejak/EmbeddedJetty
src/main/java/com/ntnu/sune/App.java
176
package com.ntnu.sune; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
gpl-2.0
xubo245/CloudSW
src/main/java/htsjdk/samtools/apps/TimeChannel.java
2688
/* * The MIT License * * Copyright (c) 2010 The Broad Institute * * 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 */ package htsjdk.samtools.apps; import java.io.File; import java.io.FileInputStream; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; /** * @author alecw@broadinstitute.org */ public class TimeChannel { public static void main(String[] args) throws Exception { long fileSize = new File(args[0]).length(); FileInputStream in = new FileInputStream(args[0]); FileChannel channel = in.getChannel(); byte[] buf = new byte[64 * 1024]; long totalBytesRead = 0; long mappedOffset = 0; // Map a round number of bytes that might correspond to some kind of page size boundary. long maxToMapAtATime = 1024 * 1024 * 1024; long mappedSize = Math.min(fileSize, maxToMapAtATime); while (totalBytesRead < fileSize) { System.err.println("mappedOffset: " + mappedOffset + "; mappedSize: " + mappedSize); System.err.println("fileSize: " + fileSize + "; totalBytesRead: " + totalBytesRead); MappedByteBuffer mappedBuffer = channel.map(FileChannel.MapMode.READ_ONLY, mappedOffset, mappedSize); while (mappedBuffer.remaining() > 0) { int bytesRead = Math.min(mappedBuffer.remaining(), buf.length); mappedBuffer.get(buf, 0, bytesRead); totalBytesRead += bytesRead; } mappedOffset += mappedSize; mappedSize = Math.min(fileSize - totalBytesRead, maxToMapAtATime); } System.out.println("Total bytes: " + totalBytesRead); } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/src/share/classes/sun/io/CharToByteCp935.java
1521
/* * Copyright 1997-2003 Sun Microsystems, Inc. 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package sun.io; import sun.nio.cs.ext.*; public class CharToByteCp935 extends CharToByteDBCS_EBCDIC { // Return the character set id public String getCharacterEncoding() { return "Cp935"; } public CharToByteCp935() { super((DoubleByte.Encoder)new IBM935().newEncoder()); } }
gpl-2.0
smarr/GraalCompiler
graal/com.oracle.graal.jtt/src/com/oracle/graal/jtt/threads/Thread_isInterrupted05.java
2287
/* * Copyright (c) 2009, 2012, 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. * * 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 com.oracle.graal.jtt.threads; import org.junit.Test; import com.oracle.graal.jtt.JTTTest; /* */ // Interrupted during wait, with interrupter joining public class Thread_isInterrupted05 extends JTTTest { public static boolean test() throws InterruptedException { final WaitInterruptee waitInterruptee = new WaitInterruptee(); waitInterruptee.start(); waitInterruptee.interrupt(); waitInterruptee.join(); if (waitInterruptee.throwable != null) { throw new RuntimeException(waitInterruptee.throwable); } return true; } static class WaitInterruptee extends Thread { Throwable throwable; public WaitInterruptee() { super("WaitInterruptee"); } @Override public void run() { try { synchronized (this) { try { wait(); } catch (InterruptedException ex) { } } } catch (Throwable t) { throwable = t; } } } @Test(timeout = 20000) public void run0() throws Throwable { runTest("test"); } }
gpl-2.0
rex-xxx/mt6572_x201
sdk/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceChooser.java
31293
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.eclipse.adt.internal.ui; import static com.android.SdkConstants.ANDROID_PREFIX; import static com.android.SdkConstants.PREFIX_RESOURCE_REF; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.ide.common.rendering.api.ResourceValue; import com.android.ide.common.resources.ResourceItem; import com.android.ide.common.resources.ResourceRepository; import com.android.ide.common.resources.ResourceResolver; import com.android.ide.eclipse.adt.AdtPlugin; import com.android.ide.eclipse.adt.AdtUtils; import com.android.ide.eclipse.adt.internal.assetstudio.OpenCreateAssetSetWizardAction; import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor; import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart; import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring; import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringWizard; import com.android.ide.eclipse.adt.internal.resources.ResourceHelper; import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator; import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager; import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData; import com.android.resources.ResourceType; import com.android.utils.Pair; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.window.Window; import org.eclipse.ltk.ui.refactoring.RefactoringWizard; import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.AbstractElementListSelectionDialog; import org.eclipse.ui.dialogs.SelectionStatusDialog; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A dialog to let the user select a resource based on a resource type. */ public class ResourceChooser extends AbstractElementListSelectionDialog implements ModifyListener { /** The return code from the dialog for the user choosing "Clear" */ public static final int CLEAR_RETURN_CODE = -5; /** The dialog button ID for the user choosing "Clear" */ private static final int CLEAR_BUTTON_ID = CLEAR_RETURN_CODE; private Pattern mProjectResourcePattern; private ResourceType mResourceType; private final ResourceRepository mProjectResources; private final ResourceRepository mFrameworkResources; private Pattern mSystemResourcePattern; private Button mProjectButton; private Button mSystemButton; private Button mNewButton; private String mCurrentResource; private final IProject mProject; private IInputValidator mInputValidator; /** Helper object used to draw previews for drawables and colors. */ private ResourcePreviewHelper mPreviewHelper; /** * Textfield for editing the actual returned value, updated when selection * changes. Only shown if {@link #mShowValueText} is true. */ private Text mEditValueText; /** * Whether the {@link #mEditValueText} textfield should be shown when the dialog is created. */ private boolean mShowValueText; /** * Flag indicating whether it's the first time {@link #handleSelectionChanged()} is called. * This is used to filter out the first selection event, always called by the superclass * when the widget is created, to distinguish between "the dialog was created" and * "the user clicked on a selection result", since only the latter should wipe out the * manual user edit shown in the value text. */ private boolean mFirstSelect = true; /** * Label used to show the resolved value in the resource chooser. Only shown * if the {@link #mResourceResolver} field is set. */ private Label mResolvedLabel; /** Resource resolver used to show actual values for resources selected. (Optional). */ private ResourceResolver mResourceResolver; /** * Creates a Resource Chooser dialog. * @param project Project being worked on * @param type The type of the resource to choose * @param projectResources The repository for the project * @param frameworkResources The Framework resource repository * @param parent the parent shell */ public ResourceChooser(IProject project, ResourceType type, ResourceRepository projectResources, ResourceRepository frameworkResources, Shell parent) { super(parent, new ResourceLabelProvider()); mProject = project; mResourceType = type; mProjectResources = projectResources; mFrameworkResources = frameworkResources; mProjectResourcePattern = Pattern.compile( PREFIX_RESOURCE_REF + mResourceType.getName() + "/(.+)"); //$NON-NLS-1$ mSystemResourcePattern = Pattern.compile( ANDROID_PREFIX + mResourceType.getName() + "/(.+)"); //$NON-NLS-1$ setTitle("Resource Chooser"); setMessage(String.format("Choose a %1$s resource", mResourceType.getDisplayName().toLowerCase(Locale.US))); } /** * Sets whether this dialog should show the value field as a separate text * value (and take the resulting value of the dialog from this text field * rather than from the selection) * * @param showValueText if true, show the value text field */ public void setShowValueText(boolean showValueText) { mShowValueText = showValueText; } /** * Sets the resource resolver to use to show resolved values for the current * selection * * @param resourceResolver the resource resolver to use */ public void setResourceResolver(ResourceResolver resourceResolver) { mResourceResolver = resourceResolver; } /** * Sets the {@link ResourcePreviewHelper} to use to preview drawable * resources, if any * * @param previewHelper the helper to use */ public void setPreviewHelper(ResourcePreviewHelper previewHelper) { mPreviewHelper = previewHelper; } @Override public void create() { super.create(); if (mShowValueText) { mEditValueText.selectAll(); mEditValueText.setFocus(); } } @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, CLEAR_BUTTON_ID, "Clear", false /*defaultButton*/); super.createButtonsForButtonBar(parent); } @Override protected void buttonPressed(int buttonId) { super.buttonPressed(buttonId); if (buttonId == CLEAR_BUTTON_ID) { assert CLEAR_RETURN_CODE != Window.OK && CLEAR_RETURN_CODE != Window.CANCEL; setReturnCode(CLEAR_RETURN_CODE); close(); } } public void setCurrentResource(String resource) { mCurrentResource = resource; if (mShowValueText && mEditValueText != null) { mEditValueText.setText(resource); } } public String getCurrentResource() { return mCurrentResource; } public void setInputValidator(IInputValidator inputValidator) { mInputValidator = inputValidator; } @Override protected void computeResult() { if (mShowValueText) { mCurrentResource = mEditValueText.getText(); if (mCurrentResource.length() == 0) { mCurrentResource = null; } return; } computeResultFromSelection(); } private void computeResultFromSelection() { if (getSelectionIndex() == -1) { mCurrentResource = null; return; } Object[] elements = getSelectedElements(); if (elements.length == 1 && elements[0] instanceof ResourceItem) { ResourceItem item = (ResourceItem)elements[0]; mCurrentResource = item.getXmlString(mResourceType, mSystemButton.getSelection()); if (mInputValidator != null && mInputValidator.isValid(mCurrentResource) != null) { mCurrentResource = null; } } } @Override protected Control createDialogArea(Composite parent) { Composite top = (Composite)super.createDialogArea(parent); createMessageArea(top); createButtons(top); createFilterText(top); createFilteredList(top); // create the "New Resource" button createNewResButtons(top); // Optionally create the value text field, if {@link #mShowValueText} is true createValueField(top); setupResourceList(); selectResourceString(mCurrentResource); return top; } /** * Creates the radio button to switch between project and system resources. * @param top the parent composite */ private void createButtons(Composite top) { mProjectButton = new Button(top, SWT.RADIO); mProjectButton.setText("Project Resources"); mProjectButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); if (mProjectButton.getSelection()) { // Clear selection before changing the list contents. This works around // a bug in the superclass where switching to the framework resources, // choosing one of the last resources, then switching to the project // resources would cause an exception when calling getSelection() because // selection state doesn't get cleared when we set new contents on // the filtered list. fFilteredList.setSelection(new int[0]); setupResourceList(); updateNewButton(false /*isSystem*/); updateValue(); } } }); mSystemButton = new Button(top, SWT.RADIO); mSystemButton.setText("System Resources"); mSystemButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); if (mSystemButton.getSelection()) { fFilteredList.setSelection(new int[0]); setupResourceList(); updateNewButton(true /*isSystem*/); updateValue(); } } }); } /** * Creates the "New Resource" button. * @param top the parent composite */ private void createNewResButtons(Composite top) { mNewButton = new Button(top, SWT.NONE); String title = String.format("New %1$s...", mResourceType.getDisplayName()); if (mResourceType == ResourceType.DRAWABLE) { title = "Create New Icon..."; } mNewButton.setText(title); mNewButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { super.widgetSelected(e); if (mResourceType == ResourceType.STRING) { // Special case: Use Extract String refactoring wizard UI String newName = createNewString(); selectAddedItem(newName); } else if (mResourceType == ResourceType.DRAWABLE) { // Special case: Use the "Create Icon Set" wizard OpenCreateAssetSetWizardAction action = new OpenCreateAssetSetWizardAction(mProject); action.run(); List<IResource> files = action.getCreatedFiles(); if (files != null && files.size() > 0) { String newName = AdtUtils.stripAllExtensions(files.get(0).getName()); // Recompute the "current resource" to select the new id ResourceItem[] items = setupResourceList(); selectItemName(newName, items); } } else { if (ResourceHelper.isValueBasedResourceType(mResourceType)) { String newName = createNewValue(mResourceType); if (newName != null) { selectAddedItem(newName); } } else { String newName = createNewFile(mResourceType); if (newName != null) { selectAddedItem(newName); } } } } private void selectAddedItem(@NonNull String newName) { // Recompute the "current resource" to select the new id ResourceItem[] items = setupResourceList(); // Ensure that the name is in the list. There's a delay after // an item is added (until the builder runs and processes the delta) // so if it's not in the list, add it boolean found = false; for (ResourceItem item : items) { if (newName.equals(item.getName())) { found = true; break; } } if (!found) { ResourceItem[] newItems = new ResourceItem[items.length + 1]; System.arraycopy(items, 0, newItems, 0, items.length); newItems[items.length] = new ResourceItem(newName); items = newItems; Arrays.sort(items); setListElements(items); fFilteredList.setEnabled(newItems.length > 0); } selectItemName(newName, items); } }); } /** * Creates the value text field. * * @param top the parent composite */ private void createValueField(Composite top) { if (mShowValueText) { mEditValueText = new Text(top, SWT.BORDER); if (mCurrentResource != null) { mEditValueText.setText(mCurrentResource); } mEditValueText.addModifyListener(this); GridData data = new GridData(); data.grabExcessVerticalSpace = false; data.grabExcessHorizontalSpace = true; data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.BEGINNING; mEditValueText.setLayoutData(data); mEditValueText.setFont(top.getFont()); } if (mResourceResolver != null) { mResolvedLabel = new Label(top, SWT.NONE); GridData data = new GridData(); data.grabExcessVerticalSpace = false; data.grabExcessHorizontalSpace = true; data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.BEGINNING; mResolvedLabel.setLayoutData(data); } } private void updateResolvedLabel() { if (mResourceResolver == null) { return; } String v = null; if (mCurrentResource != null) { v = mCurrentResource; if (mCurrentResource.startsWith(PREFIX_RESOURCE_REF)) { ResourceValue value = mResourceResolver.findResValue(mCurrentResource, false); if (value != null) { v = value.getValue(); } } } if (v == null) { v = ""; } mResolvedLabel.setText(String.format("Resolved Value: %1$s", v)); } @Override protected void handleSelectionChanged() { super.handleSelectionChanged(); if (mInputValidator != null) { Object[] elements = getSelectedElements(); if (elements.length == 1 && elements[0] instanceof ResourceItem) { ResourceItem item = (ResourceItem)elements[0]; String current = item.getXmlString(mResourceType, mSystemButton.getSelection()); String error = mInputValidator.isValid(current); IStatus status; if (error != null) { status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, error); } else { status = new Status(IStatus.OK, AdtPlugin.PLUGIN_ID, null); } updateStatus(status); } } updateValue(); } private void updateValue() { if (mPreviewHelper != null) { computeResult(); mPreviewHelper.updatePreview(mResourceType, mCurrentResource); } if (mShowValueText) { if (mFirstSelect) { mFirstSelect = false; mEditValueText.selectAll(); } else { computeResultFromSelection(); mEditValueText.setText(mCurrentResource != null ? mCurrentResource : ""); } } if (mResourceResolver != null) { if (!mShowValueText) { computeResultFromSelection(); } updateResolvedLabel(); } } @Nullable private String createNewFile(ResourceType type) { // Show a name/value dialog entering the key name and the value Shell shell = AdtPlugin.getDisplay().getActiveShell(); if (shell == null) { return null; } ResourceNameValidator validator = ResourceNameValidator.create(true /*allowXmlExtension*/, mProject, mResourceType); InputDialog d = new InputDialog( AdtPlugin.getDisplay().getActiveShell(), "Enter name", // title "Enter name", "", //$NON-NLS-1$ validator); if (d.open() == Window.OK) { String name = d.getValue().trim(); if (name.length() == 0) { return null; } Pair<IFile, IRegion> resource = ResourceHelper.createResource(mProject, type, name, null); if (resource != null) { return name; } } return null; } @Nullable private String createNewValue(ResourceType type) { // Show a name/value dialog entering the key name and the value Shell shell = AdtPlugin.getDisplay().getActiveShell(); if (shell == null) { return null; } NameValueDialog dialog = new NameValueDialog(shell, getFilter()); if (dialog.open() != Window.OK) { return null; } String name = dialog.getName(); String value = dialog.getValue(); if (name.length() == 0 || value.length() == 0) { return null; } Pair<IFile, IRegion> resource = ResourceHelper.createResource(mProject, type, name, value); if (resource != null) { return name; } return null; } private String createNewString() { ExtractStringRefactoring ref = new ExtractStringRefactoring( mProject, true /*enforceNew*/); RefactoringWizard wizard = new ExtractStringWizard(ref, mProject); RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard); try { IWorkbench w = PlatformUI.getWorkbench(); if (op.run(w.getDisplay().getActiveShell(), wizard.getDefaultPageTitle()) == IDialogConstants.OK_ID) { return ref.getXmlStringId(); } } catch (InterruptedException ex) { // Interrupted. Pass. } return null; } /** * Setups the current list. */ private ResourceItem[] setupResourceList() { Collection<ResourceItem> items = null; if (mProjectButton.getSelection()) { items = mProjectResources.getResourceItemsOfType(mResourceType); } else if (mSystemButton.getSelection()) { items = mFrameworkResources.getResourceItemsOfType(mResourceType); } if (items == null) { items = Collections.emptyList(); } ResourceItem[] arrayItems = items.toArray(new ResourceItem[items.size()]); // sort the array Arrays.sort(arrayItems); setListElements(arrayItems); fFilteredList.setEnabled(arrayItems.length > 0); return arrayItems; } /** * Select an item by its name, if possible. */ private void selectItemName(String itemName, ResourceItem[] items) { if (itemName == null || items == null) { return; } for (ResourceItem item : items) { if (itemName.equals(item.getName())) { setSelection(new Object[] { item }); break; } } } /** * Select an item by its full resource string. * This also selects between project and system repository based on the resource string. */ private void selectResourceString(String resourceString) { boolean isSystem = false; String itemName = null; if (resourceString != null) { // Is this a system resource? // If not a system resource or if they are not available, this will be a project res. Matcher m = mSystemResourcePattern.matcher(resourceString); if (m.matches()) { itemName = m.group(1); isSystem = true; } if (!isSystem && itemName == null) { // Try to match project resource name m = mProjectResourcePattern.matcher(resourceString); if (m.matches()) { itemName = m.group(1); } } } // Update the repository selection mProjectButton.setSelection(!isSystem); mSystemButton.setSelection(isSystem); updateNewButton(isSystem); // Update the list ResourceItem[] items = setupResourceList(); // If we have a selection name, select it if (itemName != null) { selectItemName(itemName, items); } } private void updateNewButton(boolean isSystem) { mNewButton.setEnabled(!isSystem && ResourceHelper.canCreateResourceType(mResourceType)); } // ---- Implements ModifyListener ---- @Override public void modifyText(ModifyEvent e) { if (e.getSource() == mEditValueText && mResourceResolver != null) { mCurrentResource = mEditValueText.getText(); if (mCurrentResource.startsWith(PREFIX_RESOURCE_REF)) { if (mProjectResourcePattern.matcher(mCurrentResource).matches() || mSystemResourcePattern.matcher(mCurrentResource).matches()) { updateResolvedLabel(); } } else { updateResolvedLabel(); } } } /** Dialog asking for a Name/Value pair */ private class NameValueDialog extends SelectionStatusDialog implements Listener { private org.eclipse.swt.widgets.Text mNameText; private org.eclipse.swt.widgets.Text mValueText; private String mInitialName; private String mName; private String mValue; private ResourceNameValidator mValidator; public NameValueDialog(Shell parent, String initialName) { super(parent); mInitialName = initialName; } @Override protected Control createDialogArea(Composite parent) { Composite container = new Composite(parent, SWT.NONE); container.setLayout(new GridLayout(2, false)); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); // Wide enough to accommodate the error label gridData.widthHint = 500; container.setLayoutData(gridData); Label nameLabel = new Label(container, SWT.NONE); nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); nameLabel.setText("Name:"); mNameText = new org.eclipse.swt.widgets.Text(container, SWT.BORDER); mNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); if (mInitialName != null) { mNameText.setText(mInitialName); mNameText.selectAll(); } Label valueLabel = new Label(container, SWT.NONE); valueLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); valueLabel.setText("Value:"); mValueText = new org.eclipse.swt.widgets.Text(container, SWT.BORDER); mValueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); mNameText.addListener(SWT.Modify, this); mValueText.addListener(SWT.Modify, this); validate(); return container; } @Override protected void computeResult() { mName = mNameText.getText().trim(); mValue = mValueText.getText().trim(); } private String getName() { return mName; } private String getValue() { return mValue; } @Override public void handleEvent(Event event) { validate(); } private void validate() { IStatus status; computeResult(); if (mName.length() == 0) { status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Enter a name"); } else if (mValue.length() == 0) { status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Enter a value"); } else { if (mValidator == null) { mValidator = ResourceNameValidator.create(false, mProject, mResourceType); } String error = mValidator.isValid(mName); if (error != null) { status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, error); } else { status = new Status(IStatus.OK, AdtPlugin.PLUGIN_ID, null); } } updateStatus(status); } } /** * Open the resource chooser for the given type, associated with the given * editor * * @param graphicalEditor the editor associated with the resource to be * chosen (used to find the associated Android target to be used * for framework resources etc) * @param type the resource type to be chosen * @param currentValue the current value, or null * @param validator a validator to be used, or null * @return the chosen resource, null if cancelled and "" if value should be * cleared */ public static String chooseResource( @NonNull GraphicalEditorPart graphicalEditor, @NonNull ResourceType type, String currentValue, IInputValidator validator) { AndroidXmlEditor editor = graphicalEditor.getEditorDelegate().getEditor(); IProject project = editor.getProject(); if (project != null) { // get the resource repository for this project and the system resources. ResourceRepository projectRepository = ResourceManager.getInstance() .getProjectResources(project); Shell shell = AdtPlugin.getDisplay().getActiveShell(); if (shell == null) { return null; } AndroidTargetData data = editor.getTargetData(); ResourceRepository systemRepository = data.getFrameworkResources(); // open a resource chooser dialog for specified resource type. ResourceChooser dlg = new ResourceChooser(project, type, projectRepository, systemRepository, shell); dlg.setPreviewHelper(new ResourcePreviewHelper(dlg, graphicalEditor)); // When editing Strings, allow editing the value text directly. When we // get inline editing support (where values entered directly into the // textual widget are translated automatically into a resource) this can // go away. if (type == ResourceType.STRING) { dlg.setResourceResolver(graphicalEditor.getResourceResolver()); dlg.setShowValueText(true); } else if (type == ResourceType.DIMEN || type == ResourceType.INTEGER) { dlg.setResourceResolver(graphicalEditor.getResourceResolver()); } if (validator != null) { // Ensure wide enough to accommodate validator error message dlg.setSize(85, 10); dlg.setInputValidator(validator); } dlg.setCurrentResource(currentValue); int result = dlg.open(); if (result == ResourceChooser.CLEAR_RETURN_CODE) { return ""; //$NON-NLS-1$ } else if (result == Window.OK) { return dlg.getCurrentResource(); } } return null; } }
gpl-2.0
rex-xxx/mt6572_x201
packages/apps/Contacts/src/com/android/contacts/util/PhoneNumberFormatter.java
4012
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.util; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.telephony.PhoneNumberFormattingTextWatcher; import android.text.Editable; import android.widget.TextView; import com.android.contacts.ContactsUtils; public final class PhoneNumberFormatter { private PhoneNumberFormatter() {} /** * Load {@link TextWatcherLoadAsyncTask} in a worker thread and set it to a {@link TextView}. */ private static class TextWatcherLoadAsyncTask extends AsyncTask<Void, Void, PhoneNumberFormattingTextWatcher> { private final String mCountryCode; private final TextView mTextView; private final Handler mHandler; private static final int MSG_GET_TEXT_WATCHER = 1; public TextWatcherLoadAsyncTask(String countryCode, TextView textView, Handler handler) { mCountryCode = countryCode; mTextView = textView; mHandler = handler; } @Override protected PhoneNumberFormattingTextWatcher doInBackground(Void... params) { return new PhoneNumberFormattingTextWatcherEx(mCountryCode); } @Override protected void onPostExecute(PhoneNumberFormattingTextWatcher watcher) { if (watcher == null || isCancelled()) { return; // May happen if we cancel the task. } // Setting a text changed listener is safe even after the view is detached. mTextView.addTextChangedListener(watcher); if (null != mHandler){ Message msg = mHandler.obtainMessage(MSG_GET_TEXT_WATCHER); msg.obj = watcher; mHandler.sendMessage(msg); } // Note changes the user made before onPostExecute() will not be formatted, but // once they type the next letter we format the entire text, so it's not a big deal. // (And loading PhoneNumberFormattingTextWatcher is usually fast enough.) // We could use watcher.afterTextChanged(mTextView.getEditableText()) to force format // the existing content here, but that could cause unwanted results. // (e.g. the contact editor thinks the user changed the content, and would save // when closed even when the user didn't make other changes.) } } /** * Delay-set {@link PhoneNumberFormattingTextWatcher} to a {@link TextView}. */ public static final void setPhoneNumberFormattingTextWatcher(Context context, TextView textView, Handler handler) { new TextWatcherLoadAsyncTask(ContactsUtils.getCurrentCountryIso(context), textView, handler) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); } public static class PhoneNumberFormattingTextWatcherEx extends PhoneNumberFormattingTextWatcher { protected static boolean mSelfChanged = false; protected PhoneNumberFormattingTextWatcherEx() {} PhoneNumberFormattingTextWatcherEx(String countryCode){ super(countryCode); } public void afterTextChanged(Editable s) { mSelfChanged = true; super.afterTextChanged(s); mSelfChanged = false; } } }
gpl-2.0
knightliao/common-utils
src/main/java/com/baidu/unbiz/common/division/DivisionException.java
603
package com.baidu.unbiz.common.division; /** * * @author <a href="mailto:xuchen06@baidu.com">xuc</a> * @version create on 2014年9月16日 上午3:58:38 */ public class DivisionException extends Exception { /** * */ private static final long serialVersionUID = -693227965893118092L; public DivisionException() { super(); } public DivisionException(String msg) { super(msg); } public DivisionException(Throwable cause) { super(cause); } public DivisionException(String msg, Throwable cause) { super(msg, cause); } }
gpl-2.0
simensma/GroupRec
WebAppBackend/grec/src/main/java/edu/ntnu/grouprec/business/providers/VenueProvider.java
355
package edu.ntnu.grouprec.business.providers; import java.util.List; import edu.ntnu.grouprec.dataccess.mysql.VenueAccess; public class VenueProvider { private VenueAccess va; public VenueProvider(VenueAccess va) { this.va = va; } public List<String> getLocations(int limit) { return va.getLocations(limit); } }
gpl-2.0
alejandropg/tutorial-oauth2
rest/src/systemTest/java/com/autentia/app/domain/web/rest/agent/UserAgent.java
3162
package com.autentia.app.domain.web.rest.agent; import com.jayway.restassured.RestAssured; import static com.jayway.restassured.RestAssured.*; import static com.jayway.restassured.http.ContentType.HTML; import static com.jayway.restassured.http.ContentType.JSON; import static java.net.HttpURLConnection.HTTP_MOVED_TEMP; import static java.net.HttpURLConnection.HTTP_OK; import static org.hamcrest.Matchers.*; public class UserAgent extends Agent { public void authenticate() { getLoginForm(); postCredentials(); } private void getLoginForm() { // @formatter:off given() .filter(sessionFilter) .when() .get("/login") .then() .statusCode(HTTP_OK) .contentType(containsString(HTML.toString())) .body(containsString("username"), containsString("password")) ; // @formatter:on } private void postCredentials() { // @formatter:off given() .filter(sessionFilter) .param("username", "user1") .param("password", "user1") .when() .post("/login") .then() .statusCode(HTTP_MOVED_TEMP) .header("Location", "http://localhost:" + RestAssured.port +"/") ; // @formatter:on } public String requestsAuthorizationCodeGrant(String clientState) { requestsAuthorizationForClient("code", "client", clientState, "http://anywhere"); return giveScopesApprovalForClient(); } public String requestsImplicitGrant(String clientState) { requestsAuthorizationForClient("token", "client-implicit", clientState, "http://registered-to-anywhere"); return giveScopesApprovalForClient(); } private void requestsAuthorizationForClient(String responseType, String client_id, String clientState, String clientRedirectUri) { // @formatter:off given() .header(ACCEPT_JSON) .filter(sessionFilter) .param("response_type", responseType) .param("client_id", client_id) .param("redirect_uri", clientRedirectUri) .param("scope", "read") .param("state", clientState) .when() .post("/oauth/authorize") .then() .statusCode(HTTP_OK) .contentType(containsString(JSON.toString())) .body("state", is(clientState)) .body("redirect_uri", is(clientRedirectUri)) ; // @formatter:on } private String giveScopesApprovalForClient() { // @formatter:off return given() .filter(sessionFilter) .param("user_oauth_approval", "true") .param("scope.read", "true") .when() .post("/oauth/authorize") .then() .statusCode(HTTP_MOVED_TEMP) .header("Location", not(isEmptyOrNullString())) .extract() .header("Location") ; // @formatter:on } }
gpl-2.0
claresco/Tinman
src/com/claresco/tinman/servlet/XapiBadParamException.java
703
/** * Copyright (c) 1999, 2014 Claresco Corporation, Berkeley, California. All rights reserved. * * * XapiBadParamException.java May 15, 2014 * * Copyright 2014 Claresco Corporation, Berkeley, CA 94704. All Rights Reserved. * * This software is the proprietary information of Claresco Corporation. * Use is subject to license terms. * * Author : Rheza * */ package com.claresco.tinman.servlet; /** * XapiBadParamException * @author Rheza * * Description: * * * Status: * * */ public class XapiBadParamException extends XapiServletException { /** * Constructor * * Params: * * */ public XapiBadParamException(String theMessage) { super(400, theMessage); } }
gpl-2.0
hawk23/bomberman
src/prototype/BombTest.java
1748
package prototype; import game.debug.Debugger; import org.newdawn.slick.*; import org.newdawn.slick.Graphics; import slick.extension.ExplosionSystem; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Roland Schreier on 31.03.2015. */ public class BombTest extends BasicGame { public static final int GAME_WIDTH = 1280; public static final int GAME_HEIGHT = 960; public static final String GAME_NAME = "BombTester"; private ExplosionSystem explosionSystem; public BombTest(String title) { super(title); } public static void main(String[] args) { try { AppGameContainer appgc; appgc = new AppGameContainer(new BombTest(GAME_NAME)); appgc.setDisplayMode(GAME_WIDTH, GAME_HEIGHT, false); appgc.start(); } catch (SlickException ex) { Logger.getLogger(BombTest.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void render(GameContainer gameContainer, Graphics graphics) throws SlickException { explosionSystem.render(gameContainer, null, graphics); } @Override public void update(GameContainer gameContainer, int delta) throws SlickException { explosionSystem.update(gameContainer, null, delta); } @Override public void init(GameContainer gameContainer) throws SlickException { explosionSystem = new ExplosionSystem(); } @Override public void mouseMoved(int oldx, int oldy, int newx, int newy) { } @Override public void mousePressed(int button, int posX, int posY){ Debugger.log("Added Explosion ("+posX+","+posY+")"); //explosionSystem.addExplosion(posX,posY); } }
gpl-2.0
a-iv/jmc
src/jmc/GatewayForm.java
8662
/** * 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 Library 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 jmc; import util.Datas; import util.Contents; import jabber.subscription.*; import java.util.Vector; //import javax.microedition.lcdui.Button; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.Form; /*import javax.microedition.lcdui.Container; import javax.microedition.lcdui.Dialog; import javax.microedition.lcdui.Label; import javax.microedition.lcdui.TextArea; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.events.ActionEvent; import javax.microedition.lcdui.events.ActionListener; import javax.microedition.lcdui.layouts.BoxLayout; import javax.microedition.lcdui.layouts.GridLayout; import javax.microedition.lcdui.plaf.Border; */ /** * Screen for the gateway registration * @author Gabriele Bianchi * */ public class GatewayForm extends Form /*implements ActionListener*/ { private GuiMidlet midlet; private Vector services; /* public TextArea gateway = new TextArea("", 64); // "Gateway hostname:", public TextArea address = new TextArea("ex: myuser@hotmail.com", 1, 64, TextArea.EMAILADDR); // "User:", public TextArea password = new TextArea("", 1, 32, TextArea.PASSWORD); // "Password:", */ //public ButtonGroup choice = new ButtonGroup();//("Choose IM protocol", ChoiceGroup.EXCLUSIVE, Contents.gtwChoices, null); public GatewayForm(GuiMidlet _midlet) { super("Gateway"); midlet = _midlet; services = Datas.server_services; //this.setLayout(new BoxLayout(BoxLayout.Y_AXIS)); configureFirstScreen(); } /** * Configure screen */ public void configureRegistration(String trans) { /* this.removeAll(); this.removeCommand(Contents.select); this.addComponent(new MyLabel("Gateway")); this.addComponent(gateway); gateway.setText(trans); this.addComponent(new MyLabel("username")); this.addComponent(address); this.addComponent(new MyLabel("password")); this.addComponent(password); if (trans.equals("")) { MyTextArea t = new MyTextArea("Cannot detect the gateway hostname. Go to 'Back'->'Server info'", 3, 100); this.addComponent(t); } this.addCommand(Contents.register); this.addCommand(Contents.unregister); //this.addCommand(Contents.back); this.setCommandListener(this); */ } /** * Configure screen */ public void configureFirstScreen() { /* //this.append(choice); Container cont = new Container(); int elementWidth = 0; ButtonActionListener action = new ButtonActionListener(this); for (int i=0; i< Contents.gtwChoices.length; i++) { //TODO: add image Button b = new Button(Contents.gtwChoices[i]); // ,img b.getStyle().setBgTransparency(0); b.getStyle().setBorder(Border.createLineBorder(1)); b.setAlignment(Label.CENTER); b.setTextPosition(Label.TOP); b.addActionListener(action); elementWidth = Math.max(b.getPreferredW(), elementWidth); cont.addComponent(b); } int cols = 2;//width / elementWidth; int rows = Contents.gtwChoices.length / cols; cont.setLayout(new GridLayout(rows, cols)); this.addComponent(cont); //this.append(address); MyTextArea t = new MyTextArea(Contents.explainGtw,0,100); t.setEnabled(true); t.setFocusable(true); this.addComponent(t); this.addCommand(Contents.select); this.addCommand(Contents.back); this.setCommandListener(this); */ } /** * Check if a gateway exists * @param serv */ public static boolean existGateway(Vector serv) { //check if Gateway exists for (int j = 0; j < serv.size(); j++) { String[] s = ((String[])serv.elementAt(j)); //String lab = ((StringItem)serv.elementAt(j)).getLabel(); if (s[1].indexOf("yahoo") != -1 || s[1].toLowerCase().indexOf("msn") != -1 || s[1].toLowerCase().indexOf("aim") != -1 || s[1].toLowerCase().indexOf("icq") != -1) { //Datas.gateways.addElement(s); return true; } if (s[0] != null && (s[0].toLowerCase().indexOf("yahoo") != -1 || s[0].toLowerCase().indexOf("msn") != -1 || s[0].toLowerCase().indexOf("aol") != -1 || s[0].toLowerCase().indexOf("icq") != -1)) { //Datas.gateways.addElement(s); return true; } } return false; } /** * Check if a single transport exists * @param serv */ public static String existTransport(Vector serv, String trans) { for (int j = 0; j < serv.size(); j++) { String s[] = ((String[])serv.elementAt(j)); //String lab = ((StringItem)serv.elementAt(j)).getLabel(); if (s[1].toLowerCase().indexOf(trans) != -1 ) { Datas.gateways.addElement(s[1]); return s[1]; } if (s[0] != null && s[0].toLowerCase().indexOf(trans) != -1 ) { Datas.gateways.addElement(s[0]); return s[0]; } } return ""; } /* public void actionPerformed(ActionEvent arg0) { Command cmd = arg0.getCommand(); if (cmd == Contents.back) { midlet.getGuiOtherOptions(); } else if (cmd == Contents.select) { Button b; try { b = (Button)this.getFocused(); } catch (Exception e) { // TODO Auto-generated catch block return; } String t = b.getText(); if (t.equals(Contents.gtwChoices[0])) { //MSN this.configureRegistration(existTransport(services,"msn")); }else if (t.equals(Contents.gtwChoices[1])) { this.configureRegistration(existTransport(services,"aim")); }else if (t.equals(Contents.gtwChoices[2])) { this.configureRegistration(existTransport(services,"icq")); }else if (t.equals(Contents.gtwChoices[3])) { this.configureRegistration(existTransport(services,"yahoo")); } } else if (cmd == Contents.register) { String gtw = gateway.getText(); //boolean go = false; if (gtw.equals("")) { this.show(); return; } for (int i = 0; i < services.size(); i++) { String lab[] = ((String[])services.elementAt(i)); if (gateway.getText().equals(lab[1])) { Subscribe.registerGateway(address.getText(), password.getText(), gtw); Dialog.show("", Contents.done, null, Dialog.TYPE_CONFIRMATION,null, 3000); midlet.getGuiOtherOptions(); return; } } Dialog.show("", Contents.noGtw, null, Dialog.TYPE_ERROR,null, 3000); return; } else if (cmd == Contents.unregister) { String gtw = gateway.getText(); if (gtw.equals("")) { this.show(); return; } //StringItem item; for (int i = 0; i < services.size(); i++) { String[] item = (String[])services.elementAt(i); if (gateway.getText().equals(item[1])) { Subscribe.unregisterGateway(gtw); Dialog.show("", Contents.done, null, Dialog.TYPE_CONFIRMATION,null, 3000); midlet.getGuiOtherOptions(); return; } } Dialog.show("", Contents.noGtw, null, Dialog.TYPE_ERROR,null, 3000); //midlet.display.setCurrent(Contents.noGtw, this); return; } } private class ButtonActionListener implements ActionListener { private GatewayForm form; public ButtonActionListener(GatewayForm f) { form = f; } public void actionPerformed(ActionEvent evt) { Button b = (Button)evt.getSource(); String t = b.getText(); if (t.equals(Contents.gtwChoices[0])) { //MSN form.configureRegistration(existTransport(services,"msn")); }else if (t.equals(Contents.gtwChoices[1])) { form.configureRegistration(existTransport(services,"aim")); }else if (t.equals(Contents.gtwChoices[2])) { form.configureRegistration(existTransport(services,"icq")); }else if (t.equals(Contents.gtwChoices[3])) { form.configureRegistration(existTransport(services,"yahoo")); } } } */ }
gpl-2.0
MisterTubbs/GLUtils
GLUtils/src/com/nishu/utils/Texture.java
3388
package com.nishu.utils; import static org.lwjgl.opengl.GL11.GL_CLAMP; import static org.lwjgl.opengl.GL11.GL_NEAREST; import static org.lwjgl.opengl.GL11.GL_RGBA; import static org.lwjgl.opengl.GL11.GL_RGBA8; import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; import static org.lwjgl.opengl.GL11.GL_TEXTURE_MAG_FILTER; import static org.lwjgl.opengl.GL11.GL_TEXTURE_MIN_FILTER; import static org.lwjgl.opengl.GL11.GL_TEXTURE_WRAP_S; import static org.lwjgl.opengl.GL11.GL_TEXTURE_WRAP_T; import static org.lwjgl.opengl.GL11.GL_UNSIGNED_BYTE; import static org.lwjgl.opengl.GL11.glBindTexture; import static org.lwjgl.opengl.GL11.glDeleteTextures; import static org.lwjgl.opengl.GL11.glEnable; import static org.lwjgl.opengl.GL11.glGenTextures; import static org.lwjgl.opengl.GL11.glTexImage2D; import static org.lwjgl.opengl.GL11.glTexParameteri; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.ByteBuffer; import javax.imageio.ImageIO; import org.lwjgl.BufferUtils; public class Texture { public int id; public int width; public int height; private Texture(int id, int width, int height) { this.id = id; this.width = width; this.height = height; } public static Texture loadTexture(String name) { // Load the image BufferedImage bimg = null; try { bimg = ImageIO.read(Texture.class.getClassLoader().getResourceAsStream(name)); } catch (IOException e) { System.out.println("Unable to load Texture: " + name); e.printStackTrace(); } // Gather all the pixels int[] pixels = new int[bimg.getWidth() * bimg.getHeight()]; bimg.getRGB(0, 0, bimg.getWidth(), bimg.getHeight(), pixels, 0, bimg.getWidth()); // Create a ByteBuffer ByteBuffer buffer = BufferUtils.createByteBuffer(bimg.getWidth() * bimg.getHeight() * 4); // Iterate through all the pixels and add them to the ByteBuffer for (int y = 0; y < bimg.getHeight(); y++) { for (int x = 0; x < bimg.getWidth(); x++) { // Select the pixel int pixel = pixels[y * bimg.getWidth() + x]; // Add the RED component buffer.put((byte) ((pixel >> 16) & 0xFF)); // Add the GREEN component buffer.put((byte) ((pixel >> 8) & 0xFF)); // Add the BLUE component buffer.put((byte) (pixel & 0xFF)); // Add the ALPHA component buffer.put((byte) ((pixel >> 24) & 0xFF)); } } // Reset the read location in the buffer so that GL can read from // beginning. buffer.flip(); // Generate a texture ID int textureID = glGenTextures(); // Bind the ID to the context glBindTexture(GL_TEXTURE_2D, textureID); // Send texture data to OpenGL glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, bimg.getWidth(), bimg.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); // Return a new Texture. return new Texture(textureID, bimg.getWidth(), bimg.getHeight()); } public static Texture createEmptyTexture(){ return new Texture(0, 0, 0); } public void bind(){ glEnable(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, id); } public void unbind(){ glBindTexture(GL_TEXTURE_2D, 0); } public void delete(){ glDeleteTextures(id); } }
gpl-2.0
dlitz/resin
modules/resin/src/com/caucho/env/deploy/AbstractDeployInstance.java
3116
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.env.deploy; import java.util.logging.Logger; /** * The abstract deployment instance represents a deployed service like * a WebApp or a Host. The instrance works with the controller to handle * dynamic deployment. */ abstract public class AbstractDeployInstance implements DeployInstance { private ClassLoader _classLoader; private Throwable _configException; protected AbstractDeployInstance() { _classLoader = Thread.currentThread().getContextClassLoader(); } /** * Returns the deployment class loader. */ @Override public ClassLoader getClassLoader() { return _classLoader; } /** * The deployment class loader. */ protected void setClassLoader(ClassLoader classLoader) { _classLoader = classLoader; } /** * Returns true if the deployment is modified. */ @Override public boolean isModified() { return isModifiedNow(); } /** * Returns true if the deployment is modified, forcing a check. */ @Override public boolean isModifiedNow() { return false; } /** * Logs the reason for modification */ @Override public boolean logModified(Logger log) { return false; } /** * Returns true if the deployment is modified for the timer redeploy. */ /* @Override public boolean isDeployError() { return false; } */ /** * Returns true if the deployment can be removed. */ @Override public boolean isDeployIdle() { return false; } /** * Sets the configuration exception. */ @Override public void setConfigException(Throwable e) { _configException = e; } /** * Gets the configuration exception. */ @Override public Throwable getConfigException() { return _configException; } /** * Starts the deployment instance */ @Override public void start() { } /** * Destroys the deployment instance */ @Override public void destroy() { } @Override public String toString() { return getClass().getSimpleName() + "[]"; } }
gpl-2.0
MyCATApache/Mycat-Server
src/test/java/io/mycat/performance/TravelRecordSelectJob.java
4178
/* * Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. 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. * * 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. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.performance; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; public class TravelRecordSelectJob implements Runnable ,SelectJob{ private final Connection con; private final long minId; private final long maxId; private final int executeTimes; Random random = new Random(); private final AtomicInteger finshiedCount; private final AtomicInteger failedCount; private volatile long usedTime; private volatile long success; private volatile long maxTTL = 0; private volatile long minTTL = Integer.MAX_VALUE; private volatile long validTTLSum = 0; private volatile long validTTLCount = 0; public TravelRecordSelectJob(Connection con, long minId, long maxId, int executeTimes, AtomicInteger finshiedCount, AtomicInteger failedCount) { super(); this.con = con; this.minId = minId; this.maxId = maxId; this.executeTimes = executeTimes; this.finshiedCount = finshiedCount; this.failedCount = failedCount; } private long select() { ResultSet rs = null; long used = -1; try { String sql = "select * from travelrecord where id=" + ((Math.abs(random.nextLong()) % (maxId - minId)) + minId); long startTime = System.currentTimeMillis(); rs = con.createStatement().executeQuery(sql); if (rs.next()) { } used = System.currentTimeMillis() - startTime; finshiedCount.addAndGet(1); success++; } catch (Exception e) { failedCount.addAndGet(1); e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return used; } @Override public void run() { long curmaxTTL = this.maxTTL; long curminTTL = this.minTTL; long curvalidTTLSum = this.validTTLSum; long curvalidTTLCount = this.validTTLCount; long start = System.currentTimeMillis(); for (int i = 0; i < executeTimes; i++) { long ttlTime = this.select(); if (ttlTime != -1) { if (ttlTime > curmaxTTL) { curmaxTTL = ttlTime; } else if (ttlTime < curminTTL) { curminTTL = ttlTime; } curvalidTTLSum += ttlTime; curvalidTTLCount += 1; } usedTime = System.currentTimeMillis() - start; } maxTTL = curmaxTTL; minTTL = curminTTL; validTTLSum = curvalidTTLSum; validTTLCount = curvalidTTLCount; try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } public long getUsedTime() { return this.usedTime; } public double getTPS() { if (usedTime > 0) { return (this.success * 1000+0.0) / this.usedTime; } else { return 0; } } public long getMaxTTL() { return maxTTL; } public long getMinTTL() { return minTTL; } public long getValidTTLSum() { return validTTLSum; } public long getValidTTLCount() { return validTTLCount; } public static void main(String[] args) { Random r = new Random(); for (int i = 0; i < 10; i++) { int f = r.nextInt(90000 - 80000) + 80000; System.out.println(f); } } }
gpl-2.0
Tsux/GeneralTest
bin/src/test/java/org/ektqa/webdriver/switchBus/TestSwitchGeneric.java
289
package org.ektqa.webdriver.switchBus; import org.ektqa.webdriver.common.WebDriverTestIndividualSwitch; import org.testng.annotations.Test; public class TestSwitchGeneric extends WebDriverTestIndividualSwitch{ @Test public void firstSwitchTest(){ //test logic code } }
gpl-2.0
dain/graal
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/DeoptimizingFixedWithNextNode.java
1815
/* * Copyright (c) 2013, 2014, 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. * * 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 com.oracle.graal.nodes; import com.oracle.graal.compiler.common.type.*; import com.oracle.graal.graph.*; public abstract class DeoptimizingFixedWithNextNode extends FixedWithNextNode implements DeoptimizingNode.DeoptBefore { @OptionalInput(InputType.State) private FrameState stateBefore; public DeoptimizingFixedWithNextNode(Stamp stamp) { super(stamp); } public DeoptimizingFixedWithNextNode(Stamp stamp, FrameState stateBefore) { super(stamp); this.stateBefore = stateBefore; } @Override public FrameState stateBefore() { return stateBefore; } @Override public void setStateBefore(FrameState f) { updateUsages(stateBefore, f); stateBefore = f; } }
gpl-2.0
FauxFaux/jdk9-jdk
src/java.base/share/classes/java/lang/invoke/MethodHandles.java
273472
/* * Copyright (c) 2008, 2016, 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.invoke; import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.Opcodes; import jdk.internal.reflect.CallerSensitive; import jdk.internal.reflect.Reflection; import jdk.internal.vm.annotation.ForceInline; import sun.invoke.util.ValueConversions; import sun.invoke.util.VerifyAccess; import sun.invoke.util.Wrapper; import sun.reflect.misc.ReflectUtil; import sun.security.util.SecurityConstants; import java.lang.invoke.LambdaForm.BasicType; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ReflectPermission; import java.nio.ByteOrder; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.lang.invoke.MethodHandleImpl.Intrinsic; import static java.lang.invoke.MethodHandleNatives.Constants.*; import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; import static java.lang.invoke.MethodType.methodType; /** * This class consists exclusively of static methods that operate on or return * method handles. They fall into several categories: * <ul> * <li>Lookup methods which help create method handles for methods and fields. * <li>Combinator methods, which combine or transform pre-existing method handles into new ones. * <li>Other factory methods to create method handles that emulate other common JVM operations or control flow patterns. * </ul> * * @author John Rose, JSR 292 EG * @since 1.7 */ public class MethodHandles { private MethodHandles() { } // do not instantiate static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); // See IMPL_LOOKUP below. //// Method handle creation from ordinary methods. /** * Returns a {@link Lookup lookup object} with * full capabilities to emulate all supported bytecode behaviors of the caller. * These capabilities include <a href="MethodHandles.Lookup.html#privacc">private access</a> to the caller. * Factory methods on the lookup object can create * <a href="MethodHandleInfo.html#directmh">direct method handles</a> * for any member that the caller has access to via bytecodes, * including protected and private fields and methods. * This lookup object is a <em>capability</em> which may be delegated to trusted agents. * Do not store it in place where untrusted code can access it. * <p> * This method is caller sensitive, which means that it may return different * values to different callers. * <p> * For any given caller class {@code C}, the lookup object returned by this call * has equivalent capabilities to any lookup object * supplied by the JVM to the bootstrap method of an * <a href="package-summary.html#indyinsn">invokedynamic instruction</a> * executing in the same caller class {@code C}. * @return a lookup object for the caller of this method, with private access */ @CallerSensitive @ForceInline // to ensure Reflection.getCallerClass optimization public static Lookup lookup() { return new Lookup(Reflection.getCallerClass()); } /** * Returns a {@link Lookup lookup object} which is trusted minimally. * It can only be used to create method handles to public members in * public classes in packages that are exported unconditionally. * <p> * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup * object is in an unnamed module. * Consequently, the lookup context of this lookup object will be the bootstrap * class loader, which means it cannot find user classes. * * <p style="font-size:smaller;"> * <em>Discussion:</em> * The lookup class can be changed to any other class {@code C} using an expression of the form * {@link Lookup#in publicLookup().in(C.class)}. * but may change the lookup context by virtue of changing the class loader. * A public lookup object is always subject to * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>. * Also, it cannot access * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>. * @return a lookup object which is trusted minimally */ public static Lookup publicLookup() { // During VM startup then only classes in the java.base module can be // loaded and linked. This is because java.base exports aren't setup until // the module system is initialized, hence types in the unnamed module // (or any named module) can't link to java/lang/Object. if (!jdk.internal.misc.VM.isModuleSystemInited()) { return new Lookup(Object.class, Lookup.PUBLIC); } else { return LookupHelper.PUBLIC_LOOKUP; } } /** * Performs an unchecked "crack" of a * <a href="MethodHandleInfo.html#directmh">direct method handle</a>. * The result is as if the user had obtained a lookup object capable enough * to crack the target method handle, called * {@link java.lang.invoke.MethodHandles.Lookup#revealDirect Lookup.revealDirect} * on the target to obtain its symbolic reference, and then called * {@link java.lang.invoke.MethodHandleInfo#reflectAs MethodHandleInfo.reflectAs} * to resolve the symbolic reference to a member. * <p> * If there is a security manager, its {@code checkPermission} method * is called with a {@code ReflectPermission("suppressAccessChecks")} permission. * @param <T> the desired type of the result, either {@link Member} or a subtype * @param target a direct method handle to crack into symbolic reference components * @param expected a class object representing the desired result type {@code T} * @return a reference to the method, constructor, or field object * @exception SecurityException if the caller is not privileged to call {@code setAccessible} * @exception NullPointerException if either argument is {@code null} * @exception IllegalArgumentException if the target is not a direct method handle * @exception ClassCastException if the member is not of the expected type * @since 1.8 */ public static <T extends Member> T reflectAs(Class<T> expected, MethodHandle target) { SecurityManager smgr = System.getSecurityManager(); if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION); Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup return lookup.revealDirect(target).reflectAs(expected, lookup); } // Copied from AccessibleObject, as used by Method.setAccessible, etc.: private static final java.security.Permission ACCESS_PERMISSION = new ReflectPermission("suppressAccessChecks"); /** * A <em>lookup object</em> is a factory for creating method handles, * when the creation requires access checking. * Method handles do not perform * access checks when they are called, but rather when they are created. * Therefore, method handle access * restrictions must be enforced when a method handle is created. * The caller class against which those restrictions are enforced * is known as the {@linkplain #lookupClass lookup class}. * <p> * A lookup class which needs to create method handles will call * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself. * When the {@code Lookup} factory object is created, the identity of the lookup class is * determined, and securely stored in the {@code Lookup} object. * The lookup class (or its delegates) may then use factory methods * on the {@code Lookup} object to create method handles for access-checked members. * This includes all methods, constructors, and fields which are allowed to the lookup class, * even private ones. * * <h1><a name="lookups"></a>Lookup Factory Methods</h1> * The factory methods on a {@code Lookup} object correspond to all major * use cases for methods, constructors, and fields. * Each method handle created by a factory method is the functional * equivalent of a particular <em>bytecode behavior</em>. * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.) * Here is a summary of the correspondence between these factory methods and * the behavior of the resulting method handles: * <table border=1 cellpadding=5 summary="lookup method behaviors"> * <tr> * <th><a name="equiv"></a>lookup expression</th> * <th>member</th> * <th>bytecode behavior</th> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findGetter lookup.findGetter(C.class,"f",FT.class)}</td> * <td>{@code FT f;}</td><td>{@code (T) this.f;}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticGetter lookup.findStaticGetter(C.class,"f",FT.class)}</td> * <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSetter lookup.findSetter(C.class,"f",FT.class)}</td> * <td>{@code FT f;}</td><td>{@code this.f = x;}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStaticSetter lookup.findStaticSetter(C.class,"f",FT.class)}</td> * <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findVirtual lookup.findVirtual(C.class,"m",MT)}</td> * <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findStatic lookup.findStatic(C.class,"m",MT)}</td> * <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findSpecial lookup.findSpecial(C.class,"m",MT,this.class)}</td> * <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findConstructor lookup.findConstructor(C.class,MT)}</td> * <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter lookup.unreflectGetter(aField)}</td> * <td>({@code static})?<br>{@code FT f;}</td><td>{@code (FT) aField.get(thisOrNull);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter lookup.unreflectSetter(aField)}</td> * <td>({@code static})?<br>{@code FT f;}</td><td>{@code aField.set(thisOrNull, arg);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor lookup.unreflectConstructor(aConstructor)}</td> * <td>{@code C(A*);}</td><td>{@code (C) aConstructor.newInstance(arg*);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#unreflect lookup.unreflect(aMethod)}</td> * <td>({@code static})?<br>{@code T m(A*);}</td><td>{@code (T) aMethod.invoke(thisOrNull, arg*);}</td> * </tr> * <tr> * <td>{@link java.lang.invoke.MethodHandles.Lookup#findClass lookup.findClass("C")}</td> * <td>{@code class C { ... }}</td><td>{@code C.class;}</td> * </tr> * </table> * * Here, the type {@code C} is the class or interface being searched for a member, * documented as a parameter named {@code refc} in the lookup methods. * The method type {@code MT} is composed from the return type {@code T} * and the sequence of argument types {@code A*}. * The constructor also has a sequence of argument types {@code A*} and * is deemed to return the newly-created object of type {@code C}. * Both {@code MT} and the field type {@code FT} are documented as a parameter named {@code type}. * The formal parameter {@code this} stands for the self-reference of type {@code C}; * if it is present, it is always the leading argument to the method handle invocation. * (In the case of some {@code protected} members, {@code this} may be * restricted in type to the lookup class; see below.) * The name {@code arg} stands for all the other method handle arguments. * In the code examples for the Core Reflection API, the name {@code thisOrNull} * stands for a null reference if the accessed method or field is static, * and {@code this} otherwise. * The names {@code aMethod}, {@code aField}, and {@code aConstructor} stand * for reflective objects corresponding to the given members. * <p> * The bytecode behavior for a {@code findClass} operation is a load of a constant class, * as if by {@code ldc CONSTANT_Class}. * The behavior is represented, not as a method handle, but directly as a {@code Class} constant. * <p> * In cases where the given member is of variable arity (i.e., a method or constructor) * the returned method handle will also be of {@linkplain MethodHandle#asVarargsCollector variable arity}. * In all other cases, the returned method handle will be of fixed arity. * <p style="font-size:smaller;"> * <em>Discussion:</em> * The equivalence between looked-up method handles and underlying * class members and bytecode behaviors * can break down in a few ways: * <ul style="font-size:smaller;"> * <li>If {@code C} is not symbolically accessible from the lookup class's loader, * the lookup can still succeed, even when there is no equivalent * Java expression or bytecoded constant. * <li>Likewise, if {@code T} or {@code MT} * is not symbolically accessible from the lookup class's loader, * the lookup can still succeed. * For example, lookups for {@code MethodHandle.invokeExact} and * {@code MethodHandle.invoke} will always succeed, regardless of requested type. * <li>If there is a security manager installed, it can forbid the lookup * on various grounds (<a href="MethodHandles.Lookup.html#secmgr">see below</a>). * By contrast, the {@code ldc} instruction on a {@code CONSTANT_MethodHandle} * constant is not subject to security manager checks. * <li>If the looked-up method has a * <a href="MethodHandle.html#maxarity">very large arity</a>, * the method handle creation may fail, due to the method handle * type having too many parameters. * </ul> * * <h1><a name="access"></a>Access checking</h1> * Access checks are applied in the factory methods of {@code Lookup}, * when a method handle is created. * This is a key difference from the Core Reflection API, since * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} * performs access checking against every caller, on every call. * <p> * All access checks start from a {@code Lookup} object, which * compares its recorded lookup class against all requests to * create method handles. * A single {@code Lookup} object can be used to create any number * of access-checked method handles, all checked against a single * lookup class. * <p> * A {@code Lookup} object can be shared with other trusted code, * such as a metaobject protocol. * A shared {@code Lookup} object delegates the capability * to create method handles on private members of the lookup class. * Even if privileged code uses the {@code Lookup} object, * the access checking is confined to the privileges of the * original lookup class. * <p> * A lookup can fail, because * the containing class is not accessible to the lookup class, or * because the desired class member is missing, or because the * desired class member is not accessible to the lookup class, or * because the lookup object is not trusted enough to access the member. * In any of these cases, a {@code ReflectiveOperationException} will be * thrown from the attempted lookup. The exact class will be one of * the following: * <ul> * <li>NoSuchMethodException &mdash; if a method is requested but does not exist * <li>NoSuchFieldException &mdash; if a field is requested but does not exist * <li>IllegalAccessException &mdash; if the member exists but an access check fails * </ul> * <p> * In general, the conditions under which a method handle may be * looked up for a method {@code M} are no more restrictive than the conditions * under which the lookup class could have compiled, verified, and resolved a call to {@code M}. * Where the JVM would raise exceptions like {@code NoSuchMethodError}, * a method handle lookup will generally raise a corresponding * checked exception, such as {@code NoSuchMethodException}. * And the effect of invoking the method handle resulting from the lookup * is <a href="MethodHandles.Lookup.html#equiv">exactly equivalent</a> * to executing the compiled, verified, and resolved call to {@code M}. * The same point is true of fields and constructors. * <p style="font-size:smaller;"> * <em>Discussion:</em> * Access checks only apply to named and reflected methods, * constructors, and fields. * Other method handle creation methods, such as * {@link MethodHandle#asType MethodHandle.asType}, * do not require any access checks, and are used * independently of any {@code Lookup} object. * <p> * If the desired member is {@code protected}, the usual JVM rules apply, * including the requirement that the lookup class must be either be in the * same package as the desired member, or must inherit that member. * (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) * In addition, if the desired member is a non-static field or method * in a different package, the resulting method handle may only be applied * to objects of the lookup class or one of its subclasses. * This requirement is enforced by narrowing the type of the leading * {@code this} parameter from {@code C} * (which will necessarily be a superclass of the lookup class) * to the lookup class itself. * <p> * The JVM imposes a similar requirement on {@code invokespecial} instruction, * that the receiver argument must match both the resolved method <em>and</em> * the current class. Again, this requirement is enforced by narrowing the * type of the leading parameter to the resulting method handle. * (See the Java Virtual Machine Specification, section 4.10.1.9.) * <p> * The JVM represents constructors and static initializer blocks as internal methods * with special names ({@code "<init>"} and {@code "<clinit>"}). * The internal syntax of invocation instructions allows them to refer to such internal * methods as if they were normal methods, but the JVM bytecode verifier rejects them. * A lookup of such an internal method will produce a {@code NoSuchMethodException}. * <p> * In some cases, access between nested classes is obtained by the Java compiler by creating * an wrapper method to access a private method of another class * in the same top-level declaration. * For example, a nested class {@code C.D} * can access private members within other related classes such as * {@code C}, {@code C.D.E}, or {@code C.B}, * but the Java compiler may need to generate wrapper methods in * those related classes. In such cases, a {@code Lookup} object on * {@code C.E} would be unable to those private members. * A workaround for this limitation is the {@link Lookup#in Lookup.in} method, * which can transform a lookup on {@code C.E} into one on any of those other * classes, without special elevation of privilege. * <p> * The accesses permitted to a given lookup object may be limited, * according to its set of {@link #lookupModes lookupModes}, * to a subset of members normally accessible to the lookup class. * For example, the {@link MethodHandles#publicLookup publicLookup} * method produces a lookup object which is only allowed to access * public members in public classes of exported packages. * The caller sensitive method {@link MethodHandles#lookup lookup} * produces a lookup object with full capabilities relative to * its caller class, to emulate all supported bytecode behaviors. * Also, the {@link Lookup#in Lookup.in} method may produce a lookup object * with fewer access modes than the original lookup object. * * <p style="font-size:smaller;"> * <a name="privacc"></a> * <em>Discussion of private access:</em> * We say that a lookup has <em>private access</em> * if its {@linkplain #lookupModes lookup modes} * include the possibility of accessing {@code private} members. * As documented in the relevant methods elsewhere, * only lookups with private access possess the following capabilities: * <ul style="font-size:smaller;"> * <li>access private fields, methods, and constructors of the lookup class * <li>create method handles which invoke <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> methods, * such as {@code Class.forName} * <li>create method handles which {@link Lookup#findSpecial emulate invokespecial} instructions * <li>avoid <a href="MethodHandles.Lookup.html#secmgr">package access checks</a> * for classes accessible to the lookup class * <li>create {@link Lookup#in delegated lookup objects} which have private access to other classes * within the same package member * </ul> * <p style="font-size:smaller;"> * Each of these permissions is a consequence of the fact that a lookup object * with private access can be securely traced back to an originating class, * whose <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> and Java language access permissions * can be reliably determined and emulated by method handles. * * <h1><a name="secmgr"></a>Security manager interactions</h1> * Although bytecode instructions can only refer to classes in * a related class loader, this API can search for methods in any * class, as long as a reference to its {@code Class} object is * available. Such cross-loader references are also possible with the * Core Reflection API, and are impossible to bytecode instructions * such as {@code invokestatic} or {@code getfield}. * There is a {@linkplain java.lang.SecurityManager security manager API} * to allow applications to check such cross-loader references. * These checks apply to both the {@code MethodHandles.Lookup} API * and the Core Reflection API * (as found on {@link java.lang.Class Class}). * <p> * If a security manager is present, member and class lookups are subject to * additional checks. * From one to three calls are made to the security manager. * Any of these calls can refuse access by throwing a * {@link java.lang.SecurityException SecurityException}. * Define {@code smgr} as the security manager, * {@code lookc} as the lookup class of the current lookup object, * {@code refc} as the containing class in which the member * is being sought, and {@code defc} as the class in which the * member is actually defined. * (If a class or other type is being accessed, * the {@code refc} and {@code defc} values are the class itself.) * The value {@code lookc} is defined as <em>not present</em> * if the current lookup object does not have * <a href="MethodHandles.Lookup.html#privacc">private access</a>. * The calls are made according to the following rules: * <ul> * <li><b>Step 1:</b> * If {@code lookc} is not present, or if its class loader is not * the same as or an ancestor of the class loader of {@code refc}, * then {@link SecurityManager#checkPackageAccess * smgr.checkPackageAccess(refcPkg)} is called, * where {@code refcPkg} is the package of {@code refc}. * <li><b>Step 2a:</b> * If the retrieved member is not public and * {@code lookc} is not present, then * {@link SecurityManager#checkPermission smgr.checkPermission} * with {@code RuntimePermission("accessDeclaredMembers")} is called. * <li><b>Step 2b:</b> * If the retrieved class has a {@code null} class loader, * and {@code lookc} is not present, then * {@link SecurityManager#checkPermission smgr.checkPermission} * with {@code RuntimePermission("getClassLoader")} is called. * <li><b>Step 3:</b> * If the retrieved member is not public, * and if {@code lookc} is not present, * and if {@code defc} and {@code refc} are different, * then {@link SecurityManager#checkPackageAccess * smgr.checkPackageAccess(defcPkg)} is called, * where {@code defcPkg} is the package of {@code defc}. * </ul> * Security checks are performed after other access checks have passed. * Therefore, the above rules presuppose a member or class that is public, * or else that is being accessed from a lookup class that has * rights to access the member or class. * * <h1><a name="callsens"></a>Caller sensitive methods</h1> * A small number of Java methods have a special property called caller sensitivity. * A <em>caller-sensitive</em> method can behave differently depending on the * identity of its immediate caller. * <p> * If a method handle for a caller-sensitive method is requested, * the general rules for <a href="MethodHandles.Lookup.html#equiv">bytecode behaviors</a> apply, * but they take account of the lookup class in a special way. * The resulting method handle behaves as if it were called * from an instruction contained in the lookup class, * so that the caller-sensitive method detects the lookup class. * (By contrast, the invoker of the method handle is disregarded.) * Thus, in the case of caller-sensitive methods, * different lookup classes may give rise to * differently behaving method handles. * <p> * In cases where the lookup object is * {@link MethodHandles#publicLookup() publicLookup()}, * or some other lookup object without * <a href="MethodHandles.Lookup.html#privacc">private access</a>, * the lookup class is disregarded. * In such cases, no caller-sensitive method handle can be created, * access is forbidden, and the lookup fails with an * {@code IllegalAccessException}. * <p style="font-size:smaller;"> * <em>Discussion:</em> * For example, the caller-sensitive method * {@link java.lang.Class#forName(String) Class.forName(x)} * can return varying classes or throw varying exceptions, * depending on the class loader of the class that calls it. * A public lookup of {@code Class.forName} will fail, because * there is no reasonable way to determine its bytecode behavior. * <p style="font-size:smaller;"> * If an application caches method handles for broad sharing, * it should use {@code publicLookup()} to create them. * If there is a lookup of {@code Class.forName}, it will fail, * and the application must take appropriate action in that case. * It may be that a later lookup, perhaps during the invocation of a * bootstrap method, can incorporate the specific identity * of the caller, making the method accessible. * <p style="font-size:smaller;"> * The function {@code MethodHandles.lookup} is caller sensitive * so that there can be a secure foundation for lookups. * Nearly all other methods in the JSR 292 API rely on lookup * objects to check access requests. */ public static final class Lookup { /** The class on behalf of whom the lookup is being performed. */ private final Class<?> lookupClass; /** The allowed sorts of members which may be looked up (PUBLIC, etc.). */ private final int allowedModes; /** A single-bit mask representing {@code public} access, * which may contribute to the result of {@link #lookupModes lookupModes}. * The value, {@code 0x01}, happens to be the same as the value of the * {@code public} {@linkplain java.lang.reflect.Modifier#PUBLIC modifier bit}. */ public static final int PUBLIC = Modifier.PUBLIC; /** A single-bit mask representing {@code private} access, * which may contribute to the result of {@link #lookupModes lookupModes}. * The value, {@code 0x02}, happens to be the same as the value of the * {@code private} {@linkplain java.lang.reflect.Modifier#PRIVATE modifier bit}. */ public static final int PRIVATE = Modifier.PRIVATE; /** A single-bit mask representing {@code protected} access, * which may contribute to the result of {@link #lookupModes lookupModes}. * The value, {@code 0x04}, happens to be the same as the value of the * {@code protected} {@linkplain java.lang.reflect.Modifier#PROTECTED modifier bit}. */ public static final int PROTECTED = Modifier.PROTECTED; /** A single-bit mask representing {@code package} access (default access), * which may contribute to the result of {@link #lookupModes lookupModes}. * The value is {@code 0x08}, which does not correspond meaningfully to * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. */ public static final int PACKAGE = Modifier.STATIC; /** A single-bit mask representing {@code module} access (default access), * which may contribute to the result of {@link #lookupModes lookupModes}. * The value is {@code 0x10}, which does not correspond meaningfully to * any particular {@linkplain java.lang.reflect.Modifier modifier bit}. * In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup} * with this lookup mode can access all public types in the module of the * lookup class and public types in packages exported by other modules * to the module of the lookup class. * @since 9 */ public static final int MODULE = PACKAGE << 1; private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE); private static final int TRUSTED = -1; private static int fixmods(int mods) { mods &= (ALL_MODES - PACKAGE - MODULE); return (mods != 0) ? mods : (PACKAGE | MODULE); } /** Tells which class is performing the lookup. It is this class against * which checks are performed for visibility and access permissions. * <p> * The class implies a maximum level of access permission, * but the permissions may be additionally limited by the bitmask * {@link #lookupModes lookupModes}, which controls whether non-public members * can be accessed. * @return the lookup class, on behalf of which this lookup object finds members */ public Class<?> lookupClass() { return lookupClass; } // This is just for calling out to MethodHandleImpl. private Class<?> lookupClassOrNull() { return (allowedModes == TRUSTED) ? null : lookupClass; } /** Tells which access-protection classes of members this lookup object can produce. * The result is a bit-mask of the bits * {@linkplain #PUBLIC PUBLIC (0x01)}, * {@linkplain #PRIVATE PRIVATE (0x02)}, * {@linkplain #PROTECTED PROTECTED (0x04)}, * {@linkplain #PACKAGE PACKAGE (0x08)}, * and {@linkplain #MODULE MODULE (0x10)}. * <p> * A freshly-created lookup object * on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} * has all possible bits set, since the caller class can access all its own members, * all public types in the caller's module, and all public types in packages exported * by other modules to the caller's module. * A lookup object on a new lookup class * {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object} * may have some mode bits set to zero. * The purpose of this is to restrict access via the new lookup object, * so that it can access only names which can be reached by the original * lookup object, and also by the new lookup class. * @return the lookup modes, which limit the kinds of access performed by this lookup object */ public int lookupModes() { return allowedModes & ALL_MODES; } /** Embody the current class (the lookupClass) as a lookup class * for method handle creation. * Must be called by from a method in this package, * which in turn is called by a method not in this package. */ Lookup(Class<?> lookupClass) { this(lookupClass, ALL_MODES); // make sure we haven't accidentally picked up a privileged class: checkUnprivilegedlookupClass(lookupClass, ALL_MODES); } private Lookup(Class<?> lookupClass, int allowedModes) { this.lookupClass = lookupClass; this.allowedModes = allowedModes; } /** * Creates a lookup on the specified new lookup class. * The resulting object will report the specified * class as its own {@link #lookupClass lookupClass}. * <p> * However, the resulting {@code Lookup} object is guaranteed * to have no more access capabilities than the original. * In particular, access capabilities can be lost as follows:<ul> * <li>If the lookup class for this {@code Lookup} is not in a named module, * and the new lookup class is in a named module {@code M}, then no members in * {@code M}'s non-exported packages will be accessible. * <li>If the lookup for this {@code Lookup} is in a named module, and the * new lookup class is in a different module {@code M}, then no members, not even * public members in {@code M}'s exported packages, will be accessible. * <li>If the new lookup class differs from the old one, * protected members will not be accessible by virtue of inheritance. * (Protected members may continue to be accessible because of package sharing.) * <li>If the new lookup class is in a different package * than the old one, protected and default (package) members will not be accessible. * <li>If the new lookup class is not within the same package member * as the old one, private members will not be accessible. * <li>If the new lookup class is not accessible to the old lookup class, * then no members, not even public members, will be accessible. * (In all other cases, public members will continue to be accessible.) * </ul> * <p> * The resulting lookup's capabilities for loading classes * (used during {@link #findClass} invocations) * are determined by the lookup class' loader, * which may change due to this operation. * * @param requestedLookupClass the desired lookup class for the new lookup object * @return a lookup object which reports the desired lookup class * @throws NullPointerException if the argument is null */ public Lookup in(Class<?> requestedLookupClass) { Objects.requireNonNull(requestedLookupClass); if (allowedModes == TRUSTED) // IMPL_LOOKUP can make any lookup at all return new Lookup(requestedLookupClass, ALL_MODES); if (requestedLookupClass == this.lookupClass) return this; // keep same capabilities int newModes = (allowedModes & (ALL_MODES & ~PROTECTED)); if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) { // Allowed to teleport from an unnamed to a named module but resulting // Lookup has no access to module private members if (this.lookupClass.getModule().isNamed()) { newModes = 0; } else { newModes &= ~MODULE; } } if ((newModes & PACKAGE) != 0 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) { newModes &= ~(PACKAGE|PRIVATE); } // Allow nestmate lookups to be created without special privilege: if ((newModes & PRIVATE) != 0 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) { newModes &= ~PRIVATE; } if ((newModes & PUBLIC) != 0 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) { // The requested class it not accessible from the lookup class. // No permissions. newModes = 0; } checkUnprivilegedlookupClass(requestedLookupClass, newModes); return new Lookup(requestedLookupClass, newModes); } // Make sure outer class is initialized first. static { IMPL_NAMES.getClass(); } /** Package-private version of lookup which is trusted. */ static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED); private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) { String name = lookupClass.getName(); if (name.startsWith("java.lang.invoke.")) throw newIllegalArgumentException("illegal lookupClass: "+lookupClass); // For caller-sensitive MethodHandles.lookup() disallow lookup from // restricted packages. This a fragile and blunt approach. // TODO replace with a more formal and less fragile mechanism // that does not bluntly restrict classes under packages within // java.base from looking up MethodHandles or VarHandles. if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) { if ((name.startsWith("java.") && !name.startsWith("java.util.concurrent.")) || (name.startsWith("sun.") && !name.startsWith("sun.invoke."))) { throw newIllegalArgumentException("illegal lookupClass: " + lookupClass); } } } /** * Displays the name of the class from which lookups are to be made. * (The name is the one reported by {@link java.lang.Class#getName() Class.getName}.) * If there are restrictions on the access permitted to this lookup, * this is indicated by adding a suffix to the class name, consisting * of a slash and a keyword. The keyword represents the strongest * allowed access, and is chosen as follows: * <ul> * <li>If no access is allowed, the suffix is "/noaccess". * <li>If only public access to types in exported packages is allowed, the suffix is "/public". * <li>If only public and module access are allowed, the suffix is "/module". * <li>If only public, module and package access are allowed, the suffix is "/package". * <li>If only public, module, package, and private access are allowed, the suffix is "/private". * </ul> * If none of the above cases apply, it is the case that full * access (public, module, package, private, and protected) is allowed. * In this case, no suffix is added. * This is true only of an object obtained originally from * {@link java.lang.invoke.MethodHandles#lookup MethodHandles.lookup}. * Objects created by {@link java.lang.invoke.MethodHandles.Lookup#in Lookup.in} * always have restricted access, and will display a suffix. * <p> * (It may seem strange that protected access should be * stronger than private access. Viewed independently from * package access, protected access is the first to be lost, * because it requires a direct subclass relationship between * caller and callee.) * @see #in */ @Override public String toString() { String cname = lookupClass.getName(); switch (allowedModes) { case 0: // no privileges return cname + "/noaccess"; case PUBLIC: return cname + "/public"; case PUBLIC|MODULE: return cname + "/module"; case PUBLIC|MODULE|PACKAGE: return cname + "/package"; case ALL_MODES & ~PROTECTED: return cname + "/private"; case ALL_MODES: return cname; case TRUSTED: return "/trusted"; // internal only; not exported default: // Should not happen, but it's a bitfield... cname = cname + "/" + Integer.toHexString(allowedModes); assert(false) : cname; return cname; } } /** * Produces a method handle for a static method. * The type of the method handle will be that of the method. * (Since static methods do not take receivers, there is no * additional receiver argument inserted into the method handle type, * as there would be with {@link #findVirtual findVirtual} or {@link #findSpecial findSpecial}.) * The method and all its argument types must be accessible to the lookup object. * <p> * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit ({@code 0x0080}) is set. * <p> * If the returned method handle is invoked, the method's class will * be initialized, if it has not already been initialized. * <p><b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle MH_asList = publicLookup().findStatic(Arrays.class, "asList", methodType(List.class, Object[].class)); assertEquals("[x, y]", MH_asList.invoke("x", "y").toString()); * }</pre></blockquote> * @param refc the class from which the method is accessed * @param name the name of the method * @param type the type of the method * @return the desired method handle * @throws NoSuchMethodException if the method does not exist * @throws IllegalAccessException if access checking fails, * or if the method is not {@code static}, * or if the method's variable arity modifier bit * is set and {@code asVarargsCollector} fails * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null */ public MethodHandle findStatic(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { MemberName method = resolveOrFail(REF_invokeStatic, refc, name, type); return getDirectMethod(REF_invokeStatic, refc, method, findBoundCallerClass(method)); } /** * Produces a method handle for a virtual method. * The type of the method handle will be that of the method, * with the receiver type (usually {@code refc}) prepended. * The method and all its argument types must be accessible to the lookup object. * <p> * When called, the handle will treat the first argument as a receiver * and dispatch on the receiver's type to determine which method * implementation to enter. * (The dispatching action is identical with that performed by an * {@code invokevirtual} or {@code invokeinterface} instruction.) * <p> * The first argument will be of type {@code refc} if the lookup * class has full privileges to access the member. Otherwise * the member must be {@code protected} and the first argument * will be restricted in type to the lookup class. * <p> * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit ({@code 0x0080}) is set. * <p> * Because of the general <a href="MethodHandles.Lookup.html#equiv">equivalence</a> between {@code invokevirtual} * instructions and method handles produced by {@code findVirtual}, * if the class is {@code MethodHandle} and the name string is * {@code invokeExact} or {@code invoke}, the resulting * method handle is equivalent to one produced by * {@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker} or * {@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker} * with the same {@code type} argument. * <p> * If the class is {@code VarHandle} and the name string corresponds to * the name of a signature-polymorphic access mode method, the resulting * method handle is equivalent to one produced by * {@link java.lang.invoke.MethodHandles#varHandleInvoker} with * the access mode corresponding to the name string and with the same * {@code type} arguments. * <p> * <b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle MH_concat = publicLookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); MethodHandle MH_hashCode = publicLookup().findVirtual(Object.class, "hashCode", methodType(int.class)); MethodHandle MH_hashCode_String = publicLookup().findVirtual(String.class, "hashCode", methodType(int.class)); assertEquals("xy", (String) MH_concat.invokeExact("x", "y")); assertEquals("xy".hashCode(), (int) MH_hashCode.invokeExact((Object)"xy")); assertEquals("xy".hashCode(), (int) MH_hashCode_String.invokeExact("xy")); // interface method: MethodHandle MH_subSequence = publicLookup().findVirtual(CharSequence.class, "subSequence", methodType(CharSequence.class, int.class, int.class)); assertEquals("def", MH_subSequence.invoke("abcdefghi", 3, 6).toString()); // constructor "internal method" must be accessed differently: MethodType MT_newString = methodType(void.class); //()V for new String() try { assertEquals("impossible", lookup() .findVirtual(String.class, "<init>", MT_newString)); } catch (NoSuchMethodException ex) { } // OK MethodHandle MH_newString = publicLookup() .findConstructor(String.class, MT_newString); assertEquals("", (String) MH_newString.invokeExact()); * }</pre></blockquote> * * @param refc the class or interface from which the method is accessed * @param name the name of the method * @param type the type of the method, with the receiver argument omitted * @return the desired method handle * @throws NoSuchMethodException if the method does not exist * @throws IllegalAccessException if access checking fails, * or if the method is {@code static}, * or if the method is {@code private} method of interface, * or if the method's variable arity modifier bit * is set and {@code asVarargsCollector} fails * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null */ public MethodHandle findVirtual(Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { if (refc == MethodHandle.class) { MethodHandle mh = findVirtualForMH(name, type); if (mh != null) return mh; } else if (refc == VarHandle.class) { MethodHandle mh = findVirtualForVH(name, type); if (mh != null) return mh; } byte refKind = (refc.isInterface() ? REF_invokeInterface : REF_invokeVirtual); MemberName method = resolveOrFail(refKind, refc, name, type); return getDirectMethod(refKind, refc, method, findBoundCallerClass(method)); } private MethodHandle findVirtualForMH(String name, MethodType type) { // these names require special lookups because of the implicit MethodType argument if ("invoke".equals(name)) return invoker(type); if ("invokeExact".equals(name)) return exactInvoker(type); assert(!MemberName.isMethodHandleInvokeName(name)); return null; } private MethodHandle findVirtualForVH(String name, MethodType type) { try { return varHandleInvoker(VarHandle.AccessMode.valueFromMethodName(name), type); } catch (IllegalArgumentException e) { return null; } } /** * Produces a method handle which creates an object and initializes it, using * the constructor of the specified type. * The parameter types of the method handle will be those of the constructor, * while the return type will be a reference to the constructor's class. * The constructor and all its argument types must be accessible to the lookup object. * <p> * The requested type must have a return type of {@code void}. * (This is consistent with the JVM's treatment of constructor type descriptors.) * <p> * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the constructor's variable arity modifier bit ({@code 0x0080}) is set. * <p> * If the returned method handle is invoked, the constructor's class will * be initialized, if it has not already been initialized. * <p><b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle MH_newArrayList = publicLookup().findConstructor( ArrayList.class, methodType(void.class, Collection.class)); Collection orig = Arrays.asList("x", "y"); Collection copy = (ArrayList) MH_newArrayList.invokeExact(orig); assert(orig != copy); assertEquals(orig, copy); // a variable-arity constructor: MethodHandle MH_newProcessBuilder = publicLookup().findConstructor( ProcessBuilder.class, methodType(void.class, String[].class)); ProcessBuilder pb = (ProcessBuilder) MH_newProcessBuilder.invoke("x", "y", "z"); assertEquals("[x, y, z]", pb.command().toString()); * }</pre></blockquote> * @param refc the class or interface from which the method is accessed * @param type the type of the method, with the receiver argument omitted, and a void return type * @return the desired method handle * @throws NoSuchMethodException if the constructor does not exist * @throws IllegalAccessException if access checking fails * or if the method's variable arity modifier bit * is set and {@code asVarargsCollector} fails * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null */ public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException { if (refc.isArray()) { throw new NoSuchMethodException("no constructor for array class: " + refc.getName()); } String name = "<init>"; MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type); return getDirectConstructor(refc, ctor); } /** * Looks up a class by name from the lookup context defined by this {@code Lookup} object. The static * initializer of the class is not run. * <p> * The lookup context here is determined by the {@linkplain #lookupClass() lookup class}, its class * loader, and the {@linkplain #lookupModes() lookup modes}. In particular, the method first attempts to * load the requested class, and then determines whether the class is accessible to this lookup object. * * @param targetName the fully qualified name of the class to be looked up. * @return the requested class. * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws LinkageError if the linkage fails * @throws ClassNotFoundException if the class cannot be loaded by the lookup class' loader. * @throws IllegalAccessException if the class is not accessible, using the allowed access * modes. * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @since 9 */ public Class<?> findClass(String targetName) throws ClassNotFoundException, IllegalAccessException { Class<?> targetClass = Class.forName(targetName, false, lookupClass.getClassLoader()); return accessClass(targetClass); } /** * Determines if a class can be accessed from the lookup context defined by this {@code Lookup} object. The * static initializer of the class is not run. * <p> * The lookup context here is determined by the {@linkplain #lookupClass() lookup class} and the * {@linkplain #lookupModes() lookup modes}. * * @param targetClass the class to be access-checked * * @return the class that has been access-checked * * @throws IllegalAccessException if the class is not accessible from the lookup class, using the allowed access * modes. * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @since 9 */ public Class<?> accessClass(Class<?> targetClass) throws IllegalAccessException { if (!VerifyAccess.isClassAccessible(targetClass, lookupClass, allowedModes)) { throw new MemberName(targetClass).makeAccessException("access violation", this); } checkSecurityManager(targetClass, null); return targetClass; } /** * Produces an early-bound method handle for a virtual method. * It will bypass checks for overriding methods on the receiver, * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} * instruction from within the explicitly specified {@code specialCaller}. * The type of the method handle will be that of the method, * with a suitably restricted receiver type prepended. * (The receiver type will be {@code specialCaller} or a subtype.) * The method and all its argument types must be accessible * to the lookup object. * <p> * Before method resolution, * if the explicitly specified caller class is not identical with the * lookup class, or if this lookup object does not have * <a href="MethodHandles.Lookup.html#privacc">private access</a> * privileges, the access fails. * <p> * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit ({@code 0x0080}) is set. * <p style="font-size:smaller;"> * <em>(Note: JVM internal methods named {@code "<init>"} are not visible to this API, * even though the {@code invokespecial} instruction can refer to them * in special circumstances. Use {@link #findConstructor findConstructor} * to access instance initialization methods in a safe manner.)</em> * <p><b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... static class Listie extends ArrayList { public String toString() { return "[wee Listie]"; } static Lookup lookup() { return MethodHandles.lookup(); } } ... // no access to constructor via invokeSpecial: MethodHandle MH_newListie = Listie.lookup() .findConstructor(Listie.class, methodType(void.class)); Listie l = (Listie) MH_newListie.invokeExact(); try { assertEquals("impossible", Listie.lookup().findSpecial( Listie.class, "<init>", methodType(void.class), Listie.class)); } catch (NoSuchMethodException ex) { } // OK // access to super and self methods via invokeSpecial: MethodHandle MH_super = Listie.lookup().findSpecial( ArrayList.class, "toString" , methodType(String.class), Listie.class); MethodHandle MH_this = Listie.lookup().findSpecial( Listie.class, "toString" , methodType(String.class), Listie.class); MethodHandle MH_duper = Listie.lookup().findSpecial( Object.class, "toString" , methodType(String.class), Listie.class); assertEquals("[]", (String) MH_super.invokeExact(l)); assertEquals(""+l, (String) MH_this.invokeExact(l)); assertEquals("[]", (String) MH_duper.invokeExact(l)); // ArrayList method try { assertEquals("inaccessible", Listie.lookup().findSpecial( String.class, "toString", methodType(String.class), Listie.class)); } catch (IllegalAccessException ex) { } // OK Listie subl = new Listie() { public String toString() { return "[subclass]"; } }; assertEquals(""+l, (String) MH_this.invokeExact(subl)); // Listie method * }</pre></blockquote> * * @param refc the class or interface from which the method is accessed * @param name the name of the method (which must not be "&lt;init&gt;") * @param type the type of the method, with the receiver argument omitted * @param specialCaller the proposed calling class to perform the {@code invokespecial} * @return the desired method handle * @throws NoSuchMethodException if the method does not exist * @throws IllegalAccessException if access checking fails, * or if the method is {@code static}, * or if the method's variable arity modifier bit * is set and {@code asVarargsCollector} fails * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null */ public MethodHandle findSpecial(Class<?> refc, String name, MethodType type, Class<?> specialCaller) throws NoSuchMethodException, IllegalAccessException { checkSpecialCaller(specialCaller, refc); Lookup specialLookup = this.in(specialCaller); MemberName method = specialLookup.resolveOrFail(REF_invokeSpecial, refc, name, type); return specialLookup.getDirectMethod(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); } /** * Produces a method handle giving read access to a non-static field. * The type of the method handle will have a return type of the field's * value type. * The method handle's single argument will be the instance containing * the field. * Access checking is performed immediately on behalf of the lookup class. * @param refc the class or interface from which the method is accessed * @param name the field's name * @param type the field's type * @return a method handle which can load values from the field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is {@code static} * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null * @see #findVarHandle(Class, String, Class) */ public MethodHandle findGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { MemberName field = resolveOrFail(REF_getField, refc, name, type); return getDirectField(REF_getField, refc, field); } /** * Produces a method handle giving write access to a non-static field. * The type of the method handle will have a void return type. * The method handle will take two arguments, the instance containing * the field, and the value to be stored. * The second argument will be of the field's value type. * Access checking is performed immediately on behalf of the lookup class. * @param refc the class or interface from which the method is accessed * @param name the field's name * @param type the field's type * @return a method handle which can store values into the field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is {@code static} * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null * @see #findVarHandle(Class, String, Class) */ public MethodHandle findSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { MemberName field = resolveOrFail(REF_putField, refc, name, type); return getDirectField(REF_putField, refc, field); } /** * Produces a VarHandle giving access to non-static fields of type * {@code T} declared by a receiver class of type {@code R}, supporting * shape {@code (R : T)}. * <p> * Access checking is performed immediately on behalf of the lookup * class. * <p> * Certain access modes of the returned VarHandle are unsupported under * the following conditions: * <ul> * <li>if the field is declared {@code final}, then the write, atomic * update, and numeric atomic update access modes are unsupported. * <li>if the field type is anything other than {@code byte}, * {@code short}, {@code char}, {@code int} or {@code long}, * {@code float}, or {@code double} then numeric atomic update * access modes are unsupported. * </ul> * <p> * If the field is declared {@code volatile} then the returned VarHandle * will override access to the field (effectively ignore the * {@code volatile} declaration) in accordance to it's specified * access modes. * <p> * If the field type is {@code float} or {@code double} then numeric * and atomic update access modes compare values using their bitwise * representation (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @apiNote * Bitwise comparison of {@code float} values or {@code double} values, * as performed by the numeric and atomic update access modes, differ * from the primitive {@code ==} operator and the {@link Float#equals} * and {@link Double#equals} methods, specifically with respect to * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. * Care should be taken when performing a compare and set or a compare * and exchange operation with such values since the operation may * unexpectedly fail. * There are many possible NaN values that are considered to be * {@code NaN} in Java, although no IEEE 754 floating-point operation * provided by Java can distinguish between them. Operation failure can * occur if the expected or witness value is a NaN value and it is * transformed (perhaps in a platform specific manner) into another NaN * value, and thus has a different bitwise representation (see * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more * details). * The values {@code -0.0} and {@code +0.0} have different bitwise * representations but are considered equal when using the primitive * {@code ==} operator. Operation failure can occur if, for example, a * numeric algorithm computes an expected value to be say {@code -0.0} * and previously computed the witness value to be say {@code +0.0}. * @param recv the receiver class, of type {@code R}, that declares the * non-static field * @param name the field's name * @param type the field's type, of type {@code T} * @return a VarHandle giving access to non-static fields. * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is {@code static} * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null * @since 9 */ public VarHandle findVarHandle(Class<?> recv, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { MemberName getField = resolveOrFail(REF_getField, recv, name, type); MemberName putField = resolveOrFail(REF_putField, recv, name, type); return getFieldVarHandle(REF_getField, REF_putField, recv, getField, putField); } /** * Produces a method handle giving read access to a static field. * The type of the method handle will have a return type of the field's * value type. * The method handle will take no arguments. * Access checking is performed immediately on behalf of the lookup class. * <p> * If the returned method handle is invoked, the field's class will * be initialized, if it has not already been initialized. * @param refc the class or interface from which the method is accessed * @param name the field's name * @param type the field's type * @return a method handle which can load values from the field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null */ public MethodHandle findStaticGetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { MemberName field = resolveOrFail(REF_getStatic, refc, name, type); return getDirectField(REF_getStatic, refc, field); } /** * Produces a method handle giving write access to a static field. * The type of the method handle will have a void return type. * The method handle will take a single * argument, of the field's value type, the value to be stored. * Access checking is performed immediately on behalf of the lookup class. * <p> * If the returned method handle is invoked, the field's class will * be initialized, if it has not already been initialized. * @param refc the class or interface from which the method is accessed * @param name the field's name * @param type the field's type * @return a method handle which can store values into the field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null */ public MethodHandle findStaticSetter(Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { MemberName field = resolveOrFail(REF_putStatic, refc, name, type); return getDirectField(REF_putStatic, refc, field); } /** * Produces a VarHandle giving access to a static field of type * {@code T} declared by a given declaring class, supporting shape * {@code ((empty) : T)}. * <p> * Access checking is performed immediately on behalf of the lookup * class. * <p> * If the returned VarHandle is operated on, the declaring class will be * initialized, if it has not already been initialized. * <p> * Certain access modes of the returned VarHandle are unsupported under * the following conditions: * <ul> * <li>if the field is declared {@code final}, then the write, atomic * update, and numeric atomic update access modes are unsupported. * <li>if the field type is anything other than {@code byte}, * {@code short}, {@code char}, {@code int} or {@code long}, * {@code float}, or {@code double}, then numeric atomic update * access modes are unsupported. * </ul> * <p> * If the field is declared {@code volatile} then the returned VarHandle * will override access to the field (effectively ignore the * {@code volatile} declaration) in accordance to it's specified * access modes. * <p> * If the field type is {@code float} or {@code double} then numeric * and atomic update access modes compare values using their bitwise * representation (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @apiNote * Bitwise comparison of {@code float} values or {@code double} values, * as performed by the numeric and atomic update access modes, differ * from the primitive {@code ==} operator and the {@link Float#equals} * and {@link Double#equals} methods, specifically with respect to * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. * Care should be taken when performing a compare and set or a compare * and exchange operation with such values since the operation may * unexpectedly fail. * There are many possible NaN values that are considered to be * {@code NaN} in Java, although no IEEE 754 floating-point operation * provided by Java can distinguish between them. Operation failure can * occur if the expected or witness value is a NaN value and it is * transformed (perhaps in a platform specific manner) into another NaN * value, and thus has a different bitwise representation (see * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more * details). * The values {@code -0.0} and {@code +0.0} have different bitwise * representations but are considered equal when using the primitive * {@code ==} operator. Operation failure can occur if, for example, a * numeric algorithm computes an expected value to be say {@code -0.0} * and previously computed the witness value to be say {@code +0.0}. * @param decl the class that declares the static field * @param name the field's name * @param type the field's type, of type {@code T} * @return a VarHandle giving access to a static field * @throws NoSuchFieldException if the field does not exist * @throws IllegalAccessException if access checking fails, or if the field is not {@code static} * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null * @since 9 */ public VarHandle findStaticVarHandle(Class<?> decl, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { MemberName getField = resolveOrFail(REF_getStatic, decl, name, type); MemberName putField = resolveOrFail(REF_putStatic, decl, name, type); return getFieldVarHandle(REF_getStatic, REF_putStatic, decl, getField, putField); } /** * Produces an early-bound method handle for a non-static method. * The receiver must have a supertype {@code defc} in which a method * of the given name and type is accessible to the lookup class. * The method and all its argument types must be accessible to the lookup object. * The type of the method handle will be that of the method, * without any insertion of an additional receiver parameter. * The given receiver will be bound into the method handle, * so that every call to the method handle will invoke the * requested method on the given receiver. * <p> * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit ({@code 0x0080}) is set * <em>and</em> the trailing array argument is not the only argument. * (If the trailing array argument is the only argument, * the given receiver value will be bound to it.) * <p> * This is equivalent to the following code: * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle mh0 = lookup().findVirtual(defc, name, type); MethodHandle mh1 = mh0.bindTo(receiver); mh1 = mh1.withVarargs(mh0.isVarargsCollector()); return mh1; * }</pre></blockquote> * where {@code defc} is either {@code receiver.getClass()} or a super * type of that class, in which the requested method is accessible * to the lookup class. * (Note that {@code bindTo} does not preserve variable arity.) * @param receiver the object from which the method is accessed * @param name the name of the method * @param type the type of the method, with the receiver argument omitted * @return the desired method handle * @throws NoSuchMethodException if the method does not exist * @throws IllegalAccessException if access checking fails * or if the method's variable arity modifier bit * is set and {@code asVarargsCollector} fails * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws NullPointerException if any argument is null * @see MethodHandle#bindTo * @see #findVirtual */ public MethodHandle bind(Object receiver, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { Class<? extends Object> refc = receiver.getClass(); // may get NPE MemberName method = resolveOrFail(REF_invokeSpecial, refc, name, type); MethodHandle mh = getDirectMethodNoRestrict(REF_invokeSpecial, refc, method, findBoundCallerClass(method)); return mh.bindArgumentL(0, receiver).setVarargs(method); } /** * Makes a <a href="MethodHandleInfo.html#directmh">direct method handle</a> * to <i>m</i>, if the lookup class has permission. * If <i>m</i> is non-static, the receiver argument is treated as an initial argument. * If <i>m</i> is virtual, overriding is respected on every call. * Unlike the Core Reflection API, exceptions are <em>not</em> wrapped. * The type of the method handle will be that of the method, * with the receiver type prepended (but only if it is non-static). * If the method's {@code accessible} flag is not set, * access checking is performed immediately on behalf of the lookup class. * If <i>m</i> is not public, do not share the resulting handle with untrusted parties. * <p> * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit ({@code 0x0080}) is set. * <p> * If <i>m</i> is static, and * if the returned method handle is invoked, the method's class will * be initialized, if it has not already been initialized. * @param m the reflected method * @return a method handle which can invoke the reflected method * @throws IllegalAccessException if access checking fails * or if the method's variable arity modifier bit * is set and {@code asVarargsCollector} fails * @throws NullPointerException if the argument is null */ public MethodHandle unreflect(Method m) throws IllegalAccessException { if (m.getDeclaringClass() == MethodHandle.class) { MethodHandle mh = unreflectForMH(m); if (mh != null) return mh; } if (m.getDeclaringClass() == VarHandle.class) { MethodHandle mh = unreflectForVH(m); if (mh != null) return mh; } MemberName method = new MemberName(m); byte refKind = method.getReferenceKind(); if (refKind == REF_invokeSpecial) refKind = REF_invokeVirtual; assert(method.isMethod()); Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this; return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method)); } private MethodHandle unreflectForMH(Method m) { // these names require special lookups because they throw UnsupportedOperationException if (MemberName.isMethodHandleInvokeName(m.getName())) return MethodHandleImpl.fakeMethodHandleInvoke(new MemberName(m)); return null; } private MethodHandle unreflectForVH(Method m) { // these names require special lookups because they throw UnsupportedOperationException if (MemberName.isVarHandleMethodInvokeName(m.getName())) return MethodHandleImpl.fakeVarHandleInvoke(new MemberName(m)); return null; } /** * Produces a method handle for a reflected method. * It will bypass checks for overriding methods on the receiver, * <a href="MethodHandles.Lookup.html#equiv">as if called</a> from an {@code invokespecial} * instruction from within the explicitly specified {@code specialCaller}. * The type of the method handle will be that of the method, * with a suitably restricted receiver type prepended. * (The receiver type will be {@code specialCaller} or a subtype.) * If the method's {@code accessible} flag is not set, * access checking is performed immediately on behalf of the lookup class, * as if {@code invokespecial} instruction were being linked. * <p> * Before method resolution, * if the explicitly specified caller class is not identical with the * lookup class, or if this lookup object does not have * <a href="MethodHandles.Lookup.html#privacc">private access</a> * privileges, the access fails. * <p> * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the method's variable arity modifier bit ({@code 0x0080}) is set. * @param m the reflected method * @param specialCaller the class nominally calling the method * @return a method handle which can invoke the reflected method * @throws IllegalAccessException if access checking fails, * or if the method is {@code static}, * or if the method's variable arity modifier bit * is set and {@code asVarargsCollector} fails * @throws NullPointerException if any argument is null */ public MethodHandle unreflectSpecial(Method m, Class<?> specialCaller) throws IllegalAccessException { checkSpecialCaller(specialCaller, null); Lookup specialLookup = this.in(specialCaller); MemberName method = new MemberName(m, true); assert(method.isMethod()); // ignore m.isAccessible: this is a new kind of access return specialLookup.getDirectMethodNoSecurityManager(REF_invokeSpecial, method.getDeclaringClass(), method, findBoundCallerClass(method)); } /** * Produces a method handle for a reflected constructor. * The type of the method handle will be that of the constructor, * with the return type changed to the declaring class. * The method handle will perform a {@code newInstance} operation, * creating a new instance of the constructor's class on the * arguments passed to the method handle. * <p> * If the constructor's {@code accessible} flag is not set, * access checking is performed immediately on behalf of the lookup class. * <p> * The returned method handle will have * {@linkplain MethodHandle#asVarargsCollector variable arity} if and only if * the constructor's variable arity modifier bit ({@code 0x0080}) is set. * <p> * If the returned method handle is invoked, the constructor's class will * be initialized, if it has not already been initialized. * @param c the reflected constructor * @return a method handle which can invoke the reflected constructor * @throws IllegalAccessException if access checking fails * or if the method's variable arity modifier bit * is set and {@code asVarargsCollector} fails * @throws NullPointerException if the argument is null */ public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException { MemberName ctor = new MemberName(c); assert(ctor.isConstructor()); Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this; return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor); } /** * Produces a method handle giving read access to a reflected field. * The type of the method handle will have a return type of the field's * value type. * If the field is static, the method handle will take no arguments. * Otherwise, its single argument will be the instance containing * the field. * If the field's {@code accessible} flag is not set, * access checking is performed immediately on behalf of the lookup class. * <p> * If the field is static, and * if the returned method handle is invoked, the field's class will * be initialized, if it has not already been initialized. * @param f the reflected field * @return a method handle which can load values from the reflected field * @throws IllegalAccessException if access checking fails * @throws NullPointerException if the argument is null */ public MethodHandle unreflectGetter(Field f) throws IllegalAccessException { return unreflectField(f, false); } private MethodHandle unreflectField(Field f, boolean isSetter) throws IllegalAccessException { MemberName field = new MemberName(f, isSetter); assert(isSetter ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind()) : MethodHandleNatives.refKindIsGetter(field.getReferenceKind())); Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this; return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field); } /** * Produces a method handle giving write access to a reflected field. * The type of the method handle will have a void return type. * If the field is static, the method handle will take a single * argument, of the field's value type, the value to be stored. * Otherwise, the two arguments will be the instance containing * the field, and the value to be stored. * If the field's {@code accessible} flag is not set, * access checking is performed immediately on behalf of the lookup class. * <p> * If the field is static, and * if the returned method handle is invoked, the field's class will * be initialized, if it has not already been initialized. * @param f the reflected field * @return a method handle which can store values into the reflected field * @throws IllegalAccessException if access checking fails * @throws NullPointerException if the argument is null */ public MethodHandle unreflectSetter(Field f) throws IllegalAccessException { return unreflectField(f, true); } /** * Produces a VarHandle that accesses fields of type {@code T} declared * by a class of type {@code R}, as described by the given reflected * field. * If the field is non-static the VarHandle supports a shape of * {@code (R : T)}, otherwise supports a shape of {@code ((empty) : T)}. * <p> * Access checking is performed immediately on behalf of the lookup * class, regardless of the value of the field's {@code accessible} * flag. * <p> * If the field is static, and if the returned VarHandle is operated * on, the field's declaring class will be initialized, if it has not * already been initialized. * <p> * Certain access modes of the returned VarHandle are unsupported under * the following conditions: * <ul> * <li>if the field is declared {@code final}, then the write, atomic * update, and numeric atomic update access modes are unsupported. * <li>if the field type is anything other than {@code byte}, * {@code short}, {@code char}, {@code int} or {@code long}, * {@code float}, or {@code double} then numeric atomic update * access modes are unsupported. * </ul> * <p> * If the field is declared {@code volatile} then the returned VarHandle * will override access to the field (effectively ignore the * {@code volatile} declaration) in accordance to it's specified * access modes. * <p> * If the field type is {@code float} or {@code double} then numeric * and atomic update access modes compare values using their bitwise * representation (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @apiNote * Bitwise comparison of {@code float} values or {@code double} values, * as performed by the numeric and atomic update access modes, differ * from the primitive {@code ==} operator and the {@link Float#equals} * and {@link Double#equals} methods, specifically with respect to * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. * Care should be taken when performing a compare and set or a compare * and exchange operation with such values since the operation may * unexpectedly fail. * There are many possible NaN values that are considered to be * {@code NaN} in Java, although no IEEE 754 floating-point operation * provided by Java can distinguish between them. Operation failure can * occur if the expected or witness value is a NaN value and it is * transformed (perhaps in a platform specific manner) into another NaN * value, and thus has a different bitwise representation (see * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more * details). * The values {@code -0.0} and {@code +0.0} have different bitwise * representations but are considered equal when using the primitive * {@code ==} operator. Operation failure can occur if, for example, a * numeric algorithm computes an expected value to be say {@code -0.0} * and previously computed the witness value to be say {@code +0.0}. * @param f the reflected field, with a field of type {@code T}, and * a declaring class of type {@code R} * @return a VarHandle giving access to non-static fields or a static * field * @throws IllegalAccessException if access checking fails * @throws NullPointerException if the argument is null * @since 9 */ public VarHandle unreflectVarHandle(Field f) throws IllegalAccessException { MemberName getField = new MemberName(f, false); MemberName putField = new MemberName(f, true); return getFieldVarHandleNoSecurityManager(getField.getReferenceKind(), putField.getReferenceKind(), f.getDeclaringClass(), getField, putField); } /** * Cracks a <a href="MethodHandleInfo.html#directmh">direct method handle</a> * created by this lookup object or a similar one. * Security and access checks are performed to ensure that this lookup object * is capable of reproducing the target method handle. * This means that the cracking may fail if target is a direct method handle * but was created by an unrelated lookup object. * This can happen if the method handle is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a> * and was created by a lookup object for a different class. * @param target a direct method handle to crack into symbolic reference components * @return a symbolic reference which can be used to reconstruct this method handle from this lookup object * @exception SecurityException if a security manager is present and it * <a href="MethodHandles.Lookup.html#secmgr">refuses access</a> * @throws IllegalArgumentException if the target is not a direct method handle or if access checking fails * @exception NullPointerException if the target is {@code null} * @see MethodHandleInfo * @since 1.8 */ public MethodHandleInfo revealDirect(MethodHandle target) { MemberName member = target.internalMemberName(); if (member == null || (!member.isResolved() && !member.isMethodHandleInvoke() && !member.isVarHandleMethodInvoke())) throw newIllegalArgumentException("not a direct method handle"); Class<?> defc = member.getDeclaringClass(); byte refKind = member.getReferenceKind(); assert(MethodHandleNatives.refKindIsValid(refKind)); if (refKind == REF_invokeSpecial && !target.isInvokeSpecial()) // Devirtualized method invocation is usually formally virtual. // To avoid creating extra MemberName objects for this common case, // we encode this extra degree of freedom using MH.isInvokeSpecial. refKind = REF_invokeVirtual; if (refKind == REF_invokeVirtual && defc.isInterface()) // Symbolic reference is through interface but resolves to Object method (toString, etc.) refKind = REF_invokeInterface; // Check SM permissions and member access before cracking. try { checkAccess(refKind, defc, member); checkSecurityManager(defc, member); } catch (IllegalAccessException ex) { throw new IllegalArgumentException(ex); } if (allowedModes != TRUSTED && member.isCallerSensitive()) { Class<?> callerClass = target.internalCallerClass(); if (!hasPrivateAccess() || callerClass != lookupClass()) throw new IllegalArgumentException("method handle is caller sensitive: "+callerClass); } // Produce the handle to the results. return new InfoFromMemberName(this, member, refKind); } /// Helper methods, all package-private. MemberName resolveOrFail(byte refKind, Class<?> refc, String name, Class<?> type) throws NoSuchFieldException, IllegalAccessException { checkSymbolicClass(refc); // do this before attempting to resolve Objects.requireNonNull(name); Objects.requireNonNull(type); return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), NoSuchFieldException.class); } MemberName resolveOrFail(byte refKind, Class<?> refc, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException { checkSymbolicClass(refc); // do this before attempting to resolve Objects.requireNonNull(name); Objects.requireNonNull(type); checkMethodName(refKind, name); // NPE check on name return IMPL_NAMES.resolveOrFail(refKind, new MemberName(refc, name, type, refKind), lookupClassOrNull(), NoSuchMethodException.class); } MemberName resolveOrFail(byte refKind, MemberName member) throws ReflectiveOperationException { checkSymbolicClass(member.getDeclaringClass()); // do this before attempting to resolve Objects.requireNonNull(member.getName()); Objects.requireNonNull(member.getType()); return IMPL_NAMES.resolveOrFail(refKind, member, lookupClassOrNull(), ReflectiveOperationException.class); } void checkSymbolicClass(Class<?> refc) throws IllegalAccessException { Objects.requireNonNull(refc); Class<?> caller = lookupClassOrNull(); if (caller != null && !VerifyAccess.isClassAccessible(refc, caller, allowedModes)) throw new MemberName(refc).makeAccessException("symbolic reference class is not accessible", this); } /** Check name for an illegal leading "&lt;" character. */ void checkMethodName(byte refKind, String name) throws NoSuchMethodException { if (name.startsWith("<") && refKind != REF_newInvokeSpecial) throw new NoSuchMethodException("illegal method name: "+name); } /** * Find my trustable caller class if m is a caller sensitive method. * If this lookup object has private access, then the caller class is the lookupClass. * Otherwise, if m is caller-sensitive, throw IllegalAccessException. */ Class<?> findBoundCallerClass(MemberName m) throws IllegalAccessException { Class<?> callerClass = null; if (MethodHandleNatives.isCallerSensitive(m)) { // Only lookups with private access are allowed to resolve caller-sensitive methods if (hasPrivateAccess()) { callerClass = lookupClass; } else { throw new IllegalAccessException("Attempt to lookup caller-sensitive method using restricted lookup object"); } } return callerClass; } private boolean hasPrivateAccess() { return (allowedModes & PRIVATE) != 0; } /** * Perform necessary <a href="MethodHandles.Lookup.html#secmgr">access checks</a>. * Determines a trustable caller class to compare with refc, the symbolic reference class. * If this lookup object has private access, then the caller class is the lookupClass. */ void checkSecurityManager(Class<?> refc, MemberName m) { SecurityManager smgr = System.getSecurityManager(); if (smgr == null) return; if (allowedModes == TRUSTED) return; // Step 1: boolean fullPowerLookup = hasPrivateAccess(); if (!fullPowerLookup || !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { ReflectUtil.checkPackageAccess(refc); } if (m == null) { // findClass or accessClass // Step 2b: if (!fullPowerLookup) { smgr.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); } return; } // Step 2a: if (m.isPublic()) return; if (!fullPowerLookup) { smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); } // Step 3: Class<?> defc = m.getDeclaringClass(); if (!fullPowerLookup && defc != refc) { ReflectUtil.checkPackageAccess(defc); } } void checkMethod(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { boolean wantStatic = (refKind == REF_invokeStatic); String message; if (m.isConstructor()) message = "expected a method, not a constructor"; else if (!m.isMethod()) message = "expected a method"; else if (wantStatic != m.isStatic()) message = wantStatic ? "expected a static method" : "expected a non-static method"; else { checkAccess(refKind, refc, m); return; } throw m.makeAccessException(message, this); } void checkField(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { boolean wantStatic = !MethodHandleNatives.refKindHasReceiver(refKind); String message; if (wantStatic != m.isStatic()) message = wantStatic ? "expected a static field" : "expected a non-static field"; else { checkAccess(refKind, refc, m); return; } throw m.makeAccessException(message, this); } /** Check public/protected/private bits on the symbolic reference class and its member. */ void checkAccess(byte refKind, Class<?> refc, MemberName m) throws IllegalAccessException { assert(m.referenceKindIsConsistentWith(refKind) && MethodHandleNatives.refKindIsValid(refKind) && (MethodHandleNatives.refKindIsField(refKind) == m.isField())); int allowedModes = this.allowedModes; if (allowedModes == TRUSTED) return; int mods = m.getModifiers(); if (Modifier.isProtected(mods) && refKind == REF_invokeVirtual && m.getDeclaringClass() == Object.class && m.getName().equals("clone") && refc.isArray()) { // The JVM does this hack also. // (See ClassVerifier::verify_invoke_instructions // and LinkResolver::check_method_accessability.) // Because the JVM does not allow separate methods on array types, // there is no separate method for int[].clone. // All arrays simply inherit Object.clone. // But for access checking logic, we make Object.clone // (normally protected) appear to be public. // Later on, when the DirectMethodHandle is created, // its leading argument will be restricted to the // requested array type. // N.B. The return type is not adjusted, because // that is *not* the bytecode behavior. mods ^= Modifier.PROTECTED | Modifier.PUBLIC; } if (Modifier.isProtected(mods) && refKind == REF_newInvokeSpecial) { // cannot "new" a protected ctor in a different package mods ^= Modifier.PROTECTED; } if (Modifier.isFinal(mods) && MethodHandleNatives.refKindIsSetter(refKind)) throw m.makeAccessException("unexpected set of a final field", this); int requestedModes = fixmods(mods); // adjust 0 => PACKAGE if ((requestedModes & allowedModes) != 0) { if (VerifyAccess.isMemberAccessible(refc, m.getDeclaringClass(), mods, lookupClass(), allowedModes)) return; } else { // Protected members can also be checked as if they were package-private. if ((requestedModes & PROTECTED) != 0 && (allowedModes & PACKAGE) != 0 && VerifyAccess.isSamePackage(m.getDeclaringClass(), lookupClass())) return; } throw m.makeAccessException(accessFailedMessage(refc, m), this); } String accessFailedMessage(Class<?> refc, MemberName m) { Class<?> defc = m.getDeclaringClass(); int mods = m.getModifiers(); // check the class first: boolean classOK = (Modifier.isPublic(defc.getModifiers()) && (defc == refc || Modifier.isPublic(refc.getModifiers()))); if (!classOK && (allowedModes & PACKAGE) != 0) { classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) && (defc == refc || VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES))); } if (!classOK) return "class is not public"; if (Modifier.isPublic(mods)) return "access to public member failed"; // (how?, module not readable?) if (Modifier.isPrivate(mods)) return "member is private"; if (Modifier.isProtected(mods)) return "member is protected"; return "member is private to package"; } private static final boolean ALLOW_NESTMATE_ACCESS = false; private void checkSpecialCaller(Class<?> specialCaller, Class<?> refc) throws IllegalAccessException { int allowedModes = this.allowedModes; if (allowedModes == TRUSTED) return; if (!hasPrivateAccess() || (specialCaller != lookupClass() // ensure non-abstract methods in superinterfaces can be special-invoked && !(refc != null && refc.isInterface() && refc.isAssignableFrom(specialCaller)) && !(ALLOW_NESTMATE_ACCESS && VerifyAccess.isSamePackageMember(specialCaller, lookupClass())))) throw new MemberName(specialCaller). makeAccessException("no private access for invokespecial", this); } private boolean restrictProtectedReceiver(MemberName method) { // The accessing class only has the right to use a protected member // on itself or a subclass. Enforce that restriction, from JVMS 5.4.4, etc. if (!method.isProtected() || method.isStatic() || allowedModes == TRUSTED || method.getDeclaringClass() == lookupClass() || VerifyAccess.isSamePackage(method.getDeclaringClass(), lookupClass()) || (ALLOW_NESTMATE_ACCESS && VerifyAccess.isSamePackageMember(method.getDeclaringClass(), lookupClass()))) return false; return true; } private MethodHandle restrictReceiver(MemberName method, DirectMethodHandle mh, Class<?> caller) throws IllegalAccessException { assert(!method.isStatic()); // receiver type of mh is too wide; narrow to caller if (!method.getDeclaringClass().isAssignableFrom(caller)) { throw method.makeAccessException("caller class must be a subclass below the method", caller); } MethodType rawType = mh.type(); if (rawType.parameterType(0) == caller) return mh; MethodType narrowType = rawType.changeParameterType(0, caller); assert(!mh.isVarargsCollector()); // viewAsType will lose varargs-ness assert(mh.viewAsTypeChecks(narrowType, true)); return mh.copyWith(narrowType, mh.form); } /** Check access and get the requested method. */ private MethodHandle getDirectMethod(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { final boolean doRestrict = true; final boolean checkSecurity = true; return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); } /** Check access and get the requested method, eliding receiver narrowing rules. */ private MethodHandle getDirectMethodNoRestrict(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { final boolean doRestrict = false; final boolean checkSecurity = true; return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); } /** Check access and get the requested method, eliding security manager checks. */ private MethodHandle getDirectMethodNoSecurityManager(byte refKind, Class<?> refc, MemberName method, Class<?> callerClass) throws IllegalAccessException { final boolean doRestrict = true; final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants return getDirectMethodCommon(refKind, refc, method, checkSecurity, doRestrict, callerClass); } /** Common code for all methods; do not call directly except from immediately above. */ private MethodHandle getDirectMethodCommon(byte refKind, Class<?> refc, MemberName method, boolean checkSecurity, boolean doRestrict, Class<?> callerClass) throws IllegalAccessException { checkMethod(refKind, refc, method); // Optionally check with the security manager; this isn't needed for unreflect* calls. if (checkSecurity) checkSecurityManager(refc, method); assert(!method.isMethodHandleInvoke()); if (refKind == REF_invokeSpecial && refc != lookupClass() && !refc.isInterface() && refc != lookupClass().getSuperclass() && refc.isAssignableFrom(lookupClass())) { assert(!method.getName().equals("<init>")); // not this code path // Per JVMS 6.5, desc. of invokespecial instruction: // If the method is in a superclass of the LC, // and if our original search was above LC.super, // repeat the search (symbolic lookup) from LC.super // and continue with the direct superclass of that class, // and so forth, until a match is found or no further superclasses exist. // FIXME: MemberName.resolve should handle this instead. Class<?> refcAsSuper = lookupClass(); MemberName m2; do { refcAsSuper = refcAsSuper.getSuperclass(); m2 = new MemberName(refcAsSuper, method.getName(), method.getMethodType(), REF_invokeSpecial); m2 = IMPL_NAMES.resolveOrNull(refKind, m2, lookupClassOrNull()); } while (m2 == null && // no method is found yet refc != refcAsSuper); // search up to refc if (m2 == null) throw new InternalError(method.toString()); method = m2; refc = refcAsSuper; // redo basic checks checkMethod(refKind, refc, method); } DirectMethodHandle dmh = DirectMethodHandle.make(refKind, refc, method); MethodHandle mh = dmh; // Optionally narrow the receiver argument to refc using restrictReceiver. if (doRestrict && (refKind == REF_invokeSpecial || (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(method)))) { mh = restrictReceiver(method, dmh, lookupClass()); } mh = maybeBindCaller(method, mh, callerClass); mh = mh.setVarargs(method); return mh; } private MethodHandle maybeBindCaller(MemberName method, MethodHandle mh, Class<?> callerClass) throws IllegalAccessException { if (allowedModes == TRUSTED || !MethodHandleNatives.isCallerSensitive(method)) return mh; Class<?> hostClass = lookupClass; if (!hasPrivateAccess()) // caller must have private access hostClass = callerClass; // callerClass came from a security manager style stack walk MethodHandle cbmh = MethodHandleImpl.bindCaller(mh, hostClass); // Note: caller will apply varargs after this step happens. return cbmh; } /** Check access and get the requested field. */ private MethodHandle getDirectField(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { final boolean checkSecurity = true; return getDirectFieldCommon(refKind, refc, field, checkSecurity); } /** Check access and get the requested field, eliding security manager checks. */ private MethodHandle getDirectFieldNoSecurityManager(byte refKind, Class<?> refc, MemberName field) throws IllegalAccessException { final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants return getDirectFieldCommon(refKind, refc, field, checkSecurity); } /** Common code for all fields; do not call directly except from immediately above. */ private MethodHandle getDirectFieldCommon(byte refKind, Class<?> refc, MemberName field, boolean checkSecurity) throws IllegalAccessException { checkField(refKind, refc, field); // Optionally check with the security manager; this isn't needed for unreflect* calls. if (checkSecurity) checkSecurityManager(refc, field); DirectMethodHandle dmh = DirectMethodHandle.make(refc, field); boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(refKind) && restrictProtectedReceiver(field)); if (doRestrict) return restrictReceiver(field, dmh, lookupClass()); return dmh; } private VarHandle getFieldVarHandle(byte getRefKind, byte putRefKind, Class<?> refc, MemberName getField, MemberName putField) throws IllegalAccessException { final boolean checkSecurity = true; return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); } private VarHandle getFieldVarHandleNoSecurityManager(byte getRefKind, byte putRefKind, Class<?> refc, MemberName getField, MemberName putField) throws IllegalAccessException { final boolean checkSecurity = false; return getFieldVarHandleCommon(getRefKind, putRefKind, refc, getField, putField, checkSecurity); } private VarHandle getFieldVarHandleCommon(byte getRefKind, byte putRefKind, Class<?> refc, MemberName getField, MemberName putField, boolean checkSecurity) throws IllegalAccessException { assert getField.isStatic() == putField.isStatic(); assert getField.isGetter() && putField.isSetter(); assert MethodHandleNatives.refKindIsStatic(getRefKind) == MethodHandleNatives.refKindIsStatic(putRefKind); assert MethodHandleNatives.refKindIsGetter(getRefKind) && MethodHandleNatives.refKindIsSetter(putRefKind); checkField(getRefKind, refc, getField); if (checkSecurity) checkSecurityManager(refc, getField); if (!putField.isFinal()) { // A VarHandle does not support updates to final fields, any // such VarHandle to a final field will be read-only and // therefore the following write-based accessibility checks are // only required for non-final fields checkField(putRefKind, refc, putField); if (checkSecurity) checkSecurityManager(refc, putField); } boolean doRestrict = (MethodHandleNatives.refKindHasReceiver(getRefKind) && restrictProtectedReceiver(getField)); if (doRestrict) { assert !getField.isStatic(); // receiver type of VarHandle is too wide; narrow to caller if (!getField.getDeclaringClass().isAssignableFrom(lookupClass())) { throw getField.makeAccessException("caller class must be a subclass below the method", lookupClass()); } refc = lookupClass(); } return VarHandles.makeFieldHandle(getField, refc, getField.getFieldType(), this.allowedModes == TRUSTED); } /** Check access and get the requested constructor. */ private MethodHandle getDirectConstructor(Class<?> refc, MemberName ctor) throws IllegalAccessException { final boolean checkSecurity = true; return getDirectConstructorCommon(refc, ctor, checkSecurity); } /** Check access and get the requested constructor, eliding security manager checks. */ private MethodHandle getDirectConstructorNoSecurityManager(Class<?> refc, MemberName ctor) throws IllegalAccessException { final boolean checkSecurity = false; // not needed for reflection or for linking CONSTANT_MH constants return getDirectConstructorCommon(refc, ctor, checkSecurity); } /** Common code for all constructors; do not call directly except from immediately above. */ private MethodHandle getDirectConstructorCommon(Class<?> refc, MemberName ctor, boolean checkSecurity) throws IllegalAccessException { assert(ctor.isConstructor()); checkAccess(REF_newInvokeSpecial, refc, ctor); // Optionally check with the security manager; this isn't needed for unreflect* calls. if (checkSecurity) checkSecurityManager(refc, ctor); assert(!MethodHandleNatives.isCallerSensitive(ctor)); // maybeBindCaller not relevant here return DirectMethodHandle.make(ctor).setVarargs(ctor); } /** Hook called from the JVM (via MethodHandleNatives) to link MH constants: */ /*non-public*/ MethodHandle linkMethodHandleConstant(byte refKind, Class<?> defc, String name, Object type) throws ReflectiveOperationException { if (!(type instanceof Class || type instanceof MethodType)) throw new InternalError("unresolved MemberName"); MemberName member = new MemberName(refKind, defc, name, type); MethodHandle mh = LOOKASIDE_TABLE.get(member); if (mh != null) { checkSymbolicClass(defc); return mh; } // Treat MethodHandle.invoke and invokeExact specially. if (defc == MethodHandle.class && refKind == REF_invokeVirtual) { mh = findVirtualForMH(member.getName(), member.getMethodType()); if (mh != null) { return mh; } } MemberName resolved = resolveOrFail(refKind, member); mh = getDirectMethodForConstant(refKind, defc, resolved); if (mh instanceof DirectMethodHandle && canBeCached(refKind, defc, resolved)) { MemberName key = mh.internalMemberName(); if (key != null) { key = key.asNormalOriginal(); } if (member.equals(key)) { // better safe than sorry LOOKASIDE_TABLE.put(key, (DirectMethodHandle) mh); } } return mh; } private boolean canBeCached(byte refKind, Class<?> defc, MemberName member) { if (refKind == REF_invokeSpecial) { return false; } if (!Modifier.isPublic(defc.getModifiers()) || !Modifier.isPublic(member.getDeclaringClass().getModifiers()) || !member.isPublic() || member.isCallerSensitive()) { return false; } ClassLoader loader = defc.getClassLoader(); if (!jdk.internal.misc.VM.isSystemDomainLoader(loader)) { ClassLoader sysl = ClassLoader.getSystemClassLoader(); boolean found = false; while (sysl != null) { if (loader == sysl) { found = true; break; } sysl = sysl.getParent(); } if (!found) { return false; } } try { MemberName resolved2 = publicLookup().resolveOrFail(refKind, new MemberName(refKind, defc, member.getName(), member.getType())); checkSecurityManager(defc, resolved2); } catch (ReflectiveOperationException | SecurityException ex) { return false; } return true; } private MethodHandle getDirectMethodForConstant(byte refKind, Class<?> defc, MemberName member) throws ReflectiveOperationException { if (MethodHandleNatives.refKindIsField(refKind)) { return getDirectFieldNoSecurityManager(refKind, defc, member); } else if (MethodHandleNatives.refKindIsMethod(refKind)) { return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass); } else if (refKind == REF_newInvokeSpecial) { return getDirectConstructorNoSecurityManager(defc, member); } // oops throw newIllegalArgumentException("bad MethodHandle constant #"+member); } static ConcurrentHashMap<MemberName, DirectMethodHandle> LOOKASIDE_TABLE = new ConcurrentHashMap<>(); } /** * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class * in an <em>unnamed module</em>. * * @see Lookup#publicLookup */ private static class LookupHelper { private static final String UNNAMED = "Unnamed"; private static final String OBJECT = "java/lang/Object"; private static Class<?> createClass() { try { ClassWriter cw = new ClassWriter(0); cw.visit(Opcodes.V1_8, Opcodes.ACC_FINAL + Opcodes.ACC_SUPER, UNNAMED, null, OBJECT, null); cw.visitSource(UNNAMED, null); cw.visitEnd(); byte[] bytes = cw.toByteArray(); ClassLoader loader = new ClassLoader(null) { @Override protected Class<?> findClass(String cn) throws ClassNotFoundException { if (cn.equals(UNNAMED)) return super.defineClass(UNNAMED, bytes, 0, bytes.length); throw new ClassNotFoundException(cn); } }; return loader.loadClass(UNNAMED); } catch (Exception e) { throw new InternalError(e); } } private static final Class<?> PUBLIC_LOOKUP_CLASS = createClass(); /** * Lookup that is trusted minimally. It can only be used to create * method handles to publicly accessible members in exported packages. * * @see MethodHandles#publicLookup */ static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC); } /** * Produces a method handle constructing arrays of a desired type. * The return type of the method handle will be the array type. * The type of its sole argument will be {@code int}, which specifies the size of the array. * @param arrayClass an array type * @return a method handle which can create arrays of the given type * @throws NullPointerException if the argument is {@code null} * @throws IllegalArgumentException if {@code arrayClass} is not an array type * @see java.lang.reflect.Array#newInstance(Class, int) * @since 9 */ public static MethodHandle arrayConstructor(Class<?> arrayClass) throws IllegalArgumentException { if (!arrayClass.isArray()) { throw newIllegalArgumentException("not an array class: " + arrayClass.getName()); } MethodHandle ani = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_Array_newInstance). bindTo(arrayClass.getComponentType()); return ani.asType(ani.type().changeReturnType(arrayClass)); } /** * Produces a method handle returning the length of an array. * The type of the method handle will have {@code int} as return type, * and its sole argument will be the array type. * @param arrayClass an array type * @return a method handle which can retrieve the length of an array of the given array type * @throws NullPointerException if the argument is {@code null} * @throws IllegalArgumentException if arrayClass is not an array type * @since 9 */ public static MethodHandle arrayLength(Class<?> arrayClass) throws IllegalArgumentException { return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.LENGTH); } /** * Produces a method handle giving read access to elements of an array. * The type of the method handle will have a return type of the array's * element type. Its first argument will be the array type, * and the second will be {@code int}. * @param arrayClass an array type * @return a method handle which can load values from the given array type * @throws NullPointerException if the argument is null * @throws IllegalArgumentException if arrayClass is not an array type */ public static MethodHandle arrayElementGetter(Class<?> arrayClass) throws IllegalArgumentException { return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.GET); } /** * Produces a method handle giving write access to elements of an array. * The type of the method handle will have a void return type. * Its last argument will be the array's element type. * The first and second arguments will be the array type and int. * @param arrayClass the class of an array * @return a method handle which can store values into the array type * @throws NullPointerException if the argument is null * @throws IllegalArgumentException if arrayClass is not an array type */ public static MethodHandle arrayElementSetter(Class<?> arrayClass) throws IllegalArgumentException { return MethodHandleImpl.makeArrayElementAccessor(arrayClass, MethodHandleImpl.ArrayAccess.SET); } /** * * Produces a VarHandle giving access to elements of an array type * {@code T[]}, supporting shape {@code (T[], int : T)}. * <p> * Certain access modes of the returned VarHandle are unsupported under * the following conditions: * <ul> * <li>if the component type is anything other than {@code byte}, * {@code short}, {@code char}, {@code int} or {@code long}, * {@code float}, or {@code double} then numeric atomic update access * modes are unsupported. * </ul> * <p> * If the component type is {@code float} or {@code double} then numeric * and atomic update access modes compare values using their bitwise * representation (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @apiNote * Bitwise comparison of {@code float} values or {@code double} values, * as performed by the numeric and atomic update access modes, differ * from the primitive {@code ==} operator and the {@link Float#equals} * and {@link Double#equals} methods, specifically with respect to * comparing NaN values or comparing {@code -0.0} with {@code +0.0}. * Care should be taken when performing a compare and set or a compare * and exchange operation with such values since the operation may * unexpectedly fail. * There are many possible NaN values that are considered to be * {@code NaN} in Java, although no IEEE 754 floating-point operation * provided by Java can distinguish between them. Operation failure can * occur if the expected or witness value is a NaN value and it is * transformed (perhaps in a platform specific manner) into another NaN * value, and thus has a different bitwise representation (see * {@link Float#intBitsToFloat} or {@link Double#longBitsToDouble} for more * details). * The values {@code -0.0} and {@code +0.0} have different bitwise * representations but are considered equal when using the primitive * {@code ==} operator. Operation failure can occur if, for example, a * numeric algorithm computes an expected value to be say {@code -0.0} * and previously computed the witness value to be say {@code +0.0}. * @param arrayClass the class of an array, of type {@code T[]} * @return a VarHandle giving access to elements of an array * @throws NullPointerException if the arrayClass is null * @throws IllegalArgumentException if arrayClass is not an array type * @since 9 */ public static VarHandle arrayElementVarHandle(Class<?> arrayClass) throws IllegalArgumentException { return VarHandles.makeArrayElementHandle(arrayClass); } /** * Produces a VarHandle giving access to elements of a {@code byte[]} array * viewed as if it were a different primitive array type, such as * {@code int[]} or {@code long[]}. The shape of the resulting VarHandle is * {@code (byte[], int : T)}, where the {@code int} coordinate type * corresponds to an argument that is an index in a {@code byte[]} array, * and {@code T} is the component type of the given view array class. The * returned VarHandle accesses bytes at an index in a {@code byte[]} array, * composing bytes to or from a value of {@code T} according to the given * endianness. * <p> * The supported component types (variables types) are {@code short}, * {@code char}, {@code int}, {@code long}, {@code float} and * {@code double}. * <p> * Access of bytes at a given index will result in an * {@code IndexOutOfBoundsException} if the index is less than {@code 0} * or greater than the {@code byte[]} array length minus the size (in bytes) * of {@code T}. * <p> * Access of bytes at an index may be aligned or misaligned for {@code T}, * with respect to the underlying memory address, {@code A} say, associated * with the array and index. * If access is misaligned then access for anything other than the * {@code get} and {@code set} access modes will result in an * {@code IllegalStateException}. In such cases atomic access is only * guaranteed with respect to the largest power of two that divides the GCD * of {@code A} and the size (in bytes) of {@code T}. * If access is aligned then following access modes are supported and are * guaranteed to support atomic access: * <ul> * <li>read write access modes for all {@code T}; * <li>atomic update access modes for {@code int}, {@code long}, * {@code float} or {@code double}. * (Future major platform releases of the JDK may support additional * types for certain currently unsupported access modes.) * <li>numeric atomic update access modes for {@code int} and {@code long}. * (Future major platform releases of the JDK may support additional * numeric types for certain currently unsupported access modes.) * </ul> * <p> * Misaligned access, and therefore atomicity guarantees, may be determined * for {@code byte[]} arrays without operating on a specific array. Given * an {@code index}, {@code T} and it's corresponding boxed type, * {@code T_BOX}, misalignment may be determined as follows: * <pre>{@code * int sizeOfT = T_BOX.BYTES; // size in bytes of T * int misalignedAtZeroIndex = ByteBuffer.wrap(new byte[0]). * alignmentOffset(0, sizeOfT); * int misalignedAtIndex = (misalignedAtZeroIndex + index) % sizeOfT; * boolean isMisaligned = misalignedAtIndex != 0; * }</pre> * <p> * If the variable type is {@code float} or {@code double} then atomic * update access modes compare values using their bitwise representation * (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @param viewArrayClass the view array class, with a component type of * type {@code T} * @param byteOrder the endianness of the view array elements, as * stored in the underlying {@code byte} array * @return a VarHandle giving access to elements of a {@code byte[]} array * viewed as if elements corresponding to the components type of the view * array class * @throws NullPointerException if viewArrayClass or byteOrder is null * @throws IllegalArgumentException if viewArrayClass is not an array type * @throws UnsupportedOperationException if the component type of * viewArrayClass is not supported as a variable type * @since 9 */ public static VarHandle byteArrayViewVarHandle(Class<?> viewArrayClass, ByteOrder byteOrder) throws IllegalArgumentException { Objects.requireNonNull(byteOrder); return VarHandles.byteArrayViewHandle(viewArrayClass, byteOrder == ByteOrder.BIG_ENDIAN); } /** * Produces a VarHandle giving access to elements of a {@code ByteBuffer} * viewed as if it were an array of elements of a different primitive * component type to that of {@code byte}, such as {@code int[]} or * {@code long[]}. The shape of the resulting VarHandle is * {@code (ByteBuffer, int : T)}, where the {@code int} coordinate type * corresponds to an argument that is an index in a {@code ByteBuffer}, and * {@code T} is the component type of the given view array class. The * returned VarHandle accesses bytes at an index in a {@code ByteBuffer}, * composing bytes to or from a value of {@code T} according to the given * endianness. * <p> * The supported component types (variables types) are {@code short}, * {@code char}, {@code int}, {@code long}, {@code float} and * {@code double}. * <p> * Access will result in a {@code ReadOnlyBufferException} for anything * other than the read access modes if the {@code ByteBuffer} is read-only. * <p> * Access of bytes at a given index will result in an * {@code IndexOutOfBoundsException} if the index is less than {@code 0} * or greater than the {@code ByteBuffer} limit minus the size (in bytes) of * {@code T}. * <p> * Access of bytes at an index may be aligned or misaligned for {@code T}, * with respect to the underlying memory address, {@code A} say, associated * with the {@code ByteBuffer} and index. * If access is misaligned then access for anything other than the * {@code get} and {@code set} access modes will result in an * {@code IllegalStateException}. In such cases atomic access is only * guaranteed with respect to the largest power of two that divides the GCD * of {@code A} and the size (in bytes) of {@code T}. * If access is aligned then following access modes are supported and are * guaranteed to support atomic access: * <ul> * <li>read write access modes for all {@code T}; * <li>atomic update access modes for {@code int}, {@code long}, * {@code float} or {@code double}. * (Future major platform releases of the JDK may support additional * types for certain currently unsupported access modes.) * <li>numeric atomic update access modes for {@code int} and {@code long}. * (Future major platform releases of the JDK may support additional * numeric types for certain currently unsupported access modes.) * </ul> * <p> * Misaligned access, and therefore atomicity guarantees, may be determined * for a {@code ByteBuffer}, {@code bb} (direct or otherwise), an * {@code index}, {@code T} and it's corresponding boxed type, * {@code T_BOX}, as follows: * <pre>{@code * int sizeOfT = T_BOX.BYTES; // size in bytes of T * ByteBuffer bb = ... * int misalignedAtIndex = bb.alignmentOffset(index, sizeOfT); * boolean isMisaligned = misalignedAtIndex != 0; * }</pre> * <p> * If the variable type is {@code float} or {@code double} then atomic * update access modes compare values using their bitwise representation * (see {@link Float#floatToRawIntBits} and * {@link Double#doubleToRawLongBits}, respectively). * @param viewArrayClass the view array class, with a component type of * type {@code T} * @param byteOrder the endianness of the view array elements, as * stored in the underlying {@code ByteBuffer} (Note this overrides the * endianness of a {@code ByteBuffer}) * @return a VarHandle giving access to elements of a {@code ByteBuffer} * viewed as if elements corresponding to the components type of the view * array class * @throws NullPointerException if viewArrayClass or byteOrder is null * @throws IllegalArgumentException if viewArrayClass is not an array type * @throws UnsupportedOperationException if the component type of * viewArrayClass is not supported as a variable type * @since 9 */ public static VarHandle byteBufferViewVarHandle(Class<?> viewArrayClass, ByteOrder byteOrder) throws IllegalArgumentException { Objects.requireNonNull(byteOrder); return VarHandles.makeByteBufferViewHandle(viewArrayClass, byteOrder == ByteOrder.BIG_ENDIAN); } /// method handle invocation (reflective style) /** * Produces a method handle which will invoke any method handle of the * given {@code type}, with a given number of trailing arguments replaced by * a single trailing {@code Object[]} array. * The resulting invoker will be a method handle with the following * arguments: * <ul> * <li>a single {@code MethodHandle} target * <li>zero or more leading values (counted by {@code leadingArgCount}) * <li>an {@code Object[]} array containing trailing arguments * </ul> * <p> * The invoker will invoke its target like a call to {@link MethodHandle#invoke invoke} with * the indicated {@code type}. * That is, if the target is exactly of the given {@code type}, it will behave * like {@code invokeExact}; otherwise it behave as if {@link MethodHandle#asType asType} * is used to convert the target to the required {@code type}. * <p> * The type of the returned invoker will not be the given {@code type}, but rather * will have all parameters except the first {@code leadingArgCount} * replaced by a single array of type {@code Object[]}, which will be * the final parameter. * <p> * Before invoking its target, the invoker will spread the final array, apply * reference casts as necessary, and unbox and widen primitive arguments. * If, when the invoker is called, the supplied array argument does * not have the correct number of elements, the invoker will throw * an {@link IllegalArgumentException} instead of invoking the target. * <p> * This method is equivalent to the following code (though it may be more efficient): * <blockquote><pre>{@code MethodHandle invoker = MethodHandles.invoker(type); int spreadArgCount = type.parameterCount() - leadingArgCount; invoker = invoker.asSpreader(Object[].class, spreadArgCount); return invoker; * }</pre></blockquote> * This method throws no reflective or security exceptions. * @param type the desired target type * @param leadingArgCount number of fixed arguments, to be passed unchanged to the target * @return a method handle suitable for invoking any method handle of the given type * @throws NullPointerException if {@code type} is null * @throws IllegalArgumentException if {@code leadingArgCount} is not in * the range from 0 to {@code type.parameterCount()} inclusive, * or if the resulting method handle's type would have * <a href="MethodHandle.html#maxarity">too many parameters</a> */ public static MethodHandle spreadInvoker(MethodType type, int leadingArgCount) { if (leadingArgCount < 0 || leadingArgCount > type.parameterCount()) throw newIllegalArgumentException("bad argument count", leadingArgCount); type = type.asSpreaderType(Object[].class, leadingArgCount, type.parameterCount() - leadingArgCount); return type.invokers().spreadInvoker(leadingArgCount); } /** * Produces a special <em>invoker method handle</em> which can be used to * invoke any method handle of the given type, as if by {@link MethodHandle#invokeExact invokeExact}. * The resulting invoker will have a type which is * exactly equal to the desired type, except that it will accept * an additional leading argument of type {@code MethodHandle}. * <p> * This method is equivalent to the following code (though it may be more efficient): * {@code publicLookup().findVirtual(MethodHandle.class, "invokeExact", type)} * * <p style="font-size:smaller;"> * <em>Discussion:</em> * Invoker method handles can be useful when working with variable method handles * of unknown types. * For example, to emulate an {@code invokeExact} call to a variable method * handle {@code M}, extract its type {@code T}, * look up the invoker method {@code X} for {@code T}, * and call the invoker method, as {@code X.invoke(T, A...)}. * (It would not work to call {@code X.invokeExact}, since the type {@code T} * is unknown.) * If spreading, collecting, or other argument transformations are required, * they can be applied once to the invoker {@code X} and reused on many {@code M} * method handle values, as long as they are compatible with the type of {@code X}. * <p style="font-size:smaller;"> * <em>(Note: The invoker method is not available via the Core Reflection API. * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} * on the declared {@code invokeExact} or {@code invoke} method will raise an * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> * <p> * This method throws no reflective or security exceptions. * @param type the desired target type * @return a method handle suitable for invoking any method handle of the given type * @throws IllegalArgumentException if the resulting method handle's type would have * <a href="MethodHandle.html#maxarity">too many parameters</a> */ public static MethodHandle exactInvoker(MethodType type) { return type.invokers().exactInvoker(); } /** * Produces a special <em>invoker method handle</em> which can be used to * invoke any method handle compatible with the given type, as if by {@link MethodHandle#invoke invoke}. * The resulting invoker will have a type which is * exactly equal to the desired type, except that it will accept * an additional leading argument of type {@code MethodHandle}. * <p> * Before invoking its target, if the target differs from the expected type, * the invoker will apply reference casts as * necessary and box, unbox, or widen primitive values, as if by {@link MethodHandle#asType asType}. * Similarly, the return value will be converted as necessary. * If the target is a {@linkplain MethodHandle#asVarargsCollector variable arity method handle}, * the required arity conversion will be made, again as if by {@link MethodHandle#asType asType}. * <p> * This method is equivalent to the following code (though it may be more efficient): * {@code publicLookup().findVirtual(MethodHandle.class, "invoke", type)} * <p style="font-size:smaller;"> * <em>Discussion:</em> * A {@linkplain MethodType#genericMethodType general method type} is one which * mentions only {@code Object} arguments and return values. * An invoker for such a type is capable of calling any method handle * of the same arity as the general type. * <p style="font-size:smaller;"> * <em>(Note: The invoker method is not available via the Core Reflection API. * An attempt to call {@linkplain java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke} * on the declared {@code invokeExact} or {@code invoke} method will raise an * {@link java.lang.UnsupportedOperationException UnsupportedOperationException}.)</em> * <p> * This method throws no reflective or security exceptions. * @param type the desired target type * @return a method handle suitable for invoking any method handle convertible to the given type * @throws IllegalArgumentException if the resulting method handle's type would have * <a href="MethodHandle.html#maxarity">too many parameters</a> */ public static MethodHandle invoker(MethodType type) { return type.invokers().genericInvoker(); } /** * Produces a special <em>invoker method handle</em> which can be used to * invoke a signature-polymorphic access mode method on any VarHandle whose * associated access mode type is compatible with the given type. * The resulting invoker will have a type which is exactly equal to the * desired given type, except that it will accept an additional leading * argument of type {@code VarHandle}. * * @param accessMode the VarHandle access mode * @param type the desired target type * @return a method handle suitable for invoking an access mode method of * any VarHandle whose access mode type is of the given type. * @since 9 */ static public MethodHandle varHandleExactInvoker(VarHandle.AccessMode accessMode, MethodType type) { return type.invokers().varHandleMethodExactInvoker(accessMode); } /** * Produces a special <em>invoker method handle</em> which can be used to * invoke a signature-polymorphic access mode method on any VarHandle whose * associated access mode type is compatible with the given type. * The resulting invoker will have a type which is exactly equal to the * desired given type, except that it will accept an additional leading * argument of type {@code VarHandle}. * <p> * Before invoking its target, if the access mode type differs from the * desired given type, the invoker will apply reference casts as necessary * and box, unbox, or widen primitive values, as if by * {@link MethodHandle#asType asType}. Similarly, the return value will be * converted as necessary. * <p> * This method is equivalent to the following code (though it may be more * efficient): {@code publicLookup().findVirtual(VarHandle.class, accessMode.name(), type)} * * @param accessMode the VarHandle access mode * @param type the desired target type * @return a method handle suitable for invoking an access mode method of * any VarHandle whose access mode type is convertible to the given * type. * @since 9 */ static public MethodHandle varHandleInvoker(VarHandle.AccessMode accessMode, MethodType type) { return type.invokers().varHandleMethodInvoker(accessMode); } static /*non-public*/ MethodHandle basicInvoker(MethodType type) { return type.invokers().basicInvoker(); } /// method handle modification (creation from other method handles) /** * Produces a method handle which adapts the type of the * given method handle to a new type by pairwise argument and return type conversion. * The original type and new type must have the same number of arguments. * The resulting method handle is guaranteed to report a type * which is equal to the desired new type. * <p> * If the original type and new type are equal, returns target. * <p> * The same conversions are allowed as for {@link MethodHandle#asType MethodHandle.asType}, * and some additional conversions are also applied if those conversions fail. * Given types <em>T0</em>, <em>T1</em>, one of the following conversions is applied * if possible, before or instead of any conversions done by {@code asType}: * <ul> * <li>If <em>T0</em> and <em>T1</em> are references, and <em>T1</em> is an interface type, * then the value of type <em>T0</em> is passed as a <em>T1</em> without a cast. * (This treatment of interfaces follows the usage of the bytecode verifier.) * <li>If <em>T0</em> is boolean and <em>T1</em> is another primitive, * the boolean is converted to a byte value, 1 for true, 0 for false. * (This treatment follows the usage of the bytecode verifier.) * <li>If <em>T1</em> is boolean and <em>T0</em> is another primitive, * <em>T0</em> is converted to byte via Java casting conversion (JLS 5.5), * and the low order bit of the result is tested, as if by {@code (x & 1) != 0}. * <li>If <em>T0</em> and <em>T1</em> are primitives other than boolean, * then a Java casting conversion (JLS 5.5) is applied. * (Specifically, <em>T0</em> will convert to <em>T1</em> by * widening and/or narrowing.) * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing * conversion will be applied at runtime, possibly followed * by a Java casting conversion (JLS 5.5) on the primitive value, * possibly followed by a conversion from byte to boolean by testing * the low-order bit. * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, * and if the reference is null at runtime, a zero value is introduced. * </ul> * @param target the method handle to invoke after arguments are retyped * @param newType the expected type of the new method handle * @return a method handle which delegates to the target after performing * any necessary argument conversions, and arranges for any * necessary return value conversions * @throws NullPointerException if either argument is null * @throws WrongMethodTypeException if the conversion cannot be made * @see MethodHandle#asType */ public static MethodHandle explicitCastArguments(MethodHandle target, MethodType newType) { explicitCastArgumentsChecks(target, newType); // use the asTypeCache when possible: MethodType oldType = target.type(); if (oldType == newType) return target; if (oldType.explicitCastEquivalentToAsType(newType)) { return target.asFixedArity().asType(newType); } return MethodHandleImpl.makePairwiseConvert(target, newType, false); } private static void explicitCastArgumentsChecks(MethodHandle target, MethodType newType) { if (target.type().parameterCount() != newType.parameterCount()) { throw new WrongMethodTypeException("cannot explicitly cast " + target + " to " + newType); } } /** * Produces a method handle which adapts the calling sequence of the * given method handle to a new type, by reordering the arguments. * The resulting method handle is guaranteed to report a type * which is equal to the desired new type. * <p> * The given array controls the reordering. * Call {@code #I} the number of incoming parameters (the value * {@code newType.parameterCount()}, and call {@code #O} the number * of outgoing parameters (the value {@code target.type().parameterCount()}). * Then the length of the reordering array must be {@code #O}, * and each element must be a non-negative number less than {@code #I}. * For every {@code N} less than {@code #O}, the {@code N}-th * outgoing argument will be taken from the {@code I}-th incoming * argument, where {@code I} is {@code reorder[N]}. * <p> * No argument or return value conversions are applied. * The type of each incoming argument, as determined by {@code newType}, * must be identical to the type of the corresponding outgoing parameter * or parameters in the target method handle. * The return type of {@code newType} must be identical to the return * type of the original target. * <p> * The reordering array need not specify an actual permutation. * An incoming argument will be duplicated if its index appears * more than once in the array, and an incoming argument will be dropped * if its index does not appear in the array. * As in the case of {@link #dropArguments(MethodHandle,int,List) dropArguments}, * incoming arguments which are not mentioned in the reordering array * may be of any type, as determined only by {@code newType}. * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodType intfn1 = methodType(int.class, int.class); MethodType intfn2 = methodType(int.class, int.class, int.class); MethodHandle sub = ... (int x, int y) -> (x-y) ...; assert(sub.type().equals(intfn2)); MethodHandle sub1 = permuteArguments(sub, intfn2, 0, 1); MethodHandle rsub = permuteArguments(sub, intfn2, 1, 0); assert((int)rsub.invokeExact(1, 100) == 99); MethodHandle add = ... (int x, int y) -> (x+y) ...; assert(add.type().equals(intfn2)); MethodHandle twice = permuteArguments(add, intfn1, 0, 0); assert(twice.type().equals(intfn1)); assert((int)twice.invokeExact(21) == 42); * }</pre></blockquote> * <p> * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector * variable-arity method handle}, even if the original target method handle was. * @param target the method handle to invoke after arguments are reordered * @param newType the expected type of the new method handle * @param reorder an index array which controls the reordering * @return a method handle which delegates to the target after it * drops unused arguments and moves and/or duplicates the other arguments * @throws NullPointerException if any argument is null * @throws IllegalArgumentException if the index array length is not equal to * the arity of the target, or if any index array element * not a valid index for a parameter of {@code newType}, * or if two corresponding parameter types in * {@code target.type()} and {@code newType} are not identical, */ public static MethodHandle permuteArguments(MethodHandle target, MethodType newType, int... reorder) { reorder = reorder.clone(); // get a private copy MethodType oldType = target.type(); permuteArgumentChecks(reorder, newType, oldType); // first detect dropped arguments and handle them separately int[] originalReorder = reorder; BoundMethodHandle result = target.rebind(); LambdaForm form = result.form; int newArity = newType.parameterCount(); // Normalize the reordering into a real permutation, // by removing duplicates and adding dropped elements. // This somewhat improves lambda form caching, as well // as simplifying the transform by breaking it up into steps. for (int ddIdx; (ddIdx = findFirstDupOrDrop(reorder, newArity)) != 0; ) { if (ddIdx > 0) { // We found a duplicated entry at reorder[ddIdx]. // Example: (x,y,z)->asList(x,y,z) // permuted by [1*,0,1] => (a0,a1)=>asList(a1,a0,a1) // permuted by [0,1,0*] => (a0,a1)=>asList(a0,a1,a0) // The starred element corresponds to the argument // deleted by the dupArgumentForm transform. int srcPos = ddIdx, dstPos = srcPos, dupVal = reorder[srcPos]; boolean killFirst = false; for (int val; (val = reorder[--dstPos]) != dupVal; ) { // Set killFirst if the dup is larger than an intervening position. // This will remove at least one inversion from the permutation. if (dupVal > val) killFirst = true; } if (!killFirst) { srcPos = dstPos; dstPos = ddIdx; } form = form.editor().dupArgumentForm(1 + srcPos, 1 + dstPos); assert (reorder[srcPos] == reorder[dstPos]); oldType = oldType.dropParameterTypes(dstPos, dstPos + 1); // contract the reordering by removing the element at dstPos int tailPos = dstPos + 1; System.arraycopy(reorder, tailPos, reorder, dstPos, reorder.length - tailPos); reorder = Arrays.copyOf(reorder, reorder.length - 1); } else { int dropVal = ~ddIdx, insPos = 0; while (insPos < reorder.length && reorder[insPos] < dropVal) { // Find first element of reorder larger than dropVal. // This is where we will insert the dropVal. insPos += 1; } Class<?> ptype = newType.parameterType(dropVal); form = form.editor().addArgumentForm(1 + insPos, BasicType.basicType(ptype)); oldType = oldType.insertParameterTypes(insPos, ptype); // expand the reordering by inserting an element at insPos int tailPos = insPos + 1; reorder = Arrays.copyOf(reorder, reorder.length + 1); System.arraycopy(reorder, insPos, reorder, tailPos, reorder.length - tailPos); reorder[insPos] = dropVal; } assert (permuteArgumentChecks(reorder, newType, oldType)); } assert (reorder.length == newArity); // a perfect permutation // Note: This may cache too many distinct LFs. Consider backing off to varargs code. form = form.editor().permuteArgumentsForm(1, reorder); if (newType == result.type() && form == result.internalForm()) return result; return result.copyWith(newType, form); } /** * Return an indication of any duplicate or omission in reorder. * If the reorder contains a duplicate entry, return the index of the second occurrence. * Otherwise, return ~(n), for the first n in [0..newArity-1] that is not present in reorder. * Otherwise, return zero. * If an element not in [0..newArity-1] is encountered, return reorder.length. */ private static int findFirstDupOrDrop(int[] reorder, int newArity) { final int BIT_LIMIT = 63; // max number of bits in bit mask if (newArity < BIT_LIMIT) { long mask = 0; for (int i = 0; i < reorder.length; i++) { int arg = reorder[i]; if (arg >= newArity) { return reorder.length; } long bit = 1L << arg; if ((mask & bit) != 0) { return i; // >0 indicates a dup } mask |= bit; } if (mask == (1L << newArity) - 1) { assert(Long.numberOfTrailingZeros(Long.lowestOneBit(~mask)) == newArity); return 0; } // find first zero long zeroBit = Long.lowestOneBit(~mask); int zeroPos = Long.numberOfTrailingZeros(zeroBit); assert(zeroPos <= newArity); if (zeroPos == newArity) { return 0; } return ~zeroPos; } else { // same algorithm, different bit set BitSet mask = new BitSet(newArity); for (int i = 0; i < reorder.length; i++) { int arg = reorder[i]; if (arg >= newArity) { return reorder.length; } if (mask.get(arg)) { return i; // >0 indicates a dup } mask.set(arg); } int zeroPos = mask.nextClearBit(0); assert(zeroPos <= newArity); if (zeroPos == newArity) { return 0; } return ~zeroPos; } } private static boolean permuteArgumentChecks(int[] reorder, MethodType newType, MethodType oldType) { if (newType.returnType() != oldType.returnType()) throw newIllegalArgumentException("return types do not match", oldType, newType); if (reorder.length == oldType.parameterCount()) { int limit = newType.parameterCount(); boolean bad = false; for (int j = 0; j < reorder.length; j++) { int i = reorder[j]; if (i < 0 || i >= limit) { bad = true; break; } Class<?> src = newType.parameterType(i); Class<?> dst = oldType.parameterType(j); if (src != dst) throw newIllegalArgumentException("parameter types do not match after reorder", oldType, newType); } if (!bad) return true; } throw newIllegalArgumentException("bad reorder array: "+Arrays.toString(reorder)); } /** * Produces a method handle of the requested return type which returns the given * constant value every time it is invoked. * <p> * Before the method handle is returned, the passed-in value is converted to the requested type. * If the requested type is primitive, widening primitive conversions are attempted, * else reference conversions are attempted. * <p>The returned method handle is equivalent to {@code identity(type).bindTo(value)}. * @param type the return type of the desired method handle * @param value the value to return * @return a method handle of the given return type and no arguments, which always returns the given value * @throws NullPointerException if the {@code type} argument is null * @throws ClassCastException if the value cannot be converted to the required return type * @throws IllegalArgumentException if the given type is {@code void.class} */ public static MethodHandle constant(Class<?> type, Object value) { if (type.isPrimitive()) { if (type == void.class) throw newIllegalArgumentException("void type"); Wrapper w = Wrapper.forPrimitiveType(type); value = w.convert(value, type); if (w.zero().equals(value)) return zero(w, type); return insertArguments(identity(type), 0, value); } else { if (value == null) return zero(Wrapper.OBJECT, type); return identity(type).bindTo(value); } } /** * Produces a method handle which returns its sole argument when invoked. * @param type the type of the sole parameter and return value of the desired method handle * @return a unary method handle which accepts and returns the given type * @throws NullPointerException if the argument is null * @throws IllegalArgumentException if the given type is {@code void.class} */ public static MethodHandle identity(Class<?> type) { Wrapper btw = (type.isPrimitive() ? Wrapper.forPrimitiveType(type) : Wrapper.OBJECT); int pos = btw.ordinal(); MethodHandle ident = IDENTITY_MHS[pos]; if (ident == null) { ident = setCachedMethodHandle(IDENTITY_MHS, pos, makeIdentity(btw.primitiveType())); } if (ident.type().returnType() == type) return ident; // something like identity(Foo.class); do not bother to intern these assert (btw == Wrapper.OBJECT); return makeIdentity(type); } /** * Produces a constant method handle of the requested return type which * returns the default value for that type every time it is invoked. * The resulting constant method handle will have no side effects. * <p>The returned method handle is equivalent to {@code empty(methodType(type))}. * It is also equivalent to {@code explicitCastArguments(constant(Object.class, null), methodType(type))}, * since {@code explicitCastArguments} converts {@code null} to default values. * @param type the expected return type of the desired method handle * @return a constant method handle that takes no arguments * and returns the default value of the given type (or void, if the type is void) * @throws NullPointerException if the argument is null * @see MethodHandles#constant * @see MethodHandles#empty * @see MethodHandles#explicitCastArguments * @since 9 */ public static MethodHandle zero(Class<?> type) { Objects.requireNonNull(type); return type.isPrimitive() ? zero(Wrapper.forPrimitiveType(type), type) : zero(Wrapper.OBJECT, type); } private static MethodHandle identityOrVoid(Class<?> type) { return type == void.class ? zero(type) : identity(type); } /** * Produces a method handle of the requested type which ignores any arguments, does nothing, * and returns a suitable default depending on the return type. * That is, it returns a zero primitive value, a {@code null}, or {@code void}. * <p>The returned method handle is equivalent to * {@code dropArguments(zero(type.returnType()), 0, type.parameterList())}. * <p> * @apiNote Given a predicate and target, a useful "if-then" construct can be produced as * {@code guardWithTest(pred, target, empty(target.type())}. * @param type the type of the desired method handle * @return a constant method handle of the given type, which returns a default value of the given return type * @throws NullPointerException if the argument is null * @see MethodHandles#zero * @see MethodHandles#constant * @since 9 */ public static MethodHandle empty(MethodType type) { Objects.requireNonNull(type); return dropArguments(zero(type.returnType()), 0, type.parameterList()); } private static final MethodHandle[] IDENTITY_MHS = new MethodHandle[Wrapper.COUNT]; private static MethodHandle makeIdentity(Class<?> ptype) { MethodType mtype = methodType(ptype, ptype); LambdaForm lform = LambdaForm.identityForm(BasicType.basicType(ptype)); return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.IDENTITY); } private static MethodHandle zero(Wrapper btw, Class<?> rtype) { int pos = btw.ordinal(); MethodHandle zero = ZERO_MHS[pos]; if (zero == null) { zero = setCachedMethodHandle(ZERO_MHS, pos, makeZero(btw.primitiveType())); } if (zero.type().returnType() == rtype) return zero; assert(btw == Wrapper.OBJECT); return makeZero(rtype); } private static final MethodHandle[] ZERO_MHS = new MethodHandle[Wrapper.COUNT]; private static MethodHandle makeZero(Class<?> rtype) { MethodType mtype = methodType(rtype); LambdaForm lform = LambdaForm.zeroForm(BasicType.basicType(rtype)); return MethodHandleImpl.makeIntrinsic(mtype, lform, Intrinsic.ZERO); } private static synchronized MethodHandle setCachedMethodHandle(MethodHandle[] cache, int pos, MethodHandle value) { // Simulate a CAS, to avoid racy duplication of results. MethodHandle prev = cache[pos]; if (prev != null) return prev; return cache[pos] = value; } /** * Provides a target method handle with one or more <em>bound arguments</em> * in advance of the method handle's invocation. * The formal parameters to the target corresponding to the bound * arguments are called <em>bound parameters</em>. * Returns a new method handle which saves away the bound arguments. * When it is invoked, it receives arguments for any non-bound parameters, * binds the saved arguments to their corresponding parameters, * and calls the original target. * <p> * The type of the new method handle will drop the types for the bound * parameters from the original target type, since the new method handle * will no longer require those arguments to be supplied by its callers. * <p> * Each given argument object must match the corresponding bound parameter type. * If a bound parameter type is a primitive, the argument object * must be a wrapper, and will be unboxed to produce the primitive value. * <p> * The {@code pos} argument selects which parameters are to be bound. * It may range between zero and <i>N-L</i> (inclusively), * where <i>N</i> is the arity of the target method handle * and <i>L</i> is the length of the values array. * <p> * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector * variable-arity method handle}, even if the original target method handle was. * @param target the method handle to invoke after the argument is inserted * @param pos where to insert the argument (zero for the first) * @param values the series of arguments to insert * @return a method handle which inserts an additional argument, * before calling the original method handle * @throws NullPointerException if the target or the {@code values} array is null * @see MethodHandle#bindTo */ public static MethodHandle insertArguments(MethodHandle target, int pos, Object... values) { int insCount = values.length; Class<?>[] ptypes = insertArgumentsChecks(target, insCount, pos); if (insCount == 0) return target; BoundMethodHandle result = target.rebind(); for (int i = 0; i < insCount; i++) { Object value = values[i]; Class<?> ptype = ptypes[pos+i]; if (ptype.isPrimitive()) { result = insertArgumentPrimitive(result, pos, ptype, value); } else { value = ptype.cast(value); // throw CCE if needed result = result.bindArgumentL(pos, value); } } return result; } private static BoundMethodHandle insertArgumentPrimitive(BoundMethodHandle result, int pos, Class<?> ptype, Object value) { Wrapper w = Wrapper.forPrimitiveType(ptype); // perform unboxing and/or primitive conversion value = w.convert(value, ptype); switch (w) { case INT: return result.bindArgumentI(pos, (int)value); case LONG: return result.bindArgumentJ(pos, (long)value); case FLOAT: return result.bindArgumentF(pos, (float)value); case DOUBLE: return result.bindArgumentD(pos, (double)value); default: return result.bindArgumentI(pos, ValueConversions.widenSubword(value)); } } private static Class<?>[] insertArgumentsChecks(MethodHandle target, int insCount, int pos) throws RuntimeException { MethodType oldType = target.type(); int outargs = oldType.parameterCount(); int inargs = outargs - insCount; if (inargs < 0) throw newIllegalArgumentException("too many values to insert"); if (pos < 0 || pos > inargs) throw newIllegalArgumentException("no argument type to append"); return oldType.ptypes(); } /** * Produces a method handle which will discard some dummy arguments * before calling some other specified <i>target</i> method handle. * The type of the new method handle will be the same as the target's type, * except it will also include the dummy argument types, * at some given position. * <p> * The {@code pos} argument may range between zero and <i>N</i>, * where <i>N</i> is the arity of the target. * If {@code pos} is zero, the dummy arguments will precede * the target's real arguments; if {@code pos} is <i>N</i> * they will come after. * <p> * <b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle cat = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); assertEquals("xy", (String) cat.invokeExact("x", "y")); MethodType bigType = cat.type().insertParameterTypes(0, int.class, String.class); MethodHandle d0 = dropArguments(cat, 0, bigType.parameterList().subList(0,2)); assertEquals(bigType, d0.type()); assertEquals("yz", (String) d0.invokeExact(123, "x", "y", "z")); * }</pre></blockquote> * <p> * This method is also equivalent to the following code: * <blockquote><pre> * {@link #dropArguments(MethodHandle,int,Class...) dropArguments}{@code (target, pos, valueTypes.toArray(new Class[0]))} * </pre></blockquote> * @param target the method handle to invoke after the arguments are dropped * @param valueTypes the type(s) of the argument(s) to drop * @param pos position of first argument to drop (zero for the leftmost) * @return a method handle which drops arguments of the given types, * before calling the original method handle * @throws NullPointerException if the target is null, * or if the {@code valueTypes} list or any of its elements is null * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, * or if {@code pos} is negative or greater than the arity of the target, * or if the new method handle's type would have too many parameters */ public static MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) { return dropArguments0(target, pos, copyTypes(valueTypes.toArray())); } private static List<Class<?>> copyTypes(Object[] array) { return Arrays.asList(Arrays.copyOf(array, array.length, Class[].class)); } private static MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) { MethodType oldType = target.type(); // get NPE int dropped = dropArgumentChecks(oldType, pos, valueTypes); MethodType newType = oldType.insertParameterTypes(pos, valueTypes); if (dropped == 0) return target; BoundMethodHandle result = target.rebind(); LambdaForm lform = result.form; int insertFormArg = 1 + pos; for (Class<?> ptype : valueTypes) { lform = lform.editor().addArgumentForm(insertFormArg++, BasicType.basicType(ptype)); } result = result.copyWith(newType, lform); return result; } private static int dropArgumentChecks(MethodType oldType, int pos, List<Class<?>> valueTypes) { int dropped = valueTypes.size(); MethodType.checkSlotCount(dropped); int outargs = oldType.parameterCount(); int inargs = outargs + dropped; if (pos < 0 || pos > outargs) throw newIllegalArgumentException("no argument type to remove" + Arrays.asList(oldType, pos, valueTypes, inargs, outargs) ); return dropped; } /** * Produces a method handle which will discard some dummy arguments * before calling some other specified <i>target</i> method handle. * The type of the new method handle will be the same as the target's type, * except it will also include the dummy argument types, * at some given position. * <p> * The {@code pos} argument may range between zero and <i>N</i>, * where <i>N</i> is the arity of the target. * If {@code pos} is zero, the dummy arguments will precede * the target's real arguments; if {@code pos} is <i>N</i> * they will come after. * @apiNote * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle cat = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); assertEquals("xy", (String) cat.invokeExact("x", "y")); MethodHandle d0 = dropArguments(cat, 0, String.class); assertEquals("yz", (String) d0.invokeExact("x", "y", "z")); MethodHandle d1 = dropArguments(cat, 1, String.class); assertEquals("xz", (String) d1.invokeExact("x", "y", "z")); MethodHandle d2 = dropArguments(cat, 2, String.class); assertEquals("xy", (String) d2.invokeExact("x", "y", "z")); MethodHandle d12 = dropArguments(cat, 1, int.class, boolean.class); assertEquals("xz", (String) d12.invokeExact("x", 12, true, "z")); * }</pre></blockquote> * <p> * This method is also equivalent to the following code: * <blockquote><pre> * {@link #dropArguments(MethodHandle,int,List) dropArguments}{@code (target, pos, Arrays.asList(valueTypes))} * </pre></blockquote> * @param target the method handle to invoke after the arguments are dropped * @param valueTypes the type(s) of the argument(s) to drop * @param pos position of first argument to drop (zero for the leftmost) * @return a method handle which drops arguments of the given types, * before calling the original method handle * @throws NullPointerException if the target is null, * or if the {@code valueTypes} array or any of its elements is null * @throws IllegalArgumentException if any element of {@code valueTypes} is {@code void.class}, * or if {@code pos} is negative or greater than the arity of the target, * or if the new method handle's type would have * <a href="MethodHandle.html#maxarity">too many parameters</a> */ public static MethodHandle dropArguments(MethodHandle target, int pos, Class<?>... valueTypes) { return dropArguments0(target, pos, copyTypes(valueTypes)); } // private version which allows caller some freedom with error handling private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos, boolean nullOnFailure) { newTypes = copyTypes(newTypes.toArray()); List<Class<?>> oldTypes = target.type().parameterList(); int match = oldTypes.size(); if (skip != 0) { if (skip < 0 || skip > match) { throw newIllegalArgumentException("illegal skip", skip, target); } oldTypes = oldTypes.subList(skip, match); match -= skip; } List<Class<?>> addTypes = newTypes; int add = addTypes.size(); if (pos != 0) { if (pos < 0 || pos > add) { throw newIllegalArgumentException("illegal pos", pos, newTypes); } addTypes = addTypes.subList(pos, add); add -= pos; assert(addTypes.size() == add); } // Do not add types which already match the existing arguments. if (match > add || !oldTypes.equals(addTypes.subList(0, match))) { if (nullOnFailure) { return null; } throw newIllegalArgumentException("argument lists do not match", oldTypes, newTypes); } addTypes = addTypes.subList(match, add); add -= match; assert(addTypes.size() == add); // newTypes: ( P*[pos], M*[match], A*[add] ) // target: ( S*[skip], M*[match] ) MethodHandle adapter = target; if (add > 0) { adapter = dropArguments0(adapter, skip+ match, addTypes); } // adapter: (S*[skip], M*[match], A*[add] ) if (pos > 0) { adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos)); } // adapter: (S*[skip], P*[pos], M*[match], A*[add] ) return adapter; } /** * Adapts a target method handle to match the given parameter type list, if necessary, by adding dummy arguments. * Some leading parameters are first skipped; they will be left unchanged and are otherwise ignored. * The remaining types in the target's parameter type list must be contained as a sub-list of the given type list, * at the given position. * Any non-matching parameter types (before or after the matching sub-list) are inserted in corresponding * positions of the target method handle's parameters, as if by {@link #dropArguments}. * (More precisely, elements in the new list before {@code pos} are inserted into the target list at {@code skip}, * while elements in the new list after the match beginning at {@code pos} are inserted at the end of the * target list.) * The target's return type will be unchanged. * @apiNote * Two method handles whose argument lists are "effectively identical" (i.e., identical * in a common prefix) may be mutually converted to a common type * by two calls to {@code dropArgumentsToMatch}, as follows: * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... ... MethodHandle h0 = constant(boolean.class, true); MethodHandle h1 = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); MethodType bigType = h1.type().insertParameterTypes(1, String.class, int.class); MethodHandle h2 = dropArguments(h1, 0, bigType.parameterList()); if (h1.type().parameterCount() < h2.type().parameterCount()) h1 = dropArgumentsToMatch(h1, 0, h2.type().parameterList(), 0); // lengthen h1 else h2 = dropArgumentsToMatch(h2, 0, h1.type().parameterList(), 0); // lengthen h2 MethodHandle h3 = guardWithTest(h0, h1, h2); assertEquals("xy", h3.invoke("x", "y", 1, "a", "b", "c")); * }</pre></blockquote> * @param target the method handle to adapt * @param skip number of targets parameters to disregard (they will be unchanged) * @param newTypes the desired argument list of the method handle * @param pos place in {@code newTypes} where the non-skipped target parameters must occur * @return a possibly adapted method handle * @throws NullPointerException if either argument is null * @throws IllegalArgumentException if any element of {@code newTypes} is {@code void.class}, * or if {@code skip} is negative or greater than the arity of the target, * or if {@code pos} is negative or greater than the newTypes list size, * or if the non-skipped target parameter types match the new types at {@code pos} * @since 9 */ public static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos) { Objects.requireNonNull(target); Objects.requireNonNull(newTypes); return dropArgumentsToMatch(target, skip, newTypes, pos, false); } /** * Adapts a target method handle by pre-processing * one or more of its arguments, each with its own unary filter function, * and then calling the target with each pre-processed argument * replaced by the result of its corresponding filter function. * <p> * The pre-processing is performed by one or more method handles, * specified in the elements of the {@code filters} array. * The first element of the filter array corresponds to the {@code pos} * argument of the target, and so on in sequence. * <p> * Null arguments in the array are treated as identity functions, * and the corresponding arguments left unchanged. * (If there are no non-null elements in the array, the original target is returned.) * Each filter is applied to the corresponding argument of the adapter. * <p> * If a filter {@code F} applies to the {@code N}th argument of * the target, then {@code F} must be a method handle which * takes exactly one argument. The type of {@code F}'s sole argument * replaces the corresponding argument type of the target * in the resulting adapted method handle. * The return type of {@code F} must be identical to the corresponding * parameter type of the target. * <p> * It is an error if there are elements of {@code filters} * (null or not) * which do not correspond to argument positions in the target. * <p><b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle cat = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); MethodHandle upcase = lookup().findVirtual(String.class, "toUpperCase", methodType(String.class)); assertEquals("xy", (String) cat.invokeExact("x", "y")); MethodHandle f0 = filterArguments(cat, 0, upcase); assertEquals("Xy", (String) f0.invokeExact("x", "y")); // Xy MethodHandle f1 = filterArguments(cat, 1, upcase); assertEquals("xY", (String) f1.invokeExact("x", "y")); // xY MethodHandle f2 = filterArguments(cat, 0, upcase, upcase); assertEquals("XY", (String) f2.invokeExact("x", "y")); // XY * }</pre></blockquote> * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} * denotes the return type of both the {@code target} and resulting adapter. * {@code P}/{@code p} and {@code B}/{@code b} represent the types and values * of the parameters and arguments that precede and follow the filter position * {@code pos}, respectively. {@code A[i]}/{@code a[i]} stand for the types and * values of the filtered parameters and arguments; they also represent the * return types of the {@code filter[i]} handles. The latter accept arguments * {@code v[i]} of type {@code V[i]}, which also appear in the signature of * the resulting adapter. * <blockquote><pre>{@code * T target(P... p, A[i]... a[i], B... b); * A[i] filter[i](V[i]); * T adapter(P... p, V[i]... v[i], B... b) { * return target(p..., filter[i](v[i])..., b...); * } * }</pre></blockquote> * <p> * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector * variable-arity method handle}, even if the original target method handle was. * * @param target the method handle to invoke after arguments are filtered * @param pos the position of the first argument to filter * @param filters method handles to call initially on filtered arguments * @return method handle which incorporates the specified argument filtering logic * @throws NullPointerException if the target is null * or if the {@code filters} array is null * @throws IllegalArgumentException if a non-null element of {@code filters} * does not match a corresponding argument type of target as described above, * or if the {@code pos+filters.length} is greater than {@code target.type().parameterCount()}, * or if the resulting method handle's type would have * <a href="MethodHandle.html#maxarity">too many parameters</a> */ public static MethodHandle filterArguments(MethodHandle target, int pos, MethodHandle... filters) { filterArgumentsCheckArity(target, pos, filters); MethodHandle adapter = target; int curPos = pos-1; // pre-incremented for (MethodHandle filter : filters) { curPos += 1; if (filter == null) continue; // ignore null elements of filters adapter = filterArgument(adapter, curPos, filter); } return adapter; } /*non-public*/ static MethodHandle filterArgument(MethodHandle target, int pos, MethodHandle filter) { filterArgumentChecks(target, pos, filter); MethodType targetType = target.type(); MethodType filterType = filter.type(); BoundMethodHandle result = target.rebind(); Class<?> newParamType = filterType.parameterType(0); LambdaForm lform = result.editor().filterArgumentForm(1 + pos, BasicType.basicType(newParamType)); MethodType newType = targetType.changeParameterType(pos, newParamType); result = result.copyWithExtendL(newType, lform, filter); return result; } private static void filterArgumentsCheckArity(MethodHandle target, int pos, MethodHandle[] filters) { MethodType targetType = target.type(); int maxPos = targetType.parameterCount(); if (pos + filters.length > maxPos) throw newIllegalArgumentException("too many filters"); } private static void filterArgumentChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { MethodType targetType = target.type(); MethodType filterType = filter.type(); if (filterType.parameterCount() != 1 || filterType.returnType() != targetType.parameterType(pos)) throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); } /** * Adapts a target method handle by pre-processing * a sub-sequence of its arguments with a filter (another method handle). * The pre-processed arguments are replaced by the result (if any) of the * filter function. * The target is then called on the modified (usually shortened) argument list. * <p> * If the filter returns a value, the target must accept that value as * its argument in position {@code pos}, preceded and/or followed by * any arguments not passed to the filter. * If the filter returns void, the target must accept all arguments * not passed to the filter. * No arguments are reordered, and a result returned from the filter * replaces (in order) the whole subsequence of arguments originally * passed to the adapter. * <p> * The argument types (if any) of the filter * replace zero or one argument types of the target, at position {@code pos}, * in the resulting adapted method handle. * The return type of the filter (if any) must be identical to the * argument type of the target at position {@code pos}, and that target argument * is supplied by the return value of the filter. * <p> * In all cases, {@code pos} must be greater than or equal to zero, and * {@code pos} must also be less than or equal to the target's arity. * <p><b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle deepToString = publicLookup() .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class)); MethodHandle ts1 = deepToString.asCollector(String[].class, 1); assertEquals("[strange]", (String) ts1.invokeExact("strange")); MethodHandle ts2 = deepToString.asCollector(String[].class, 2); assertEquals("[up, down]", (String) ts2.invokeExact("up", "down")); MethodHandle ts3 = deepToString.asCollector(String[].class, 3); MethodHandle ts3_ts2 = collectArguments(ts3, 1, ts2); assertEquals("[top, [up, down], strange]", (String) ts3_ts2.invokeExact("top", "up", "down", "strange")); MethodHandle ts3_ts2_ts1 = collectArguments(ts3_ts2, 3, ts1); assertEquals("[top, [up, down], [strange]]", (String) ts3_ts2_ts1.invokeExact("top", "up", "down", "strange")); MethodHandle ts3_ts2_ts3 = collectArguments(ts3_ts2, 1, ts3); assertEquals("[top, [[up, down, strange], charm], bottom]", (String) ts3_ts2_ts3.invokeExact("top", "up", "down", "strange", "charm", "bottom")); * }</pre></blockquote> * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} * represents the return type of the {@code target} and resulting adapter. * {@code V}/{@code v} stand for the return type and value of the * {@code filter}, which are also found in the signature and arguments of * the {@code target}, respectively, unless {@code V} is {@code void}. * {@code A}/{@code a} and {@code C}/{@code c} represent the parameter types * and values preceding and following the collection position, {@code pos}, * in the {@code target}'s signature. They also turn up in the resulting * adapter's signature and arguments, where they surround * {@code B}/{@code b}, which represent the parameter types and arguments * to the {@code filter} (if any). * <blockquote><pre>{@code * T target(A...,V,C...); * V filter(B...); * T adapter(A... a,B... b,C... c) { * V v = filter(b...); * return target(a...,v,c...); * } * // and if the filter has no arguments: * T target2(A...,V,C...); * V filter2(); * T adapter2(A... a,C... c) { * V v = filter2(); * return target2(a...,v,c...); * } * // and if the filter has a void return: * T target3(A...,C...); * void filter3(B...); * T adapter3(A... a,B... b,C... c) { * filter3(b...); * return target3(a...,c...); * } * }</pre></blockquote> * <p> * A collection adapter {@code collectArguments(mh, 0, coll)} is equivalent to * one which first "folds" the affected arguments, and then drops them, in separate * steps as follows: * <blockquote><pre>{@code * mh = MethodHandles.dropArguments(mh, 1, coll.type().parameterList()); //step 2 * mh = MethodHandles.foldArguments(mh, coll); //step 1 * }</pre></blockquote> * If the target method handle consumes no arguments besides than the result * (if any) of the filter {@code coll}, then {@code collectArguments(mh, 0, coll)} * is equivalent to {@code filterReturnValue(coll, mh)}. * If the filter method handle {@code coll} consumes one argument and produces * a non-void result, then {@code collectArguments(mh, N, coll)} * is equivalent to {@code filterArguments(mh, N, coll)}. * Other equivalences are possible but would require argument permutation. * <p> * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector * variable-arity method handle}, even if the original target method handle was. * * @param target the method handle to invoke after filtering the subsequence of arguments * @param pos the position of the first adapter argument to pass to the filter, * and/or the target argument which receives the result of the filter * @param filter method handle to call on the subsequence of arguments * @return method handle which incorporates the specified argument subsequence filtering logic * @throws NullPointerException if either argument is null * @throws IllegalArgumentException if the return type of {@code filter} * is non-void and is not the same as the {@code pos} argument of the target, * or if {@code pos} is not between 0 and the target's arity, inclusive, * or if the resulting method handle's type would have * <a href="MethodHandle.html#maxarity">too many parameters</a> * @see MethodHandles#foldArguments * @see MethodHandles#filterArguments * @see MethodHandles#filterReturnValue */ public static MethodHandle collectArguments(MethodHandle target, int pos, MethodHandle filter) { MethodType newType = collectArgumentsChecks(target, pos, filter); MethodType collectorType = filter.type(); BoundMethodHandle result = target.rebind(); LambdaForm lform; if (collectorType.returnType().isArray() && filter.intrinsicName() == Intrinsic.NEW_ARRAY) { lform = result.editor().collectArgumentArrayForm(1 + pos, filter); if (lform != null) { return result.copyWith(newType, lform); } } lform = result.editor().collectArgumentsForm(1 + pos, collectorType.basicType()); return result.copyWithExtendL(newType, lform, filter); } private static MethodType collectArgumentsChecks(MethodHandle target, int pos, MethodHandle filter) throws RuntimeException { MethodType targetType = target.type(); MethodType filterType = filter.type(); Class<?> rtype = filterType.returnType(); List<Class<?>> filterArgs = filterType.parameterList(); if (rtype == void.class) { return targetType.insertParameterTypes(pos, filterArgs); } if (rtype != targetType.parameterType(pos)) { throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); } return targetType.dropParameterTypes(pos, pos+1).insertParameterTypes(pos, filterArgs); } /** * Adapts a target method handle by post-processing * its return value (if any) with a filter (another method handle). * The result of the filter is returned from the adapter. * <p> * If the target returns a value, the filter must accept that value as * its only argument. * If the target returns void, the filter must accept no arguments. * <p> * The return type of the filter * replaces the return type of the target * in the resulting adapted method handle. * The argument type of the filter (if any) must be identical to the * return type of the target. * <p><b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle cat = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); MethodHandle length = lookup().findVirtual(String.class, "length", methodType(int.class)); System.out.println((String) cat.invokeExact("x", "y")); // xy MethodHandle f0 = filterReturnValue(cat, length); System.out.println((int) f0.invokeExact("x", "y")); // 2 * }</pre></blockquote> * <p>Here is pseudocode for the resulting adapter. In the code, * {@code T}/{@code t} represent the result type and value of the * {@code target}; {@code V}, the result type of the {@code filter}; and * {@code A}/{@code a}, the types and values of the parameters and arguments * of the {@code target} as well as the resulting adapter. * <blockquote><pre>{@code * T target(A...); * V filter(T); * V adapter(A... a) { * T t = target(a...); * return filter(t); * } * // and if the target has a void return: * void target2(A...); * V filter2(); * V adapter2(A... a) { * target2(a...); * return filter2(); * } * // and if the filter has a void return: * T target3(A...); * void filter3(V); * void adapter3(A... a) { * T t = target3(a...); * filter3(t); * } * }</pre></blockquote> * <p> * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector * variable-arity method handle}, even if the original target method handle was. * @param target the method handle to invoke before filtering the return value * @param filter method handle to call on the return value * @return method handle which incorporates the specified return value filtering logic * @throws NullPointerException if either argument is null * @throws IllegalArgumentException if the argument list of {@code filter} * does not match the return type of target as described above */ public static MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) { MethodType targetType = target.type(); MethodType filterType = filter.type(); filterReturnValueChecks(targetType, filterType); BoundMethodHandle result = target.rebind(); BasicType rtype = BasicType.basicType(filterType.returnType()); LambdaForm lform = result.editor().filterReturnForm(rtype, false); MethodType newType = targetType.changeReturnType(filterType.returnType()); result = result.copyWithExtendL(newType, lform, filter); return result; } private static void filterReturnValueChecks(MethodType targetType, MethodType filterType) throws RuntimeException { Class<?> rtype = targetType.returnType(); int filterValues = filterType.parameterCount(); if (filterValues == 0 ? (rtype != void.class) : (rtype != filterType.parameterType(0) || filterValues != 1)) throw newIllegalArgumentException("target and filter types do not match", targetType, filterType); } /** * Adapts a target method handle by pre-processing * some of its arguments, and then calling the target with * the result of the pre-processing, inserted into the original * sequence of arguments. * <p> * The pre-processing is performed by {@code combiner}, a second method handle. * Of the arguments passed to the adapter, the first {@code N} arguments * are copied to the combiner, which is then called. * (Here, {@code N} is defined as the parameter count of the combiner.) * After this, control passes to the target, with any result * from the combiner inserted before the original {@code N} incoming * arguments. * <p> * If the combiner returns a value, the first parameter type of the target * must be identical with the return type of the combiner, and the next * {@code N} parameter types of the target must exactly match the parameters * of the combiner. * <p> * If the combiner has a void return, no result will be inserted, * and the first {@code N} parameter types of the target * must exactly match the parameters of the combiner. * <p> * The resulting adapter is the same type as the target, except that the * first parameter type is dropped, * if it corresponds to the result of the combiner. * <p> * (Note that {@link #dropArguments(MethodHandle,int,List) dropArguments} can be used to remove any arguments * that either the combiner or the target does not wish to receive. * If some of the incoming arguments are destined only for the combiner, * consider using {@link MethodHandle#asCollector asCollector} instead, since those * arguments will not need to be live on the stack on entry to the * target.) * <p><b>Example:</b> * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, "println", methodType(void.class, String.class)) .bindTo(System.out); MethodHandle cat = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); MethodHandle catTrace = foldArguments(cat, trace); // also prints "boo": assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); * }</pre></blockquote> * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} * represents the result type of the {@code target} and resulting adapter. * {@code V}/{@code v} represent the type and value of the parameter and argument * of {@code target} that precedes the folding position; {@code V} also is * the result type of the {@code combiner}. {@code A}/{@code a} denote the * types and values of the {@code N} parameters and arguments at the folding * position. {@code B}/{@code b} represent the types and values of the * {@code target} parameters and arguments that follow the folded parameters * and arguments. * <blockquote><pre>{@code * // there are N arguments in A... * T target(V, A[N]..., B...); * V combiner(A...); * T adapter(A... a, B... b) { * V v = combiner(a...); * return target(v, a..., b...); * } * // and if the combiner has a void return: * T target2(A[N]..., B...); * void combiner2(A...); * T adapter2(A... a, B... b) { * combiner2(a...); * return target2(a..., b...); * } * }</pre></blockquote> * <p> * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector * variable-arity method handle}, even if the original target method handle was. * @param target the method handle to invoke after arguments are combined * @param combiner method handle to call initially on the incoming arguments * @return method handle which incorporates the specified argument folding logic * @throws NullPointerException if either argument is null * @throws IllegalArgumentException if {@code combiner}'s return type * is non-void and not the same as the first argument type of * the target, or if the initial {@code N} argument types * of the target * (skipping one matching the {@code combiner}'s return type) * are not identical with the argument types of {@code combiner} */ public static MethodHandle foldArguments(MethodHandle target, MethodHandle combiner) { return foldArguments(target, 0, combiner); } private static Class<?> foldArgumentChecks(int foldPos, MethodType targetType, MethodType combinerType) { int foldArgs = combinerType.parameterCount(); Class<?> rtype = combinerType.returnType(); int foldVals = rtype == void.class ? 0 : 1; int afterInsertPos = foldPos + foldVals; boolean ok = (targetType.parameterCount() >= afterInsertPos + foldArgs); if (ok) { for (int i = 0; i < foldArgs; i++) { if (combinerType.parameterType(i) != targetType.parameterType(i + afterInsertPos)) { ok = false; break; } } } if (ok && foldVals != 0 && combinerType.returnType() != targetType.parameterType(foldPos)) ok = false; if (!ok) throw misMatchedTypes("target and combiner types", targetType, combinerType); return rtype; } /** * Makes a method handle which adapts a target method handle, * by guarding it with a test, a boolean-valued method handle. * If the guard fails, a fallback handle is called instead. * All three method handles must have the same corresponding * argument and return types, except that the return type * of the test must be boolean, and the test is allowed * to have fewer arguments than the other two method handles. * <p> * Here is pseudocode for the resulting adapter. In the code, {@code T} * represents the uniform result type of the three involved handles; * {@code A}/{@code a}, the types and values of the {@code target} * parameters and arguments that are consumed by the {@code test}; and * {@code B}/{@code b}, those types and values of the {@code target} * parameters and arguments that are not consumed by the {@code test}. * <blockquote><pre>{@code * boolean test(A...); * T target(A...,B...); * T fallback(A...,B...); * T adapter(A... a,B... b) { * if (test(a...)) * return target(a..., b...); * else * return fallback(a..., b...); * } * }</pre></blockquote> * Note that the test arguments ({@code a...} in the pseudocode) cannot * be modified by execution of the test, and so are passed unchanged * from the caller to the target or fallback as appropriate. * @param test method handle used for test, must return boolean * @param target method handle to call if test passes * @param fallback method handle to call if test fails * @return method handle which incorporates the specified if/then/else logic * @throws NullPointerException if any argument is null * @throws IllegalArgumentException if {@code test} does not return boolean, * or if all three method types do not match (with the return * type of {@code test} changed to match that of the target). */ public static MethodHandle guardWithTest(MethodHandle test, MethodHandle target, MethodHandle fallback) { MethodType gtype = test.type(); MethodType ttype = target.type(); MethodType ftype = fallback.type(); if (!ttype.equals(ftype)) throw misMatchedTypes("target and fallback types", ttype, ftype); if (gtype.returnType() != boolean.class) throw newIllegalArgumentException("guard type is not a predicate "+gtype); List<Class<?>> targs = ttype.parameterList(); test = dropArgumentsToMatch(test, 0, targs, 0, true); if (test == null) { throw misMatchedTypes("target and test types", ttype, gtype); } return MethodHandleImpl.makeGuardWithTest(test, target, fallback); } static <T> RuntimeException misMatchedTypes(String what, T t1, T t2) { return newIllegalArgumentException(what + " must match: " + t1 + " != " + t2); } /** * Makes a method handle which adapts a target method handle, * by running it inside an exception handler. * If the target returns normally, the adapter returns that value. * If an exception matching the specified type is thrown, the fallback * handle is called instead on the exception, plus the original arguments. * <p> * The target and handler must have the same corresponding * argument and return types, except that handler may omit trailing arguments * (similarly to the predicate in {@link #guardWithTest guardWithTest}). * Also, the handler must have an extra leading parameter of {@code exType} or a supertype. * <p> * Here is pseudocode for the resulting adapter. In the code, {@code T} * represents the return type of the {@code target} and {@code handler}, * and correspondingly that of the resulting adapter; {@code A}/{@code a}, * the types and values of arguments to the resulting handle consumed by * {@code handler}; and {@code B}/{@code b}, those of arguments to the * resulting handle discarded by {@code handler}. * <blockquote><pre>{@code * T target(A..., B...); * T handler(ExType, A...); * T adapter(A... a, B... b) { * try { * return target(a..., b...); * } catch (ExType ex) { * return handler(ex, a...); * } * } * }</pre></blockquote> * Note that the saved arguments ({@code a...} in the pseudocode) cannot * be modified by execution of the target, and so are passed unchanged * from the caller to the handler, if the handler is invoked. * <p> * The target and handler must return the same type, even if the handler * always throws. (This might happen, for instance, because the handler * is simulating a {@code finally} clause). * To create such a throwing handler, compose the handler creation logic * with {@link #throwException throwException}, * in order to create a method handle of the correct return type. * @param target method handle to call * @param exType the type of exception which the handler will catch * @param handler method handle to call if a matching exception is thrown * @return method handle which incorporates the specified try/catch logic * @throws NullPointerException if any argument is null * @throws IllegalArgumentException if {@code handler} does not accept * the given exception type, or if the method handle types do * not match in their return types and their * corresponding parameters * @see MethodHandles#tryFinally(MethodHandle, MethodHandle) */ public static MethodHandle catchException(MethodHandle target, Class<? extends Throwable> exType, MethodHandle handler) { MethodType ttype = target.type(); MethodType htype = handler.type(); if (!Throwable.class.isAssignableFrom(exType)) throw new ClassCastException(exType.getName()); if (htype.parameterCount() < 1 || !htype.parameterType(0).isAssignableFrom(exType)) throw newIllegalArgumentException("handler does not accept exception type "+exType); if (htype.returnType() != ttype.returnType()) throw misMatchedTypes("target and handler return types", ttype, htype); handler = dropArgumentsToMatch(handler, 1, ttype.parameterList(), 0, true); if (handler == null) { throw misMatchedTypes("target and handler types", ttype, htype); } return MethodHandleImpl.makeGuardWithCatch(target, exType, handler); } /** * Produces a method handle which will throw exceptions of the given {@code exType}. * The method handle will accept a single argument of {@code exType}, * and immediately throw it as an exception. * The method type will nominally specify a return of {@code returnType}. * The return type may be anything convenient: It doesn't matter to the * method handle's behavior, since it will never return normally. * @param returnType the return type of the desired method handle * @param exType the parameter type of the desired method handle * @return method handle which can throw the given exceptions * @throws NullPointerException if either argument is null */ public static MethodHandle throwException(Class<?> returnType, Class<? extends Throwable> exType) { if (!Throwable.class.isAssignableFrom(exType)) throw new ClassCastException(exType.getName()); return MethodHandleImpl.throwException(methodType(returnType, exType)); } /** * Constructs a method handle representing a loop with several loop variables that are updated and checked upon each * iteration. Upon termination of the loop due to one of the predicates, a corresponding finalizer is run and * delivers the loop's result, which is the return value of the resulting handle. * <p> * Intuitively, every loop is formed by one or more "clauses", each specifying a local iteration value and/or a loop * exit. Each iteration of the loop executes each clause in order. A clause can optionally update its iteration * variable; it can also optionally perform a test and conditional loop exit. In order to express this logic in * terms of method handles, each clause will determine four actions:<ul> * <li>Before the loop executes, the initialization of an iteration variable or loop invariant local. * <li>When a clause executes, an update step for the iteration variable. * <li>When a clause executes, a predicate execution to test for loop exit. * <li>If a clause causes a loop exit, a finalizer execution to compute the loop's return value. * </ul> * <p> * Some of these clause parts may be omitted according to certain rules, and useful default behavior is provided in * this case. See below for a detailed description. * <p> * Each clause function, with the exception of clause initializers, is able to observe the entire loop state, * because it will be passed <em>all</em> current iteration variable values, as well as all incoming loop * parameters. Most clause functions will not need all of this information, but they will be formally connected as * if by {@link #dropArguments}. * <p> * Given a set of clauses, there is a number of checks and adjustments performed to connect all the parts of the * loop. They are spelled out in detail in the steps below. In these steps, every occurrence of the word "must" * corresponds to a place where {@link IllegalArgumentException} may be thrown if the required constraint is not met * by the inputs to the loop combinator. The term "effectively identical", applied to parameter type lists, means * that they must be identical, or else one list must be a proper prefix of the other. * <p> * <em>Step 0: Determine clause structure.</em><ol type="a"> * <li>The clause array (of type {@code MethodHandle[][]} must be non-{@code null} and contain at least one element. * <li>The clause array may not contain {@code null}s or sub-arrays longer than four elements. * <li>Clauses shorter than four elements are treated as if they were padded by {@code null} elements to length * four. Padding takes place by appending elements to the array. * <li>Clauses with all {@code null}s are disregarded. * <li>Each clause is treated as a four-tuple of functions, called "init", "step", "pred", and "fini". * </ol> * <p> * <em>Step 1A: Determine iteration variables.</em><ol type="a"> * <li>Examine init and step function return types, pairwise, to determine each clause's iteration variable type. * <li>If both functions are omitted, use {@code void}; else if one is omitted, use the other's return type; else * use the common return type (they must be identical). * <li>Form the list of return types (in clause order), omitting all occurrences of {@code void}. * <li>This list of types is called the "common prefix". * </ol> * <p> * <em>Step 1B: Determine loop parameters.</em><ul> * <li><b>If at least one init function is given,</b><ol type="a"> * <li>Examine init function parameter lists. * <li>Omitted init functions are deemed to have {@code null} parameter lists. * <li>All init function parameter lists must be effectively identical. * <li>The longest parameter list (which is necessarily unique) is called the "common suffix". * </ol> * <li><b>If no init function is given,</b><ol type="a"> * <li>Examine the suffixes of the step, pred, and fini parameter lists, after removing the "common prefix". * <li>The longest of these suffixes is taken as the "common suffix". * </ol></ul> * <p> * <em>Step 1C: Determine loop return type.</em><ol type="a"> * <li>Examine fini function return types, disregarding omitted fini functions. * <li>If there are no fini functions, use {@code void} as the loop return type. * <li>Otherwise, use the common return type of the fini functions; they must all be identical. * </ol> * <p> * <em>Step 1D: Check other types.</em><ol type="a"> * <li>There must be at least one non-omitted pred function. * <li>Every non-omitted pred function must have a {@code boolean} return type. * </ol> * <p> * <em>Step 2: Determine parameter lists.</em><ol type="a"> * <li>The parameter list for the resulting loop handle will be the "common suffix". * <li>The parameter list for init functions will be adjusted to the "common suffix". (Note that their parameter * lists are already effectively identical to the common suffix.) * <li>The parameter list for non-init (step, pred, and fini) functions will be adjusted to the common prefix * followed by the common suffix, called the "common parameter sequence". * <li>Every non-init, non-omitted function parameter list must be effectively identical to the common parameter * sequence. * </ol> * <p> * <em>Step 3: Fill in omitted functions.</em><ol type="a"> * <li>If an init function is omitted, use a {@linkplain #constant constant function} of the appropriate * {@code null}/zero/{@code false}/{@code void} type. (For this purpose, a constant {@code void} is simply a * function which does nothing and returns {@code void}; it can be obtained from another constant function by * {@linkplain MethodHandle#asType type conversion}.) * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void} * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.) * <li>If a pred function is omitted, the corresponding fini function must also be omitted. * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far * as this clause is concerned.) * <li>If a fini function is omitted, use a constant {@code null}/zero/{@code false}/{@code void} function of the * loop return type. * </ol> * <p> * <em>Step 4: Fill in missing parameter types.</em><ol type="a"> * <li>At this point, every init function parameter list is effectively identical to the common suffix, but some * lists may be shorter. For every init function with a short parameter list, pad out the end of the list by * {@linkplain #dropArguments dropping arguments}. * <li>At this point, every non-init function parameter list is effectively identical to the common parameter * sequence, but some lists may be shorter. For every non-init function with a short parameter list, pad out the end * of the list by {@linkplain #dropArguments dropping arguments}. * </ol> * <p> * <em>Final observations.</em><ol type="a"> * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments. * <li>All init functions have a common parameter type list, which the final loop handle will also have. * <li>All fini functions have a common return type, which the final loop handle will also have. * <li>All non-init functions have a common parameter type list, which is the common parameter sequence, of * (non-{@code void}) iteration variables followed by loop parameters. * <li>Each pair of init and step functions agrees in their return types. * <li>Each non-init function will be able to observe the current values of all iteration variables, by means of the * common prefix. * </ol> * <p> * <em>Loop execution.</em><ol type="a"> * <li>When the loop is called, the loop input values are saved in locals, to be passed (as the common suffix) to * every clause function. These locals are loop invariant. * <li>Each init function is executed in clause order (passing the common suffix) and the non-{@code void} values * are saved (as the common prefix) into locals. These locals are loop varying (unless their steps are identity * functions, as noted above). * <li>All function executions (except init functions) will be passed the common parameter sequence, consisting of * the non-{@code void} iteration values (in clause order) and then the loop inputs (in argument order). * <li>The step and pred functions are then executed, in clause order (step before pred), until a pred function * returns {@code false}. * <li>The non-{@code void} result from a step function call is used to update the corresponding loop variable. The * updated value is immediately visible to all subsequent function calls. * <li>If a pred function returns {@code false}, the corresponding fini function is called, and the resulting value * is returned from the loop as a whole. * </ol> * <p> * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the types / values * of loop variables; {@code A}/{@code a}, those of arguments passed to the resulting loop; and {@code R}, the * result types of finalizers as well as of the resulting loop. * <blockquote><pre>{@code * V... init...(A...); * boolean pred...(V..., A...); * V... step...(V..., A...); * R fini...(V..., A...); * R loop(A... a) { * V... v... = init...(a...); * for (;;) { * for ((v, p, s, f) in (v..., pred..., step..., fini...)) { * v = s(v..., a...); * if (!p(v..., a...)) { * return f(v..., a...); * } * } * } * } * }</pre></blockquote> * <p> * @apiNote Example: * <blockquote><pre>{@code * // iterative implementation of the factorial function as a loop handle * static int one(int k) { return 1; } * static int inc(int i, int acc, int k) { return i + 1; } * static int mult(int i, int acc, int k) { return i * acc; } * static boolean pred(int i, int acc, int k) { return i < k; } * static int fin(int i, int acc, int k) { return acc; } * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods * // null initializer for counter, should initialize to 0 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc}; * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin}; * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause); * assertEquals(120, loop.invoke(5)); * }</pre></blockquote> * * @param clauses an array of arrays (4-tuples) of {@link MethodHandle}s adhering to the rules described above. * * @return a method handle embodying the looping behavior as defined by the arguments. * * @throws IllegalArgumentException in case any of the constraints described above is violated. * * @see MethodHandles#whileLoop(MethodHandle, MethodHandle, MethodHandle) * @see MethodHandles#doWhileLoop(MethodHandle, MethodHandle, MethodHandle) * @see MethodHandles#countedLoop(MethodHandle, MethodHandle, MethodHandle) * @see MethodHandles#iteratedLoop(MethodHandle, MethodHandle, MethodHandle) * @since 9 */ public static MethodHandle loop(MethodHandle[]... clauses) { // Step 0: determine clause structure. checkLoop0(clauses); List<MethodHandle> init = new ArrayList<>(); List<MethodHandle> step = new ArrayList<>(); List<MethodHandle> pred = new ArrayList<>(); List<MethodHandle> fini = new ArrayList<>(); Stream.of(clauses).filter(c -> Stream.of(c).anyMatch(Objects::nonNull)).forEach(clause -> { init.add(clause[0]); // all clauses have at least length 1 step.add(clause.length <= 1 ? null : clause[1]); pred.add(clause.length <= 2 ? null : clause[2]); fini.add(clause.length <= 3 ? null : clause[3]); }); assert Stream.of(init, step, pred, fini).map(List::size).distinct().count() == 1; final int nclauses = init.size(); // Step 1A: determine iteration variables. final List<Class<?>> iterationVariableTypes = new ArrayList<>(); for (int i = 0; i < nclauses; ++i) { MethodHandle in = init.get(i); MethodHandle st = step.get(i); if (in == null && st == null) { iterationVariableTypes.add(void.class); } else if (in != null && st != null) { checkLoop1a(i, in, st); iterationVariableTypes.add(in.type().returnType()); } else { iterationVariableTypes.add(in == null ? st.type().returnType() : in.type().returnType()); } } final List<Class<?>> commonPrefix = iterationVariableTypes.stream().filter(t -> t != void.class). collect(Collectors.toList()); // Step 1B: determine loop parameters. final List<Class<?>> commonSuffix = buildCommonSuffix(init, step, pred, fini, commonPrefix.size()); checkLoop1b(init, commonSuffix); // Step 1C: determine loop return type. // Step 1D: check other types. final Class<?> loopReturnType = fini.stream().filter(Objects::nonNull).map(MethodHandle::type). map(MethodType::returnType).findFirst().orElse(void.class); checkLoop1cd(pred, fini, loopReturnType); // Step 2: determine parameter lists. final List<Class<?>> commonParameterSequence = new ArrayList<>(commonPrefix); commonParameterSequence.addAll(commonSuffix); checkLoop2(step, pred, fini, commonParameterSequence); // Step 3: fill in omitted functions. for (int i = 0; i < nclauses; ++i) { Class<?> t = iterationVariableTypes.get(i); if (init.get(i) == null) { init.set(i, empty(methodType(t, commonSuffix))); } if (step.get(i) == null) { step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i)); } if (pred.get(i) == null) { pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence)); } if (fini.get(i) == null) { fini.set(i, empty(methodType(t, commonParameterSequence))); } } // Step 4: fill in missing parameter types. List<MethodHandle> finit = fillParameterTypes(init, commonSuffix); List<MethodHandle> fstep = fillParameterTypes(step, commonParameterSequence); List<MethodHandle> fpred = fillParameterTypes(pred, commonParameterSequence); List<MethodHandle> ffini = fillParameterTypes(fini, commonParameterSequence); assert finit.stream().map(MethodHandle::type).map(MethodType::parameterList). allMatch(pl -> pl.equals(commonSuffix)); assert Stream.of(fstep, fpred, ffini).flatMap(List::stream).map(MethodHandle::type).map(MethodType::parameterList). allMatch(pl -> pl.equals(commonParameterSequence)); return MethodHandleImpl.makeLoop(loopReturnType, commonSuffix, finit, fstep, fpred, ffini); } private static List<MethodHandle> fillParameterTypes(List<MethodHandle> hs, final List<Class<?>> targetParams) { return hs.stream().map(h -> { int pc = h.type().parameterCount(); int tpsize = targetParams.size(); return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h; }).collect(Collectors.toList()); } /** * Constructs a {@code while} loop from an initializer, a body, and a predicate. This is a convenience wrapper for * the {@linkplain #loop(MethodHandle[][]) generic loop combinator}. * <p> * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) * generic loop combinator}. * <p> * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument * passed to the loop. * <blockquote><pre>{@code * V init(A); * boolean pred(V, A); * V body(V, A); * V whileLoop(A a) { * V v = init(a); * while (pred(v, a)) { * v = body(v, a); * } * return v; * } * }</pre></blockquote> * <p> * @apiNote Example: * <blockquote><pre>{@code * // implement the zip function for lists as a loop handle * static List<String> initZip(Iterator<String> a, Iterator<String> b) { return new ArrayList<>(); } * static boolean zipPred(List<String> zip, Iterator<String> a, Iterator<String> b) { return a.hasNext() && b.hasNext(); } * static List<String> zipStep(List<String> zip, Iterator<String> a, Iterator<String> b) { * zip.add(a.next()); * zip.add(b.next()); * return zip; * } * // assume MH_initZip, MH_zipPred, and MH_zipStep are handles to the above methods * MethodHandle loop = MethodHandles.whileLoop(MH_initZip, MH_zipPred, MH_zipStep); * List<String> a = Arrays.asList("a", "b", "c", "d"); * List<String> b = Arrays.asList("e", "f", "g", "h"); * List<String> zipped = Arrays.asList("a", "e", "b", "f", "c", "g", "d", "h"); * assertEquals(zipped, (List<String>) loop.invoke(a.iterator(), b.iterator())); * }</pre></blockquote> * * <p> * @implSpec The implementation of this method is equivalent to: * <blockquote><pre>{@code * MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { * MethodHandle[] * checkExit = {null, null, pred, identity(init.type().returnType())}, * varBody = {init, body}; * return loop(checkExit, varBody); * } * }</pre></blockquote> * * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's * result type. Passing {@code null} or a {@code void} init function will make the loop's result type * {@code void}. * @param pred condition for the loop, which may not be {@code null}. * @param body body of the loop, which may not be {@code null}. * * @return the value of the loop variable as the loop terminates. * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure * * @see MethodHandles#loop(MethodHandle[][]) * @since 9 */ public static MethodHandle whileLoop(MethodHandle init, MethodHandle pred, MethodHandle body) { MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : identity(init.type().returnType()); MethodHandle[] checkExit = {null, null, pred, fin}; MethodHandle[] varBody = {init, body}; return loop(checkExit, varBody); } /** * Constructs a {@code do-while} loop from an initializer, a body, and a predicate. This is a convenience wrapper * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. * <p> * The loop handle's result type is the same as the sole loop variable's, i.e., the result type of {@code init}. * The parameter type list of {@code init} also determines that of the resulting handle. The {@code pred} handle * must have an additional leading parameter of the same type as {@code init}'s result, and so must the {@code * body}. These constraints follow directly from those described for the {@linkplain MethodHandles#loop(MethodHandle[][]) * generic loop combinator}. * <p> * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument * passed to the loop. * <blockquote><pre>{@code * V init(A); * boolean pred(V, A); * V body(V, A); * V doWhileLoop(A a) { * V v = init(a); * do { * v = body(v, a); * } while (pred(v, a)); * return v; * } * }</pre></blockquote> * <p> * @apiNote Example: * <blockquote><pre>{@code * // int i = 0; while (i < limit) { ++i; } return i; => limit * static int zero(int limit) { return 0; } * static int step(int i, int limit) { return i + 1; } * static boolean pred(int i, int limit) { return i < limit; } * // assume MH_zero, MH_step, and MH_pred are handles to the above methods * MethodHandle loop = MethodHandles.doWhileLoop(MH_zero, MH_step, MH_pred); * assertEquals(23, loop.invoke(23)); * }</pre></blockquote> * * <p> * @implSpec The implementation of this method is equivalent to: * <blockquote><pre>{@code * MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { * MethodHandle[] clause = { init, body, pred, identity(init.type().returnType()) }; * return loop(clause); * } * }</pre></blockquote> * * * @param init initializer: it should provide the initial value of the loop variable. This controls the loop's * result type. Passing {@code null} or a {@code void} init function will make the loop's result type * {@code void}. * @param pred condition for the loop, which may not be {@code null}. * @param body body of the loop, which may not be {@code null}. * * @return the value of the loop variable as the loop terminates. * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure * * @see MethodHandles#loop(MethodHandle[][]) * @since 9 */ public static MethodHandle doWhileLoop(MethodHandle init, MethodHandle body, MethodHandle pred) { MethodHandle fin = init == null || init.type().returnType() == void.class ? zero(void.class) : identity(init.type().returnType()); MethodHandle[] clause = {init, body, pred, fin}; return loop(clause); } /** * Constructs a loop that runs a given number of iterations. The loop counter is an {@code int} initialized from the * {@code iterations} handle evaluation result. The counter is passed to the {@code body} function, so that must * accept an initial {@code int} argument. The result of the loop execution is the final value of the additional * local state. This is a convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop * combinator}. * <p> * The result type and parameter type list of {@code init} determine those of the resulting handle. The {@code * iterations} handle must accept the same parameter types as {@code init} but return an {@code int}. The {@code * body} handle must accept the same parameter types as well, preceded by an {@code int} parameter for the counter, * and a parameter of the same type as {@code init}'s result. These constraints follow directly from those described * for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. * <p> * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument * passed to the loop. * <blockquote><pre>{@code * int iterations(A); * V init(A); * V body(int, V, A); * V countedLoop(A a) { * int end = iterations(a); * V v = init(a); * for (int i = 0; i < end; ++i) { * v = body(i, v, a); * } * return v; * } * }</pre></blockquote> * <p> * @apiNote Example: * <blockquote><pre>{@code * // String s = "Lambdaman!"; for (int i = 0; i < 13; ++i) { s = "na " + s; } return s; * // => a variation on a well known theme * static String start(String arg) { return arg; } * static String step(int counter, String v, String arg) { return "na " + v; } * // assume MH_start and MH_step are handles to the two methods above * MethodHandle fit13 = MethodHandles.constant(int.class, 13); * MethodHandle loop = MethodHandles.countedLoop(fit13, MH_start, MH_step); * assertEquals("na na na na na na na na na na na na na Lambdaman!", loop.invoke("Lambdaman!")); * }</pre></blockquote> * * <p> * @implSpec The implementation of this method is equivalent to: * <blockquote><pre>{@code * MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { * return countedLoop(null, iterations, init, body); // null => constant zero * } * }</pre></blockquote> * * @param iterations a handle to return the number of iterations this loop should run. * @param init initializer for additional loop state. This determines the loop's result type. * Passing {@code null} or a {@code void} init function will make the loop's result type * {@code void}. * @param body the body of the loop, which must not be {@code null}. * It must accept an initial {@code int} parameter (for the counter), and then any * additional loop-local variable plus loop parameters. * * @return a method handle representing the loop. * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure * * @since 9 */ public static MethodHandle countedLoop(MethodHandle iterations, MethodHandle init, MethodHandle body) { return countedLoop(null, iterations, init, body); } /** * Constructs a loop that counts over a range of numbers. The loop counter is an {@code int} that will be * initialized to the {@code int} value returned from the evaluation of the {@code start} handle and run to the * value returned from {@code end} (exclusively) with a step width of 1. The counter value is passed to the {@code * body} function in each iteration; it has to accept an initial {@code int} parameter * for that. The result of the loop execution is the final value of the additional local state * obtained by running {@code init}. * This is a * convenience wrapper for the {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}. * <p> * The constraints for the {@code init} and {@code body} handles are the same as for {@link * #countedLoop(MethodHandle, MethodHandle, MethodHandle)}. Additionally, the {@code start} and {@code end} handles * must return an {@code int} and accept the same parameters as {@code init}. * <p> * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of * the sole loop variable as well as the result type of the loop; and {@code A}/{@code a}, that of the argument * passed to the loop. * <blockquote><pre>{@code * int start(A); * int end(A); * V init(A); * V body(int, V, A); * V countedLoop(A a) { * int s = start(a); * int e = end(a); * V v = init(a); * for (int i = s; i < e; ++i) { * v = body(i, v, a); * } * return v; * } * }</pre></blockquote> * * <p> * @implSpec The implementation of this method is equivalent to: * <blockquote><pre>{@code * MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, int.class, int.class); * // assume MH_increment and MH_lessThan are handles to x+1 and x<y of type int, * // assume MH_decrement is a handle to x-1 of type int * MethodHandle[] * indexVar = {start, MH_increment}, // i = start; i = i+1 * loopLimit = {end, null, * filterArgument(MH_lessThan, 0, MH_decrement), returnVar}, // i-1<end * bodyClause = {init, * filterArgument(dropArguments(body, 1, int.class), 0, MH_decrement}; // v = body(i-1, v) * return loop(indexVar, loopLimit, bodyClause); * } * }</pre></blockquote> * * @param start a handle to return the start value of the loop counter. * If it is {@code null}, a constant zero is assumed. * @param end a non-{@code null} handle to return the end value of the loop counter (the loop will run to {@code end-1}). * @param init initializer for additional loop state. This determines the loop's result type. * Passing {@code null} or a {@code void} init function will make the loop's result type * {@code void}. * @param body the body of the loop, which must not be {@code null}. * It must accept an initial {@code int} parameter (for the counter), and then any * additional loop-local variable plus loop parameters. * * @return a method handle representing the loop. * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure * * @since 9 */ public static MethodHandle countedLoop(MethodHandle start, MethodHandle end, MethodHandle init, MethodHandle body) { Class<?> resultType; MethodHandle actualInit; if (init == null) { resultType = body == null ? void.class : body.type().returnType(); actualInit = empty(methodType(resultType)); } else { resultType = init.type().returnType(); actualInit = init; } MethodHandle defaultResultHandle = resultType == void.class ? zero(void.class) : identity(resultType); MethodHandle actualBody = body == null ? dropArguments(defaultResultHandle, 0, int.class) : body; MethodHandle returnVar = dropArguments(defaultResultHandle, 0, int.class, int.class); MethodHandle actualEnd = end == null ? constant(int.class, 0) : end; MethodHandle decr = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_decrementCounter); MethodHandle[] indexVar = {start, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopStep)}; MethodHandle[] loopLimit = {actualEnd, null, filterArgument(MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_countedLoopPred), 0, decr), returnVar}; MethodHandle[] bodyClause = {actualInit, filterArgument(dropArguments(actualBody, 1, int.class), 0, decr)}; return loop(indexVar, loopLimit, bodyClause); } /** * Constructs a loop that ranges over the elements produced by an {@code Iterator<T>}. * The iterator will be produced by the evaluation of the {@code iterator} handle. * This handle must have {@link java.util.Iterator} as its return type. * If this handle is passed as {@code null} the method {@link Iterable#iterator} will be used instead, * and will be applied to a leading argument of the loop handle. * Each value produced by the iterator is passed to the {@code body}, which must accept an initial {@code T} parameter. * The result of the loop execution is the final value of the additional local state * obtained by running {@code init}. * <p> * This is a convenience wrapper for the * {@linkplain MethodHandles#loop(MethodHandle[][]) generic loop combinator}, and the constraints imposed on the {@code body} * handle follow directly from those described for the latter. * <p> * Here is pseudocode for the resulting loop handle. In the code, {@code V}/{@code v} represent the type / value of * the loop variable as well as the result type of the loop; {@code T}/{@code t}, that of the elements of the * structure the loop iterates over, and {@code A}/{@code a}, that of the argument passed to the loop. * <blockquote><pre>{@code * Iterator<T> iterator(A); // defaults to Iterable::iterator * V init(A); * V body(T,V,A); * V iteratedLoop(A a) { * Iterator<T> it = iterator(a); * V v = init(a); * for (T t : it) { * v = body(t, v, a); * } * return v; * } * }</pre></blockquote> * <p> * The type {@code T} may be either a primitive or reference. * Since type {@code Iterator<T>} is erased in the method handle representation to the raw type * {@code Iterator}, the {@code iteratedLoop} combinator adjusts the leading argument type for {@code body} * to {@code Object} as if by the {@link MethodHandle#asType asType} conversion method. * Therefore, if an iterator of the wrong type appears as the loop is executed, * runtime exceptions may occur as the result of dynamic conversions performed by {@code asType}. * <p> * @apiNote Example: * <blockquote><pre>{@code * // reverse a list * static List<String> reverseStep(String e, List<String> r, List<String> l) { * r.add(0, e); * return r; * } * static List<String> newArrayList(List<String> l) { return new ArrayList<>(); } * // assume MH_reverseStep, MH_newArrayList are handles to the above methods * MethodHandle loop = MethodHandles.iteratedLoop(null, MH_newArrayList, MH_reverseStep); * List<String> list = Arrays.asList("a", "b", "c", "d", "e"); * List<String> reversedList = Arrays.asList("e", "d", "c", "b", "a"); * assertEquals(reversedList, (List<String>) loop.invoke(list)); * }</pre></blockquote> * <p> * @implSpec The implementation of this method is equivalent to (excluding error handling): * <blockquote><pre>{@code * MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { * // assume MH_next and MH_hasNext are handles to methods of Iterator * Class<?> itype = iterator.type().returnType(); * Class<?> ttype = body.type().parameterType(0); * MethodHandle returnVar = dropArguments(identity(init.type().returnType()), 0, itype); * MethodHandle nextVal = MH_next.asType(MH_next.type().changeReturnType(ttype)); * MethodHandle[] * iterVar = {iterator, null, MH_hasNext, returnVar}, // it = iterator(); while (it.hasNext) * bodyClause = {init, filterArgument(body, 0, nextVal)}; // v = body(t, v, a); * return loop(iterVar, bodyClause); * } * }</pre></blockquote> * * @param iterator a handle to return the iterator to start the loop. * The handle must have {@link java.util.Iterator} as its return type. * Passing {@code null} will make the loop call {@link Iterable#iterator()} on the first * incoming value. * @param init initializer for additional loop state. This determines the loop's result type. * Passing {@code null} or a {@code void} init function will make the loop's result type * {@code void}. * @param body the body of the loop, which must not be {@code null}. * It must accept an initial {@code T} parameter (for the iterated values), and then any * additional loop-local variable plus loop parameters. * * @return a method handle embodying the iteration loop functionality. * @throws IllegalArgumentException if any argument has a type inconsistent with the loop structure * * @since 9 */ public static MethodHandle iteratedLoop(MethodHandle iterator, MethodHandle init, MethodHandle body) { checkIteratedLoop(iterator, body); Class<?> resultType = init == null ? body == null ? void.class : body.type().returnType() : init.type().returnType(); boolean voidResult = resultType == void.class; MethodHandle initIterator; if (iterator == null) { MethodHandle initit = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_initIterator); initIterator = initit.asType(initit.type().changeParameterType(0, body.type().parameterType(voidResult ? 1 : 2))); } else { initIterator = iterator.asType(iterator.type().changeReturnType(Iterator.class)); } Class<?> ttype = body.type().parameterType(0); MethodHandle returnVar = dropArguments(voidResult ? zero(void.class) : identity(resultType), 0, Iterator.class); MethodHandle initnx = MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iterateNext); MethodHandle nextVal = initnx.asType(initnx.type().changeReturnType(ttype)); MethodHandle[] iterVar = {initIterator, null, MethodHandleImpl.getConstantHandle(MethodHandleImpl.MH_iteratePred), returnVar}; MethodHandle[] bodyClause = {init, filterArgument(body, 0, nextVal)}; return loop(iterVar, bodyClause); } /** * Makes a method handle that adapts a {@code target} method handle by wrapping it in a {@code try-finally} block. * Another method handle, {@code cleanup}, represents the functionality of the {@code finally} block. Any exception * thrown during the execution of the {@code target} handle will be passed to the {@code cleanup} handle. The * exception will be rethrown, unless {@code cleanup} handle throws an exception first. The * value returned from the {@code cleanup} handle's execution will be the result of the execution of the * {@code try-finally} handle. * <p> * The {@code cleanup} handle will be passed one or two additional leading arguments. * The first is the exception thrown during the * execution of the {@code target} handle, or {@code null} if no exception was thrown. * The second is the result of the execution of the {@code target} handle, or, if it throws an exception, * a {@code null}, zero, or {@code false} value of the required type is supplied as a placeholder. * The second argument is not present if the {@code target} handle has a {@code void} return type. * (Note that, except for argument type conversions, combinators represent {@code void} values in parameter lists * by omitting the corresponding paradoxical arguments, not by inserting {@code null} or zero values.) * <p> * The {@code target} and {@code cleanup} handles must have the same corresponding argument and return types, except * that the {@code cleanup} handle may omit trailing arguments. Also, the {@code cleanup} handle must have one or * two extra leading parameters:<ul> * <li>a {@code Throwable}, which will carry the exception thrown by the {@code target} handle (if any); and * <li>a parameter of the same type as the return type of both {@code target} and {@code cleanup}, which will carry * the result from the execution of the {@code target} handle. * This parameter is not present if the {@code target} returns {@code void}. * </ul> * <p> * The pseudocode for the resulting adapter looks as follows. In the code, {@code V} represents the result type of * the {@code try/finally} construct; {@code A}/{@code a}, the types and values of arguments to the resulting * handle consumed by the cleanup; and {@code B}/{@code b}, those of arguments to the resulting handle discarded by * the cleanup. * <blockquote><pre>{@code * V target(A..., B...); * V cleanup(Throwable, V, A...); * V adapter(A... a, B... b) { * V result = (zero value for V); * Throwable throwable = null; * try { * result = target(a..., b...); * } catch (Throwable t) { * throwable = t; * throw t; * } finally { * result = cleanup(throwable, result, a...); * } * return result; * } * }</pre></blockquote> * <p> * Note that the saved arguments ({@code a...} in the pseudocode) cannot * be modified by execution of the target, and so are passed unchanged * from the caller to the cleanup, if it is invoked. * <p> * The target and cleanup must return the same type, even if the cleanup * always throws. * To create such a throwing cleanup, compose the cleanup logic * with {@link #throwException throwException}, * in order to create a method handle of the correct return type. * <p> * Note that {@code tryFinally} never converts exceptions into normal returns. * In rare cases where exceptions must be converted in that way, first wrap * the target with {@link #catchException(MethodHandle, Class, MethodHandle)} * to capture an outgoing exception, and then wrap with {@code tryFinally}. * * @param target the handle whose execution is to be wrapped in a {@code try} block. * @param cleanup the handle that is invoked in the finally block. * * @return a method handle embodying the {@code try-finally} block composed of the two arguments. * @throws NullPointerException if any argument is null * @throws IllegalArgumentException if {@code cleanup} does not accept * the required leading arguments, or if the method handle types do * not match in their return types and their * corresponding trailing parameters * * @see MethodHandles#catchException(MethodHandle, Class, MethodHandle) * @since 9 */ public static MethodHandle tryFinally(MethodHandle target, MethodHandle cleanup) { List<Class<?>> targetParamTypes = target.type().parameterList(); List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); Class<?> rtype = target.type().returnType(); checkTryFinally(target, cleanup); // Match parameter lists: if the cleanup has a shorter parameter list than the target, add ignored arguments. // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the // target parameter list. cleanup = dropArgumentsToMatch(cleanup, (rtype == void.class ? 1 : 2), targetParamTypes, 0); return MethodHandleImpl.makeTryFinally(target, cleanup, rtype, targetParamTypes); } /** * Adapts a target method handle by pre-processing some of its arguments, starting at a given position, and then * calling the target with the result of the pre-processing, inserted into the original sequence of arguments just * before the folded arguments. * <p> * This method is closely related to {@link #foldArguments(MethodHandle, MethodHandle)}, but allows to control the * position in the parameter list at which folding takes place. The argument controlling this, {@code pos}, is a * zero-based index. The aforementioned method {@link #foldArguments(MethodHandle, MethodHandle)} assumes position * 0. * <p> * @apiNote Example: * <blockquote><pre>{@code import static java.lang.invoke.MethodHandles.*; import static java.lang.invoke.MethodType.*; ... MethodHandle trace = publicLookup().findVirtual(java.io.PrintStream.class, "println", methodType(void.class, String.class)) .bindTo(System.out); MethodHandle cat = lookup().findVirtual(String.class, "concat", methodType(String.class, String.class)); assertEquals("boojum", (String) cat.invokeExact("boo", "jum")); MethodHandle catTrace = foldArguments(cat, 1, trace); // also prints "jum": assertEquals("boojum", (String) catTrace.invokeExact("boo", "jum")); * }</pre></blockquote> * <p>Here is pseudocode for the resulting adapter. In the code, {@code T} * represents the result type of the {@code target} and resulting adapter. * {@code V}/{@code v} represent the type and value of the parameter and argument * of {@code target} that precedes the folding position; {@code V} also is * the result type of the {@code combiner}. {@code A}/{@code a} denote the * types and values of the {@code N} parameters and arguments at the folding * position. {@code Z}/{@code z} and {@code B}/{@code b} represent the types * and values of the {@code target} parameters and arguments that precede and * follow the folded parameters and arguments starting at {@code pos}, * respectively. * <blockquote><pre>{@code * // there are N arguments in A... * T target(Z..., V, A[N]..., B...); * V combiner(A...); * T adapter(Z... z, A... a, B... b) { * V v = combiner(a...); * return target(z..., v, a..., b...); * } * // and if the combiner has a void return: * T target2(Z..., A[N]..., B...); * void combiner2(A...); * T adapter2(Z... z, A... a, B... b) { * combiner2(a...); * return target2(z..., a..., b...); * } * }</pre></blockquote> * <p> * <em>Note:</em> The resulting adapter is never a {@linkplain MethodHandle#asVarargsCollector * variable-arity method handle}, even if the original target method handle was. * * @param target the method handle to invoke after arguments are combined * @param pos the position at which to start folding and at which to insert the folding result; if this is {@code * 0}, the effect is the same as for {@link #foldArguments(MethodHandle, MethodHandle)}. * @param combiner method handle to call initially on the incoming arguments * @return method handle which incorporates the specified argument folding logic * @throws NullPointerException if either argument is null * @throws IllegalArgumentException if {@code combiner}'s return type * is non-void and not the same as the argument type at position {@code pos} of * the target signature, or if the {@code N} argument types at position {@code pos} * of the target signature * (skipping one matching the {@code combiner}'s return type) * are not identical with the argument types of {@code combiner} * * @see #foldArguments(MethodHandle, MethodHandle) * @since 9 */ public static MethodHandle foldArguments(MethodHandle target, int pos, MethodHandle combiner) { MethodType targetType = target.type(); MethodType combinerType = combiner.type(); Class<?> rtype = foldArgumentChecks(pos, targetType, combinerType); BoundMethodHandle result = target.rebind(); boolean dropResult = rtype == void.class; LambdaForm lform = result.editor().foldArgumentsForm(1 + pos, dropResult, combinerType.basicType()); MethodType newType = targetType; if (!dropResult) { newType = newType.dropParameterTypes(pos, pos + 1); } result = result.copyWithExtendL(newType, lform, combiner); return result; } private static void checkLoop0(MethodHandle[][] clauses) { if (clauses == null || clauses.length == 0) { throw newIllegalArgumentException("null or no clauses passed"); } if (Stream.of(clauses).anyMatch(Objects::isNull)) { throw newIllegalArgumentException("null clauses are not allowed"); } if (Stream.of(clauses).anyMatch(c -> c.length > 4)) { throw newIllegalArgumentException("All loop clauses must be represented as MethodHandle arrays with at most 4 elements."); } } private static void checkLoop1a(int i, MethodHandle in, MethodHandle st) { if (in.type().returnType() != st.type().returnType()) { throw misMatchedTypes("clause " + i + ": init and step return types", in.type().returnType(), st.type().returnType()); } } private static List<Class<?>> buildCommonSuffix(List<MethodHandle> init, List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, int cpSize) { final List<Class<?>> empty = List.of(); final List<MethodHandle> nonNullInits = init.stream().filter(Objects::nonNull).collect(Collectors.toList()); if (nonNullInits.isEmpty()) { final List<Class<?>> longest = Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull). // take only those that can contribute to a common suffix because they are longer than the prefix map(MethodHandle::type).filter(t -> t.parameterCount() > cpSize).map(MethodType::parameterList). reduce((p, q) -> p.size() >= q.size() ? p : q).orElse(empty); return longest.size() == 0 ? empty : longest.subList(cpSize, longest.size()); } else { return nonNullInits.stream().map(MethodHandle::type).map(MethodType::parameterList). reduce((p, q) -> p.size() >= q.size() ? p : q).get(); } } private static void checkLoop1b(List<MethodHandle> init, List<Class<?>> commonSuffix) { if (init.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::parameterList). anyMatch(pl -> !pl.equals(commonSuffix.subList(0, pl.size())))) { throw newIllegalArgumentException("found non-effectively identical init parameter type lists: " + init + " (common suffix: " + commonSuffix + ")"); } } private static void checkLoop1cd(List<MethodHandle> pred, List<MethodHandle> fini, Class<?> loopReturnType) { if (fini.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). anyMatch(t -> t != loopReturnType)) { throw newIllegalArgumentException("found non-identical finalizer return types: " + fini + " (return type: " + loopReturnType + ")"); } if (!pred.stream().filter(Objects::nonNull).findFirst().isPresent()) { throw newIllegalArgumentException("no predicate found", pred); } if (pred.stream().filter(Objects::nonNull).map(MethodHandle::type).map(MethodType::returnType). anyMatch(t -> t != boolean.class)) { throw newIllegalArgumentException("predicates must have boolean return type", pred); } } private static void checkLoop2(List<MethodHandle> step, List<MethodHandle> pred, List<MethodHandle> fini, List<Class<?>> commonParameterSequence) { final int cpSize = commonParameterSequence.size(); if (Stream.of(step, pred, fini).flatMap(List::stream).filter(Objects::nonNull).map(MethodHandle::type). map(MethodType::parameterList). anyMatch(pl -> pl.size() > cpSize || !pl.equals(commonParameterSequence.subList(0, pl.size())))) { throw newIllegalArgumentException("found non-effectively identical parameter type lists:\nstep: " + step + "\npred: " + pred + "\nfini: " + fini + " (common parameter sequence: " + commonParameterSequence + ")"); } } private static void checkIteratedLoop(MethodHandle iterator, MethodHandle body) { if (null != iterator && !Iterator.class.isAssignableFrom(iterator.type().returnType())) { throw newIllegalArgumentException("iteratedLoop first argument must have Iterator return type"); } if (null == body) { throw newIllegalArgumentException("iterated loop body must not be null"); } } private static void checkTryFinally(MethodHandle target, MethodHandle cleanup) { Class<?> rtype = target.type().returnType(); if (rtype != cleanup.type().returnType()) { throw misMatchedTypes("target and return types", cleanup.type().returnType(), rtype); } List<Class<?>> cleanupParamTypes = cleanup.type().parameterList(); if (!Throwable.class.isAssignableFrom(cleanupParamTypes.get(0))) { throw misMatchedTypes("cleanup first argument and Throwable", cleanup.type(), Throwable.class); } if (rtype != void.class && cleanupParamTypes.get(1) != rtype) { throw misMatchedTypes("cleanup second argument and target return type", cleanup.type(), rtype); } // The cleanup parameter list (minus the leading Throwable and result parameters) must be a sublist of the // target parameter list. int cleanupArgIndex = rtype == void.class ? 1 : 2; List<Class<?>> cleanupArgSuffix = cleanupParamTypes.subList(cleanupArgIndex, cleanupParamTypes.size()); List<Class<?>> targetParamTypes = target.type().parameterList(); if (targetParamTypes.size() < cleanupArgSuffix.size() || !cleanupArgSuffix.equals(targetParamTypes.subList(0, cleanupParamTypes.size() - cleanupArgIndex))) { throw misMatchedTypes("cleanup parameters after (Throwable,result) and target parameter list prefix", cleanup.type(), target.type()); } } }
gpl-2.0
52North/SOS
spring/install-controller/src/main/java/org/n52/sos/web/install/ErrorMessages.java
5662
/* * Copyright (C) 2012-2022 52°North Spatial Information Research GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * 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. */ package org.n52.sos.web.install; /** * TODO JavaDoc * * @author <a href="mailto:c.autermann@52north.org">Christian Autermann</a> * * @since 4.0.0 */ public interface ErrorMessages { String INVALID_DATASOURCE = "The datasource %s is invalid!"; String POST_GIS_IS_NOT_INSTALLED_IN_THE_DATABASE = "PostGIS is not installed in the database."; String COULD_NOT_INSERT_TEST_DATA = "Could not insert test data: %s"; String NO_DRIVER_SPECIFIED = "no driver specified"; String NO_SCHEMA_SPECIFIED = "No schema specified"; String NO_JDBC_URL_SPECIFIED = "No JDBC URL specified."; String COULD_NOT_WRITE_DATASOURCE_CONFIG = "Could not write datasource config: %s"; String PASSWORD_IS_INVALID = "Password is invalid."; String COULD_NOT_READ_SPATIAL_REF_SYS_TABLE = "Could not read 'spatial_ref_sys' table of PostGIS. " + "Please revise your database configuration."; String COULD_NOT_LOAD_DIALECT = "Could not load dialect: %s"; String COULD_NOT_LOAD_CONNECTION_POOL = "Could not load connection pool: %s"; String COULD_NOT_VALIDATE_PARAMETER = "Could not validate '%s' parameter: %s"; String COULD_NOT_INSTANTIATE_CONFIGURATOR = "Could not instantiate Configurator: %s"; String INVALID_JDBC_URL_WITH_ERROR_MESSAGE = "Invalid JDBC URL: %s"; String CAN_NOT_CREATE_STATEMENT = "Cannot create Statement: %s"; String COULD_NOT_CONNECT_TO_THE_DATABASE = "Could not connect to the database: %s"; String COULD_NOT_SAVE_ADMIN_CREDENTIALS = "Could not save admin credentials into the database: %s"; String INVALID_JDBC_URL = "Invalid JDBC URL."; String USERNAME_IS_INVALID = "Username is invalid."; String COULD_NOT_LOAD_DRIVER = "Could not load Driver: %s"; String NO_DIALECT_SPECIFIED = "no dialect specified"; String TABLES_ALREADY_CREATED_BUT_SHOULD_NOT_OVERWRITE = "Tables already created, but should not overwrite. " + "Please take a look at the 'Actions' section."; String COULD_NOT_INSERT_SETTINGS = "Could not insert settings into the database: %s"; String NO_CONNECTION_POOL_SPECIFIED = "no connection pool specified"; String COULD_NOT_CREATE_SOS_TABLES = "Could not create SOS tables: %s"; String COULD_NOT_DROP_SOS_TABLES = "Could not drop SOS tables: %s"; String COULD_NOT_FIND_FILE = "Could not find file '%s'!"; String COULD_NOT_CONNECT_TO_DATABASE_SERVER = "Could not connect to DB server: %s"; String COULD_NOT_CREATE_TABLES = "Could not create tables: %s"; String NO_TABLES_AND_SHOULD_NOT_CREATE = "No tables are present in the database " + "and no tables should be created. Enable 'Create tables' or select another datasource."; String COULD_NOT_INSTANTIATE_SETTINGS_MANAGER = "Could not instantiate Settings Manager: %s"; String NO_DEFINITON_FOUND = "No definiton found for setting with key '%s'"; String COULD_NOT_DELETE_PREVIOUS_SETTINGS = "Could not delete previous settings: %s"; String COULD_NOT_SET_CATALOG = "Could not set catalog search path"; String COULD_NOT_CHECK_IF_TABLE_EXISTS = "Could not check if table '%s' exists: %s"; String COULD_NOT_CHECK_IF_SCHEMA_EXISTS = "Could not check if schema '%s' exists: %s"; String SCHEMA_DOES_NOT_EXIST = "Schema %s does not exist"; String EXISTING_SCHEMA_DIFFERS_DROP_CREATE_SCHEMA = "The installed schema does not accord to the schema which should be created! Please, check the checkbox " + "'Old observation concept' or delete existing schema manually with the according drop schema " + "in /misc/db!"; String EXISTING_SCHEMA_REQUIRES_UPDATE = "The installed schema is corrupt/invalid (%s).%nTry to delete the existing tables and check " + "'Create tables' or check 'Force update tables' (experimental).%nOr check for update" + " scripts in /misc/db!"; String EXISTING_SCHEMA_DIFFERS_UPDATE_SCHEMA = "The installed schema does not accord to the update schema! Please, check the checkbox " + "'Old observation concept'!"; String TO_CHECK_ERROR_MESSAGE_FOI_COL_IN_OBS_TAB = "Missing column: featureOfInterestId in public.observation"; String TO_CHECK_ERROR_MESSAGE_SERIES_COL_IN_OBS_TAB = "Missing column: seriesId in public.observation"; }
gpl-2.0
justayak/peersim-spray
src/main/java/descent/rps/AAgingPartialView.java
1409
package descent.rps; import java.util.ArrayList; import java.util.List; import peersim.core.Node; import descent.scamp.PartialView; public abstract class AAgingPartialView extends PartialView implements IAgingPartialView { protected ArrayList<Integer> ages; public AAgingPartialView() { super(); this.ages = new ArrayList<Integer>(); } public void incrementAge() { for (Integer age : this.ages) { ++age; } } public Node getOldest() { return this.partialView.get(0); } public abstract List<Node> getSample(Node caller, Node neighbor, boolean isInitiator); @Override public boolean removeNode(Node peer) { int index = this.getIndex(peer); if (index >= 0) { this.partialView.remove(index); this.ages.remove(index); } return index >= 0; } public boolean removeNode(Node peer, Integer age) { int i = 0; boolean found = false; while (!found && i < this.partialView.size() && this.ages.get(i) >= age) { if (this.partialView.get(i).getID() == peer.getID()) { found = true; } else { ++i; } } if (found) { this.partialView.remove(i); this.ages.remove(i); } return found; } public abstract void mergeSample(Node me, Node other, List<Node> newSample, List<Node> oldSample, boolean isInitiator); @Override public abstract boolean addNeighbor(Node peer); public void clear() { super.clear(); this.ages.clear(); } }
gpl-2.0
donghyuck/podo-project
competency-assessment/src/main/java/com/podosoftware/competency/competency/DefaultEssentialElement.java
1815
package com.podosoftware.competency.competency; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnore; import architecture.common.model.support.PropertyAwareSupport; public class DefaultEssentialElement extends PropertyAwareSupport implements EssentialElement { private Long competencyId; private Long essentialElementId; private String name; private String capabilityStandard; private Integer level; private String description; public DefaultEssentialElement() { competencyId = -1L; essentialElementId = -1L; name = null; this.description = null; level = 0; } public Long getCompetencyId() { return competencyId; } public void setCompetencyId(Long competencyId) { this.competencyId = competencyId; } public Long getEssentialElementId() { return essentialElementId; } public void setEssentialElementId(Long essentialElementId) { this.essentialElementId = essentialElementId; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCapabilityStandard() { return capabilityStandard; } public void setCapabilityStandard(String capabilityStandard) { this.capabilityStandard = capabilityStandard; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @JsonIgnore public int getCachedSize() { return 0; } @JsonIgnore public Serializable getPrimaryKeyObject() { return essentialElementId; } public int getModelObjectType() { return 54; } }
gpl-2.0
siriuswinds/KGraph
src/com/example/KGraph/StockList.java
3504
package com.example.KGraph; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by yangj on 13-12-12. */ public class StockList extends Activity { private DBManager dbmgr; private ListView m_stocklist; private SimpleAdapter adapter; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.stockview); dbmgr = new DBManager(this); //dbmgr.deleteStockDays(); m_stocklist = (ListView)findViewById(R.id.stocklist); m_stocklist.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { TextView mTxtcode = (TextView)view.findViewById(R.id.txtStockCode); String code = mTxtcode.getText().toString(); Intent intent = new Intent(); intent.setClass(StockList.this,StockDayList.class); Bundle bundle = new Bundle(); bundle.putString("STOCKCODE",code); intent.putExtras(bundle); startActivity(intent); mTxtcode = null; } }); //加载stock列表 loadStockList(); } @Override protected void onDestroy(){ super.onDestroy(); dbmgr.closeDB(); } public void loadStockList(){ List<StockDay> stocks = dbmgr.queryStock(); //如果本地数据库没有数据,从本地文件读取,并写入数据库 if(stocks==null || stocks.size()==0){ stocks = StockDay.ReadFromFile(this.getApplicationContext()); dbmgr.addStock(stocks); } //加载到listview ArrayList<Map<String,String>> list = new ArrayList<Map<String, String>>(); for (StockDay stock:stocks){ HashMap<String,String> map = new HashMap<String, String>(); map.put("name",stock.NAME); map.put("code",stock.CODE); map.put("industry",stock.INDUSTRY); map.put("region",stock.REGION); list.add(map); } //SimpleAdapter adapter = new SimpleAdapter(this,list,android.R.layout.simple_list_item_2,new String[]{"name","info"},new int[]{android.R.id.text1,android.R.id.text2}); adapter = new SimpleAdapter(this,list,R.layout.stocklist,new String[]{"code","name","industry","region"},new int[]{R.id.txtStockCode,R.id.txtStockName,R.id.txtIndustry,R.id.txtRegion}); m_stocklist.setAdapter(adapter); } public void queryTheCursor(){ /* Cursor c = dbmgr.queryTheCursor(); startManagingCursor(c); CursorWrapper cursorWrapper = new CursorWrapper(c){ @Override public String getString(int columnIndex){ if(getColumnName(columnIndex).equals("CODE")){ String code = getString(getColumnIndex("CODE")); return code; } return super.getString(columnIndex); } }; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursorWrapper,new String[]{"name","code"},new int[]{android.R.id.text1,android.R.id.text2}); */ } }
gpl-2.0
joezxh/DATAX-UI
eshbase-commons/src/main/java/net/iharding/modules/meta/service/MetaPropertyService.java
349
package net.iharding.modules.meta.service; import org.guess.core.service.BaseService; import net.iharding.modules.meta.model.MetaProperty; /** * * @ClassName: MetaProperty * @Description: MetaPropertyservice * @author Joe.zhang * @date 2014-8-5 下午02:04:46 * */ public interface MetaPropertyService extends BaseService<MetaProperty, Long>{ }
gpl-2.0
oonym/l2InterludeServer
L2J_Server/java/net/sf/l2j/gameserver/skills/conditions/ConditionUsingSkill.java
1345
/* * 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, 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. * * http://www.gnu.org/copyleft/gpl.html */ package net.sf.l2j.gameserver.skills.conditions; import net.sf.l2j.gameserver.skills.Env; /** * @author mkizub TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code Templates */ public final class ConditionUsingSkill extends Condition { private final int _skillId; public ConditionUsingSkill(int skillId) { _skillId = skillId; } @Override public boolean testImpl(Env env) { if (env.skill == null) { return false; } return env.skill.getId() == _skillId; } }
gpl-2.0
dain/graal
graal/com.oracle.graal.hotspot/src/com/oracle/graal/hotspot/nodes/VMErrorNode.java
3116
/* * Copyright (c) 2012, 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. * * 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 com.oracle.graal.hotspot.nodes; import static com.oracle.graal.hotspot.HotSpotBackend.*; import static com.oracle.graal.hotspot.nodes.CStringNode.*; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.compiler.common.type.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; import com.oracle.graal.replacements.*; /** * Causes the VM to exit with a description of the current Java location and an optional * {@linkplain Log#printf(String, long) formatted} error message specified. */ public final class VMErrorNode extends DeoptimizingStubCall implements LIRLowerable { private final String format; @Input private ValueNode value; public VMErrorNode(String format, ValueNode value) { super(StampFactory.forVoid()); this.format = format; this.value = value; } @Override public void generate(NodeLIRBuilderTool gen) { String whereString; if (stateBefore() != null) { String nl = CodeUtil.NEW_LINE; StringBuilder sb = new StringBuilder("in compiled code associated with frame state:"); FrameState fs = stateBefore(); while (fs != null) { MetaUtil.appendLocation(sb.append(nl).append("\t"), fs.method(), fs.bci); fs = fs.outerFrameState(); } whereString = sb.toString(); } else { ResolvedJavaMethod method = graph().method(); whereString = "in compiled code for " + (method == null ? graph().toString() : method.format("%H.%n(%p)")); } Value whereArg = emitCString(gen, whereString); Value formatArg = emitCString(gen, format); ForeignCallLinkage linkage = gen.getLIRGeneratorTool().getForeignCalls().lookupForeignCall(VM_ERROR); gen.getLIRGeneratorTool().emitForeignCall(linkage, null, whereArg, formatArg, gen.operand(value)); } @NodeIntrinsic public static native void vmError(@ConstantNodeParameter String format, long value); }
gpl-2.0
axnsan12/Airplanes
airplanes/src/com/axnsan/airplanes/screens/MainMenuScreen.java
3140
package com.axnsan.airplanes.screens; import com.axnsan.airplanes.Airplanes; import com.axnsan.airplanes.util.FontManager; import com.axnsan.airplanes.util.StringManager; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.utils.Align; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; public class MainMenuScreen implements Screen { private Stage stage; private Airplanes game; private Table table; private TextButton exitButton; public MainMenuScreen() { this.game = Airplanes.game; stage = new Stage(); float h = Gdx.graphics.getHeight(); table = new Table(); table.setFillParent(true); stage.addActor(table); table.align(Align.top); table.padTop(h/5); exitButton = new TextButton(StringManager.getString("main_exit"), game.skin); exitButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { game.exit(); } }); stage.addActor(exitButton); } @Override public void show() { game.setScreen(new PlayMenuScreen()); /*game.input.clear(); game.input.addProcessor(game); game.input.addProcessor(stage);*/ } @Override public void dispose() { Airplanes.game.input.removeProcessor(stage); if (stage != null) stage.dispose(); stage = null; } @Override public void render(float delta) { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); if (stage != null) { stage.act(delta); stage.draw(); } try { Thread.sleep(Math.max(0, (long) (Airplanes.MAX_FRAME_TIME - Gdx.graphics.getRawDeltaTime()))); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void resize(int width, int height) { stage.setViewport(width, height); float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); table.clearChildren(); game.setTextButtonFont(FontManager.getFontForHeight(h/10 - h/20)); TextButton startGameButton = new TextButton(StringManager.getString("main_play"), game.skin); startGameButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { game.setScreen(new PlayMenuScreen()); } }); table.add(startGameButton).pad(5).width(w/2).height(h/10); table.row(); TextButton optionsButton = new TextButton(StringManager.getString("main_options"), game.skin); table.add(optionsButton).pad(5).width(w/2).height(h/10); table.row(); exitButton.setBounds(w/4, h/5, w/2, h/10); exitButton.setStyle(game.skin.get(TextButtonStyle.class)); Gdx.graphics.requestRendering(); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { Airplanes.game.input.removeProcessor(stage); } }
gpl-2.0
favedit/MoPlatform
mo-2-core/src/engine-java/org/mo/eng/global/IGlobalConsole.java
1790
package org.mo.eng.global; //============================================================ // <T>全局管理器接口。</T> //============================================================ public interface IGlobalConsole { //============================================================ // <T>根据名称查找一个全局对象。</T> // // @param name 名称 // @return 全局对象 //============================================================ <V> V find(String name); //============================================================ // <T>根据名称查找一个全局对象。</T> // // @param clazz 类对象 // @return 全局对象 //============================================================ <V> V find(Class<?> clazz); //============================================================ // <T>根据名称查找一个全局对象。</T> // // @param name 名称 // @param clazz 类对象 // @return 全局对象 //============================================================ <V> V find(String name, Class<?> clazz); //============================================================ // <T>根据名称移除一个全局对象。</T> // // @param name 名称 //============================================================ void remove(String name); //============================================================ // <T>根据名称移除一个全局对象。</T> // // @param clazz 类对象 //============================================================ void remove(Class<?> clazz); //============================================================ // <T>清空所有内容。</T> //============================================================ void clear(); }
gpl-2.0
JMaNGOS/JMaNGOS
Commons/src/main/java/org/jmangos/commons/enums/UnitFlags.java
2925
/******************************************************************************* * Copyright (C) 2013 JMaNGOS <http://jmangos.org/> * * 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, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.jmangos.commons.enums; /** * The Enum UnitFlags. */ public enum UnitFlags { /** The UNK_0. */ UNK_0(1 << 0), /** The NON_ATTACKABLE. */ NON_ATTACKABLE(1 << 1), /** The DISABLE_MOVE. */ DISABLE_MOVE(1 << 2), /** The PVP_ATTACKABLE. */ PVP_ATTACKABLE(1 << 3), /** The RENAME. */ RENAME(1 << 4), /** The PREPARATION. */ PREPARATION(1 << 5), /** The UNK_6. */ UNK_6(1 << 6), /** The NOT_ATTACKABLE_1. */ NOT_ATTACKABLE_1(1 << 7), /** The OOC_NOT_ATTACKABLE. */ OOC_NOT_ATTACKABLE(1 << 8), /** The PASSIVE. */ PASSIVE(1 << 9), /** The LOOTING. */ LOOTING(1 << 10), /** The PET_IN_COMBAT. */ PET_IN_COMBAT(1 << 11), /** The PVP. */ PVP(1 << 12), /** The SILENCED. */ SILENCED(1 << 13), /** The UNK_14. */ UNK_14(1 << 14), /** The UNK_15. */ UNK_15(1 << 15), /** The UNK_16. */ UNK_16(1 << 16), /** The PACIFIED. */ PACIFIED(1 << 17), /** The STUNNED. */ STUNNED(1 << 18), /** The IN_COMBAT. */ IN_COMBAT(1 << 19), /** The TAXI_FLIGHT. */ TAXI_FLIGHT(1 << 20), /** The DISARMED. */ DISARMED(1 << 21), /** The CONFUSED. */ CONFUSED(1 << 22), /** The FLEEING. */ FLEEING(1 << 23), /** The PLAYER_CONTROLLED. */ PLAYER_CONTROLLED(1 << 24), /** The NOT_SELECTABLE. */ NOT_SELECTABLE(1 << 25), /** The SKINNABLE. */ SKINNABLE(1 << 26), /** The MOUNT. */ MOUNT(1 << 27), /** The UNK_28. */ UNK_28(1 << 28), /** The UNK_29. */ UNK_29(1 << 29), /** The SHEATHE. */ SHEATHE(1 << 30), /** The UNK_31. */ UNK_31(1 << 31); /** The value. */ private int value; /** * Instantiates a new unit flags. * * @param flag * the flag */ UnitFlags(final int flag) { this.value = flag; } /** * Gets the value. * * @return the value */ public int getValue() { return this.value; } }
gpl-2.0
Ankama/harvey
src/com/ankamagames/dofus/harvey/generic/sets/interfaces/IGenericInterval.java
583
/** * */ package com.ankamagames.dofus.harvey.generic.sets.interfaces; import com.ankamagames.dofus.harvey.engine.common.sets.interfaces.IInterval; import org.eclipse.jdt.annotation.NonNullByDefault; /** * @author sgros * */ @NonNullByDefault public interface IGenericInterval<Data> extends IInterval<IGenericBound<Data>, ISortedGenericSet<Data>, ISimpleSortedGenericSet<Data>, IElementarySortedGenericSet<Data>, IGenericInterval<Data>>, ISortedGenericSet<Data>, IElementarySortedGenericSet<Data> { @Override IGenericInterval<Data> getSimpleSet(); }
gpl-2.0
anarion1191/MUI
src/mui/menu/item/Item.java
1164
package mui.menu.item; /** * Abstract class representing a menu item. * Menu items should extend the {@code Item} * class and override it's {@code action()} * method. * * @author Kian Nejadfard * */ public abstract class Item { /** * A {@code String} representing the menu item's * name that is to be printed in the menu list for * users to see. */ protected String name; /** * Abstract function that must be overridden by * subclasses to perform necessary actions for * a certain menu item. * * @return True if the menu loop must continue after * the function has finished execution. False if * the menu loop must end. */ public abstract boolean action(); /** * Get the name field of a menu item. * * @return {@code String} The name of the menu item */ final public String getName() { return name; } /** * Set the name field of a menu item. * * @param newName A {@code String} object containing the name */ final public void setName(String newName) { name = newName; } }
gpl-2.0
luisdecker/Formais-15.2
src/formais152/Modelo/Expressao.java
8824
package formais152.Modelo; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Set; import formais152.Modelo.Excecoes.ParenteseMismatchException; public class Expressao { public String expressao; public Expressao(String exp) { expressao = exp.trim(); } private String getInicial(Automato a) throws Exception { Set<Estado> set = a.getEstados(); for (Estado e : set) { String nome = e.getNome(); if (e.isInicial()) { return e.getNome(); } } throw new Exception("sem estado inicial"); } private String createNewEnd(Automato a) throws Exception { Set<Estado> set = a.getEstados(); ArrayList<String> names = new ArrayList<String>(); Set<Estado> finais = new HashSet<Estado>(); for (Estado e : set) { if (e.isTerminal()) { finais.add(e); } names.add(e.getNome()); } if (set.isEmpty()) { throw new Exception("Sem estado final"); } String nomeFinal = "SS0"; int i = 0; while (names.contains(nomeFinal)) { i++; nomeFinal = "SS"; nomeFinal += i; } a.addEstado(nomeFinal); a.addEstadoFinal(nomeFinal); for (Estado e : finais) { a.addTransicao(e.getNome(), "&", nomeFinal); } return nomeFinal; } public Automato obterAutomato() throws Exception { String express = expressao; Automato auto = new Automato(); String result = ""; for (int i = 0; i < express.length(); i++) { char at = express.charAt(i); if (at != ' ') { result += at; } } return obterAutomato(result, '\0'); } private boolean isMod(char a) { return (a == '+' || a == '*' || a == '?'); } private Automato obterAutomato(String express, char mod) { int vn = 0; Automato auto = new Automato(); boolean start = false; auto.addEstado("S0"); try { auto.setEstadoInicial("S0"); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String lastEstate = "S0"; String estadoInicial = "S0"; String estadoFinal = lastEstate; for (int i = 0; i < express.length(); i++) { char at = express.charAt(i); if (at == '(') { /** * se encontrar um come�o de uma expressao ele procura o final * dela e chama o metodo recursivamente concatenando o resultado * com esse e passando adiante * * tambem � verificado se tem um modificador depois */ int end = -1; /** * verifica��o de multiplos parenteses * */ for (int j = i + 1, cont = 1; j < express.length(); j++) { char c = express.charAt(j); if (c == ')') { cont--; } if (cont == 0) { end = j; break; } if (c == '(') { cont++; } } if (end == -1) { throw new ParenteseMismatchException("Parentese n�o encontrado"); } String sub = express.substring(i + 1, end); char submod = '\0'; if (end < express.length() - 1) { submod = express.charAt(end + 1); } if (isMod(submod)) { end++; } else { submod = 0; } auto.addEstadoFinal(lastEstate); try { auto = auto.concatenacao(obterAutomato(sub, submod)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } end++; if (end < express.length()) { if (express.charAt(end) == '|') { sub = express.substring(end + 1); return auto.uniao(obterAutomato(sub, '\0')); } else { sub = express.substring(end); try { return auto.concatenacao(obterAutomato(sub, '\0')); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (isMod(mod)) { try { estadoInicial = getInicial(auto); estadoFinal = createNewEnd(auto); } catch (Exception e) { System.out.println(e.getMessage()); } break; } else { return auto; } } if (at == '|') { /** * Caso encontrado um operador | � feito uniao do automato atual * com o restante da expressao */ String sub = express.substring(i + 1); auto.addEstadoFinal(lastEstate); auto = auto.uniao(obterAutomato(sub, (char) 0)); if (isMod(mod)) { try { estadoInicial = getInicial(auto); estadoFinal = createNewEnd(auto); } catch (Exception e) { System.out.println(e.getMessage()); } break; } else { return auto; } } /** * Verifica-se se ha algum modificador como *,+,? depois do simbolo * atual */ char cmod = '\0'; if (i < express.length() - 1) { cmod = express.charAt(i + 1); } if (isMod(cmod)) { i++; } String estadoAtual = lastEstate; vn++; String estadoTransicao = "S" + vn; auto.addEstado(estadoTransicao); String producao = ""; producao += at; lastEstate = estadoTransicao; try { switch (cmod) { case '+': { auto.addTransicao(estadoAtual, producao, estadoTransicao); auto.addTransicao(estadoTransicao, producao, estadoTransicao); break; } case '*': { auto.addTransicao(estadoAtual, "&", estadoTransicao); auto.addTransicao(estadoTransicao, producao, estadoTransicao); break; } case '?': { auto.addTransicao(estadoAtual, producao, estadoTransicao); auto.addTransicao(estadoAtual, "&", estadoTransicao); break; } default: { auto.addTransicao(estadoAtual, producao, estadoTransicao); break; } } } catch (Exception e) { e.printStackTrace(); } estadoFinal = lastEstate; } /** * Agora lidando com algum modificador que influencia em toda expressao * */ try { auto.addEstadoFinal(lastEstate); switch (mod) { case '+': { auto.addTransicao(estadoFinal, "&", estadoInicial); break; } case '*': { auto.addTransicao(estadoInicial, "&", estadoFinal); auto.addTransicao(estadoFinal, "&", estadoInicial); break; } case '?': { auto.addTransicao(estadoInicial, "&", estadoFinal); break; } default: { break; } } } catch (Exception e) { e.printStackTrace(); } return auto; } }
gpl-2.0
tectronics/xenogeddon
src/com/jmex/model/collada/schema/light_spot_cutoffType.java
8279
/** * light_spot_cutoffType.java * * This file was generated by XMLSpy 2007sp2 Enterprise Edition. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the XMLSpy Documentation for further details. * http://www.altova.com/xmlspy */ package com.jmex.model.collada.schema; import com.jmex.xml.types.SchemaNCName; public class light_spot_cutoffType extends com.jmex.xml.xml.Node { public light_spot_cutoffType(light_spot_cutoffType node) { super(node); } public light_spot_cutoffType(org.w3c.dom.Node node) { super(node); } public light_spot_cutoffType(org.w3c.dom.Document doc) { super(doc); } public light_spot_cutoffType(com.jmex.xml.xml.Document doc, String namespaceURI, String prefix, String name) { super(doc, namespaceURI, prefix, name); } public void adjustPrefix() { for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "value" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "value", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "param" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "param", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "index" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "index", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } } public void setXsiType() { org.w3c.dom.Element el = (org.w3c.dom.Element) domNode; el.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", "light_spot_cutoff"); } public static int getvalue2MinCount() { return 0; } public static int getvalue2MaxCount() { return 1; } public int getvalue2Count() { return getDomChildCount(Attribute, null, "value"); } public boolean hasvalue2() { return hasDomChild(Attribute, null, "value"); } public float2 newvalue2() { return new float2(); } public float2 getvalue2At(int index) throws Exception { return new float2(getDomNodeValue(getDomChildAt(Attribute, null, "value", index))); } public org.w3c.dom.Node getStartingvalue2Cursor() throws Exception { return getDomFirstChild(Attribute, null, "value" ); } public org.w3c.dom.Node getAdvancedvalue2Cursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "value", curNode ); } public float2 getvalue2ValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new float2(getDomNodeValue(curNode)); } public float2 getvalue2() throws Exception { return getvalue2At(0); } public void removevalue2At(int index) { removeDomChildAt(Attribute, null, "value", index); } public void removevalue2() { removevalue2At(0); } public org.w3c.dom.Node addvalue2(float2 value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "value", value.toString()); } public org.w3c.dom.Node addvalue2(String value) throws Exception { return addvalue2(new float2(value)); } public void insertvalue2At(float2 value, int index) { insertDomChildAt(Attribute, null, "value", index, value.toString()); } public void insertvalue2At(String value, int index) throws Exception { insertvalue2At(new float2(value), index); } public void replacevalue2At(float2 value, int index) { replaceDomChildAt(Attribute, null, "value", index, value.toString()); } public void replacevalue2At(String value, int index) throws Exception { replacevalue2At(new float2(value), index); } public static int getparamMinCount() { return 0; } public static int getparamMaxCount() { return 1; } public int getparamCount() { return getDomChildCount(Attribute, null, "param"); } public boolean hasparam() { return hasDomChild(Attribute, null, "param"); } public SchemaNCName newparam() { return new SchemaNCName(); } public SchemaNCName getparamAt(int index) throws Exception { return new SchemaNCName(getDomNodeValue(getDomChildAt(Attribute, null, "param", index))); } public org.w3c.dom.Node getStartingparamCursor() throws Exception { return getDomFirstChild(Attribute, null, "param" ); } public org.w3c.dom.Node getAdvancedparamCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "param", curNode ); } public SchemaNCName getparamValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new SchemaNCName(getDomNodeValue(curNode)); } public SchemaNCName getparam() throws Exception { return getparamAt(0); } public void removeparamAt(int index) { removeDomChildAt(Attribute, null, "param", index); } public void removeparam() { removeparamAt(0); } public org.w3c.dom.Node addparam(SchemaNCName value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "param", value.toString()); } public org.w3c.dom.Node addparam(String value) throws Exception { return addparam(new SchemaNCName(value)); } public void insertparamAt(SchemaNCName value, int index) { insertDomChildAt(Attribute, null, "param", index, value.toString()); } public void insertparamAt(String value, int index) throws Exception { insertparamAt(new SchemaNCName(value), index); } public void replaceparamAt(SchemaNCName value, int index) { replaceDomChildAt(Attribute, null, "param", index, value.toString()); } public void replaceparamAt(String value, int index) throws Exception { replaceparamAt(new SchemaNCName(value), index); } public static int getindexMinCount() { return 1; } public static int getindexMaxCount() { return 1; } public int getindexCount() { return getDomChildCount(Attribute, null, "index"); } public boolean hasindex() { return hasDomChild(Attribute, null, "index"); } public GL_MAX_LIGHTS_index newindex() { return new GL_MAX_LIGHTS_index(); } public GL_MAX_LIGHTS_index getindexAt(int index) throws Exception { return new GL_MAX_LIGHTS_index(getDomNodeValue(getDomChildAt(Attribute, null, "index", index))); } public org.w3c.dom.Node getStartingindexCursor() throws Exception { return getDomFirstChild(Attribute, null, "index" ); } public org.w3c.dom.Node getAdvancedindexCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "index", curNode ); } public GL_MAX_LIGHTS_index getindexValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new GL_MAX_LIGHTS_index(getDomNodeValue(curNode)); } public GL_MAX_LIGHTS_index getindex() throws Exception { return getindexAt(0); } public void removeindexAt(int index) { removeDomChildAt(Attribute, null, "index", index); } public void removeindex() { removeindexAt(0); } public org.w3c.dom.Node addindex(GL_MAX_LIGHTS_index value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "index", value.toString()); } public org.w3c.dom.Node addindex(String value) throws Exception { return addindex(new GL_MAX_LIGHTS_index(value)); } public void insertindexAt(GL_MAX_LIGHTS_index value, int index) { insertDomChildAt(Attribute, null, "index", index, value.toString()); } public void insertindexAt(String value, int index) throws Exception { insertindexAt(new GL_MAX_LIGHTS_index(value), index); } public void replaceindexAt(GL_MAX_LIGHTS_index value, int index) { replaceDomChildAt(Attribute, null, "index", index, value.toString()); } public void replaceindexAt(String value, int index) throws Exception { replaceindexAt(new GL_MAX_LIGHTS_index(value), index); } }
gpl-2.0
specify/specify6
src/edu/ku/brc/stats/StatGroupTableFromCustomQuery.java
8332
/* Copyright (C) 2022, Specify Collections Consortium * * Specify Collections Consortium, Biodiversity Institute, University of Kansas, * 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package edu.ku.brc.stats; import static edu.ku.brc.ui.UIHelper.createLabel; import static edu.ku.brc.ui.UIRegistry.getResourceString; import java.awt.BorderLayout; import java.awt.Dimension; import java.util.List; import javax.swing.JLabel; import com.jgoodies.forms.layout.CellConstraints; import edu.ku.brc.dbsupport.CustomQueryFactory; import edu.ku.brc.dbsupport.CustomQueryIFace; import edu.ku.brc.dbsupport.CustomQueryListener; import edu.ku.brc.ui.CommandAction; /** * * Class to create an entire group from a single query. * Groups are typically made up of individual StatItems where each statistic requires it's * own query and the usually just the right hand side comes from the query, although the * description part can come from the query also. With this class you describe whcih columns in the resultset * that the description and value (left and right) comes from. * @code_status Unknown (auto-generated) ** * @author rods * */ @SuppressWarnings("serial") public class StatGroupTableFromCustomQuery extends StatGroupTable implements CustomQueryListener { // Static Data Members //private static final Logger log = Logger.getLogger(StatGroupTableFromCustomQuery.class); // Data Members protected String noResultsMsg; protected boolean hasData = false; /** * Constructor that describes where we get everything from. * @param name the name or title * @param sql the SQL statement to be executed * @param descCol the column where the description comes form * @param valCol the column where the value comes from * @param noResultsMsg the message to display when there is no results */ public StatGroupTableFromCustomQuery(final String name, final String[] columnNames, final String sql, final String noResultsMsg) { super(name, columnNames); this.noResultsMsg = noResultsMsg; StatDataItem statItem = new StatDataItem("RetrievingData", null , false); model.addDataItem(statItem); CustomQueryIFace customQuery = CustomQueryFactory.getInstance().getQuery(sql); customQuery.execute(this); } /** * Constructor that describes where we get everything from. * @param name the name or title * @param jpaQuery the JPA CustomQuery Processor * @param descCol the column where the description comes form * @param valCol the column where the value comes from * @param useSeparator use non-border separator titles * @param noResultsMsg the message to display when there is no results */ public StatGroupTableFromCustomQuery(final String name, final String[] columnNames, final CustomQueryIFace jpaQuery, boolean useSeparator, final String noResultsMsg) { super(name, columnNames); this.noResultsMsg = noResultsMsg; StatDataItem statItem = new StatDataItem("RetrievingData", null , false); model.addDataItem(statItem); jpaQuery.execute(this); } /** * Constructor that describes where we get everything from. * @param name the name or title * @param sql the SQL statement to be executed * @param descCol the column where the description comes form * @param valCol the column where the value comes from * @param useSeparator use non-border separator titles * @param noResultsMsg the message to display when there is no results */ public StatGroupTableFromCustomQuery(final String name, final String[] columnNames, final String sql, boolean useSeparator, final String noResultsMsg) { super(name, columnNames, useSeparator, 100); // this is an arbitrary number only to tell it to make scrollbars this.noResultsMsg = noResultsMsg; StatDataItem statItem = new StatDataItem("RetrievingData", null , false); model.addDataItem(statItem); CustomQueryIFace customQuery = CustomQueryFactory.getInstance().getQuery(sql); customQuery.execute(this); } /** * Sets info needed to send commands * @param commandAction the command to be cloned and sent * @param colId the column of the id which is used to build the link */ public void setCommandAction(final CommandAction commandAction, final int colId) { this.cmdAction = commandAction; this.colId = colId; } /** * Requests that all the data be reloaded (Not implemented yet) */ public void reloadData() { } /* (non-Javadoc) * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { // this is needed to the box isn't huge before it has data return hasData ? super.getPreferredSize() : new Dimension(100,100); } /** * Removes the table and adds the None Available message * @param msg the message to be displayed */ protected void addNoneAvailableMsg(final String msg) { JLabel label = createLabel(noResultsMsg != null ? noResultsMsg : getResourceString("NoneAvail")); if (useSeparator) { builder.getPanel().remove(scrollPane != null ? scrollPane : table); builder.add(label, new CellConstraints().xy(1,2)); } else { remove(scrollPane != null ? scrollPane : table); add(label, BorderLayout.CENTER); } } //----------------------------------------------------- //-- CustomQueryListener //----------------------------------------------------- /* (non-Javadoc) * @see edu.ku.brc.dbsupport.CustomQueryListener#exectionDone(edu.ku.brc.dbsupport.CustomQuery) */ public synchronized void exectionDone(final CustomQueryIFace customQuery) { model.clear(); hasData = true; List<?> results = customQuery.getDataObjects(); if (results != null && results.size() > 0) { for (int i=0;i<results.size();i++) { String desc = results.get(i++).toString(); Object val = results.get(i++); Object colIdObj = results.get(i); StatDataItem statItem = new StatDataItem(desc, createCommandAction(colIdObj), false); statItem.setValue(val); model.addDataItem(statItem); } results.clear(); } else { addNoneAvailableMsg(noResultsMsg); } model.fireNewData(); } /* (non-Javadoc) * @see edu.ku.brc.dbsupport.CustomQueryListener#executionError(edu.ku.brc.dbsupport.CustomQuery) */ public synchronized void executionError(CustomQueryIFace customQuery) { addNoneAvailableMsg(getResourceString("GetStatsError")); } }
gpl-2.0
teamfx/openjfx-8u-dev-rt
modules/web/src/main/java/com/sun/javafx/webkit/PasteboardImpl.java
3529
/* * Copyright (c) 2011, 2018, 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 com.sun.javafx.webkit; import com.sun.webkit.Pasteboard; import com.sun.webkit.graphics.WCImage; import com.sun.webkit.graphics.WCImageFrame; import java.io.File; import java.io.IOException; import java.util.Arrays; import javafx.scene.image.Image; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javax.imageio.ImageIO; final class PasteboardImpl implements Pasteboard { private final Clipboard clipboard = Clipboard.getSystemClipboard(); PasteboardImpl() { } @Override public String getPlainText() { return clipboard.getString(); } @Override public String getHtml() { return clipboard.getHtml(); } @Override public void writePlainText(String text) { ClipboardContent content = new ClipboardContent(); content.putString(text); clipboard.setContent(content); } @Override public void writeSelection(boolean canSmartCopyOrDelete, String text, String html) { ClipboardContent content = new ClipboardContent(); content.putString(text); content.putHtml(html); clipboard.setContent(content); } @Override public void writeImage(WCImageFrame frame) { final WCImage img = frame.getFrame(); final Image fxImage = img != null && !img.isNull() ? Image.impl_fromPlatformImage(img.getPlatformImage()) : null; if (fxImage != null) { ClipboardContent content = new ClipboardContent(); content.putImage(fxImage); String fileExtension = img.getFileExtension(); try { File imageDump = File.createTempFile("jfx", "." + fileExtension); imageDump.deleteOnExit(); ImageIO.write(img.toBufferedImage(), fileExtension, imageDump); content.putFiles(Arrays.asList(imageDump)); } catch (IOException | SecurityException e) { // Nothing specific to be done as of now } clipboard.setContent(content); } } @Override public void writeUrl(String url, String markup) { ClipboardContent content = new ClipboardContent(); content.putString(url); content.putHtml(markup); content.putUrl(url); clipboard.setContent(content); } }
gpl-2.0
phasenraum2010/javaee7-petclinic
src/main/java/org/woehlke/javaee7/petclinic/web/PetTypeController.java
2558
package org.woehlke.javaee7.petclinic.web; import org.richfaces.component.SortOrder; import org.woehlke.javaee7.petclinic.dao.PetTypeDao; import org.woehlke.javaee7.petclinic.entities.PetType; import javax.ejb.EJB; import javax.ejb.EJBTransactionRolledbackException; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import java.io.Serializable; import java.util.List; /** * Created with IntelliJ IDEA. * User: Fert * Date: 06.01.14 * Time: 11:49 * To change this template use File | Settings | File Templates. */ @ManagedBean @SessionScoped public class PetTypeController implements Serializable { @EJB private PetTypeDao petTypeDao; private PetType petType; private SortOrder petTypeSortOrder = SortOrder.ascending; private int scrollerPage; public SortOrder getPetTypeSortOrder() { return petTypeSortOrder; } public void setPetTypeSortOrder(SortOrder petTypeSortOrder) { this.petTypeSortOrder = petTypeSortOrder; } public void switchSortOrder(){ if(petTypeSortOrder == SortOrder.ascending){ petTypeSortOrder = SortOrder.descending; } else { petTypeSortOrder = SortOrder.ascending; } } public PetType getPetType() { return petType; } public void setPetType(PetType petType) { this.petType = petType; } public List<PetType> getPetTypes(){ return petTypeDao.getAll(); } public String getNewPetTypeForm(){ petType = new PetType(); return "petTypeNew.jsf"; } public String saveNewPetType(){ petTypeDao.addNew(this.petType); return "petTypeList.jsf"; } public String getEditForm(long id){ this.petType = petTypeDao.findById(id); return "petTypeEdit.jsf"; } public String saveEditedPetType(){ petTypeDao.update(this.petType); return "petTypeList.jsf"; } public String delete(long id){ try { petTypeDao.delete(id); } catch (EJBTransactionRolledbackException e) { FacesContext ctx = FacesContext.getCurrentInstance(); ctx.addMessage(null, new FacesMessage("cannot delete, object still in use")); } return "petTypeList.jsf"; } public void setScrollerPage(int scrollerPage) { this.scrollerPage = scrollerPage; } public int getScrollerPage() { return scrollerPage; } }
gpl-2.0
dsx-tech/e-voting
sources/e-voting/common/src/main/java/uk/dsxt/voting/common/iso20022/jaxb/SecurityIdentification14.java
3428
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.02.25 at 03:58:45 PM GMT+03:00 // package uk.dsxt.voting.common.iso20022.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; /** * <p>Java class for SecurityIdentification14 complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SecurityIdentification14"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="ISIN" type="{}ISINIdentifier" minOccurs="0"/> * &lt;element name="OthrId" type="{}OtherIdentification1" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="Desc" type="{}Max140Text" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SecurityIdentification14", propOrder = { "isin", "othrId", "desc" }) public class SecurityIdentification14 { @XmlElement(name = "ISIN") protected String isin; @XmlElement(name = "OthrId") protected List<OtherIdentification1> othrId; @XmlElement(name = "Desc") protected String desc; /** * Gets the value of the isin property. * * @return * possible object is * {@link String } * */ public String getISIN() { return isin; } /** * Sets the value of the isin property. * * @param value * allowed object is * {@link String } * */ public void setISIN(String value) { this.isin = value; } /** * Gets the value of the othrId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the othrId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOthrId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OtherIdentification1 } * * */ public List<OtherIdentification1> getOthrId() { if (othrId == null) { othrId = new ArrayList<OtherIdentification1>(); } return this.othrId; } /** * Gets the value of the desc property. * * @return * possible object is * {@link String } * */ public String getDesc() { return desc; } /** * Sets the value of the desc property. * * @param value * allowed object is * {@link String } * */ public void setDesc(String value) { this.desc = value; } }
gpl-2.0
abhijit5893/QUBA
Learn(QUBA)/languages/dsl.Learnings.one/source_gen/dsl/Learnings/one/editor/EmptyLineSETQP_Editor.java
845
package dsl.Learnings.one.editor; /*Generated by MPS */ import jetbrains.mps.nodeEditor.DefaultNodeEditor; import jetbrains.mps.openapi.editor.cells.EditorCell; import jetbrains.mps.openapi.editor.EditorContext; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.nodeEditor.cells.EditorCell_Constant; public class EmptyLineSETQP_Editor extends DefaultNodeEditor { public EditorCell createEditorCell(EditorContext editorContext, SNode node) { return this.createConstant_fmc9km_a(editorContext, node); } private EditorCell createConstant_fmc9km_a(EditorContext editorContext, SNode node) { EditorCell_Constant editorCell = new EditorCell_Constant(editorContext, node, ""); editorCell.setCellId("Constant_fmc9km_a"); editorCell.setBig(true); editorCell.setDefaultText(""); return editorCell; } }
gpl-2.0
sismics/docs
docs-core/src/main/java/com/sismics/docs/core/service/FileService.java
2484
package com.sismics.docs.core.service; import com.google.common.util.concurrent.AbstractScheduledService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; /** * File service. * * @author bgamard */ public class FileService extends AbstractScheduledService { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(FileService.class); /** * Phantom references queue. */ private final ReferenceQueue<Path> referenceQueue = new ReferenceQueue<>(); private final Set<TemporaryPathReference> referenceSet = new HashSet<>(); public FileService() { } @Override protected void startUp() { log.info("File service starting up"); } @Override protected void shutDown() { log.info("File service shutting down"); } @Override protected void runOneIteration() { try { deleteTemporaryFiles(); } catch (Throwable e) { log.error("Exception during file service iteration", e); } } /** * Delete unreferenced temporary files. */ private void deleteTemporaryFiles() throws Exception { TemporaryPathReference ref; while ((ref = (TemporaryPathReference) referenceQueue.poll()) != null) { Files.delete(Paths.get(ref.path)); referenceSet.remove(ref); } } @Override protected Scheduler scheduler() { return Scheduler.newFixedDelaySchedule(0, 5, TimeUnit.SECONDS); } /** * Create a temporary file. * * @return New temporary file */ public Path createTemporaryFile() throws IOException { Path path = Files.createTempFile("sismics_docs", null); referenceSet.add(new TemporaryPathReference(path, referenceQueue)); return path; } /** * Phantom reference to a temporary file. * * @author bgamard */ static class TemporaryPathReference extends PhantomReference<Path> { String path; TemporaryPathReference(Path referent, ReferenceQueue<? super Path> q) { super(referent, q); path = referent.toAbsolutePath().toString(); } } }
gpl-2.0
ahuarte47/SOS
core/api/src/main/java/org/n52/sos/service/profile/DefaultProfile.java
6085
/** * Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * 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. */ package org.n52.sos.service.profile; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.n52.sos.ogc.om.OmConstants; /** * @since 4.0.0 * */ public class DefaultProfile implements Profile { private static final String DEFAULT_IDENTIFIER = "SOS_20_PROFILE"; private static final String DEFAULT_OBSERVATION_RESPONSE_FORMAT = OmConstants.NS_OM_2; private static final String DEFAULT_ENCODING_NAMESPACE_FOR_FEATUTREOFINTEREST_SOS_20 = ""; private static final boolean DEFAULT_ENCODE_FEATUREOFINTEREST_IN_OBSERVATION = true; private static final boolean DEFAULT_SHOW_METADATA_OF_EMPTY_OBSERVATIONS = false; private static final boolean DEFAULT_ALLOW_SUBSETTING_FOR_OM_20 = false; private static final boolean DEAFULT_MERGE_VALUES = false; private static final boolean DEAFULT_RETURN_LATEST_VALUE_IF_TEMPORAL_FILTER_IS_MISSING_IN_GETOBSERVATION = false; private static final boolean DEFAULT_LIST_FEATURE_OF_INSEREST_IN_OFFERINGS = true; private static final boolean DEFAULT_ENCODE_CHILD_PROCEDURE_DESCRIPTION = false; private static final boolean DEFAULT_SHOW_FULL_OPERATIONS_METADATA = false; private static final boolean DEFAULT_SHOW_FULL_OPERATIONS_METADATA_FOR_OBSERVATIONS = false; private static final String DAFUALT_RESPONSE_NODATA_PLACEHOLDER = "noData"; private Set<String> defaultNoDataPlaceholder = new HashSet<String>(); private Map<String, Boolean> encodeProcedureInObservation = new HashMap<String, Boolean>(0); private Map<String, String> defaultObservationTypesForEncoding = new HashMap<String, String>(0); private String definition; @Override public String getIdentifier() { return DEFAULT_IDENTIFIER; } @Override public boolean isActiveProfile() { return true; } @Override public void setActiveProfile(boolean active) { // nothing to do; } @Override public String getObservationResponseFormat() { return DEFAULT_OBSERVATION_RESPONSE_FORMAT; } @Override public boolean isEncodeFeatureOfInterestInObservations() { return DEFAULT_ENCODE_FEATUREOFINTEREST_IN_OBSERVATION; } @Override public String getEncodingNamespaceForFeatureOfInterest() { return DEFAULT_ENCODING_NAMESPACE_FOR_FEATUTREOFINTEREST_SOS_20; } @Override public boolean isShowMetadataOfEmptyObservations() { return DEFAULT_SHOW_METADATA_OF_EMPTY_OBSERVATIONS; } @Override public boolean isAllowSubsettingForSOS20OM20() { return DEFAULT_ALLOW_SUBSETTING_FOR_OM_20; } @Override public boolean isMergeValues() { return DEAFULT_MERGE_VALUES; } @Override public boolean isSetEncodeFeatureOfInterestNamespace() { return false; } @Override public boolean isEncodeProcedureInObservation() { return encodeProcedureInObservation != null && !encodeProcedureInObservation.isEmpty(); } @Override public boolean isEncodeProcedureInObservation(String namespace) { if (encodeProcedureInObservation.get(namespace) != null) { return encodeProcedureInObservation.get(namespace); } return false; } @Override public boolean isReturnLatestValueIfTemporalFilterIsMissingInGetObservation() { return DEAFULT_RETURN_LATEST_VALUE_IF_TEMPORAL_FILTER_IS_MISSING_IN_GETOBSERVATION; } @Override public Map<String, String> getDefaultObservationTypesForEncoding() { return defaultObservationTypesForEncoding; } @Override public boolean isListFeatureOfInterestsInOfferings() { return DEFAULT_LIST_FEATURE_OF_INSEREST_IN_OFFERINGS; } @Override public boolean isEncodeChildProcedureDescriptions() { return DEFAULT_ENCODE_CHILD_PROCEDURE_DESCRIPTION; } @Override public boolean isShowFullOperationsMetadata() { return DEFAULT_SHOW_FULL_OPERATIONS_METADATA; } @Override public boolean isShowFullOperationsMetadataForObservations() { return DEFAULT_SHOW_FULL_OPERATIONS_METADATA_FOR_OBSERVATIONS; } @Override public String getResponseNoDataPlaceholder() { return DAFUALT_RESPONSE_NODATA_PLACEHOLDER; } @Override public Set<String> getNoDataPlaceholder() { return defaultNoDataPlaceholder; } @Override public boolean isSetNoDataPlaceholder() { return defaultNoDataPlaceholder != null && !defaultNoDataPlaceholder.isEmpty(); } @Override public void setDefinition(String definition) { this.definition = definition; } @Override public String getDefinition() { return definition; } }
gpl-2.0
fantesy84/java-code-tutorials
java-code-tutorials-spring/java-code-tutorials-spring-submit-token/src/main/java/net/fantesy84/sys/web/constants/WebConstants.java
474
/** * Project java-code-tutorials-spring-commit-token * File: WebConstants.java * CreateTime: 2015年12月23日 * Creator: junjie.ge * copy right ©2015 葛俊杰 */ package net.fantesy84.sys.web.constants; /** * TypeName: WebConstants * <P>TODO * * <P>CreateTime: 2015年12月23日 * <P>UpdateTime: * @author junjie.ge * */ public interface WebConstants { String REQUEST_SUBMIT_TOKEN = "submit_token"; String RESET_SUBMIT_TOKEN = "reset_submit_token"; }
gpl-2.0
ONSemiconductor/MatrixRTSPTests
Android/app/src/main/java/com/onsemi/matrix/rtspclient/commands/OptionsCommand.java
2858
/* ** Copyright 2015 ON Semiconductor Inc. ** ** ** This file is part of MatrixRTSPTests. ** ** MatrixRTSPTests 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. ** ** MatrixRTSPTests 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 MatrixRTSPTests. If not, see <http://www.gnu.org/licenses/>. */ package com.onsemi.matrix.rtspclient.commands; import com.onsemi.matrix.rtspclient.TestResult; import com.onsemi.matrix.rtspclient.MessageLogger; import com.onsemi.matrix.rtspclient.RTSPCommand; import com.onsemi.matrix.rtspclient.TestLogger; import com.onsemi.matrix.rtspclient.Settings; import java.net.URI; import br.com.voicetechnology.rtspclient.MissingHeaderException; import br.com.voicetechnology.rtspclient.RTSPClient; import br.com.voicetechnology.rtspclient.concepts.Header; import br.com.voicetechnology.rtspclient.concepts.Request; import br.com.voicetechnology.rtspclient.concepts.Response; public class OptionsCommand extends RTSPCommand { private Settings settings = null; public OptionsCommand(RTSPClient client, MessageLogger mLogger, TestLogger tLogger, Settings settings) { super(client, mLogger, tLogger); this.settings = settings; } @Override public void execute() { super.execute(); try { this.client.options("*", new URI(this.settings.getCameraURL())); } catch (Exception e) { e.printStackTrace(); } } @Override public TestResult verify(Request request, Response response) { TestResult testResult = super.verify(request, response); if (!testResult.isPassed()) { return testResult; } String methodName = request.getMethod().toString(); try { Header publicHeader = response.getHeader("Public"); String publicHeaderValue = publicHeader.getRawValue(); for (Request.Method method : Request.Method.values()) { if(!publicHeaderValue.contains(method.toString())) { return new TestResult(methodName, false, String.format( "'Public' header doesn't contain %s command", method)); } } } catch (MissingHeaderException e) { return new TestResult(methodName, false, "Response doesn't contain 'Public' header"); } return new TestResult(methodName, true); } }
gpl-2.0
TheApacheCats/quercus
com/caucho/quercus/lib/curl/PostBody.java
1760
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Nam Nguyen */ package com.caucho.quercus.lib.curl; import java.io.IOException; import java.io.OutputStream; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.Value; abstract public class PostBody { static PostBody create(Env env, Value body) { PostBody post; if (body == null) return null; else if (body.isArray()) post = new MultipartBody(); else post = new UrlEncodedBody(); if (post.init(env, body)) return post; else return null; } abstract protected boolean init(Env env, Value body); abstract public long getContentLength(); abstract public String getContentType(); abstract public void writeTo(Env env, OutputStream os) throws IOException; }
gpl-2.0
dionesf/Algoritmos---Design-Patterns
Observer_Jornal/Observer/src/observer/Singleton.java
643
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package observer; /** * * @author dionesfischer */ public class Singleton { private String nome; private static Singleton unico; public static Singleton getSingleton() { if (unico == null) { unico = new Singleton(); } return unico; } private Singleton() { System.out.println("Criando um novo Singleton"); } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } }
gpl-2.0
christianchristensen/resin
modules/resin/src/com/caucho/db/sql/IsNullExpr.java
2765
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * Free SoftwareFoundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.db.sql; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Logger; class IsNullExpr extends Expr { private Expr _expr; private boolean _isNot; IsNullExpr(Expr expr, boolean isNot) { _expr = expr; _isNot = isNot; } /** * Binds the expression to the actual tables. */ public Expr bind(Query query) throws SQLException { _expr = _expr.bind(query); return this; } /** * Returns the type of the expression. */ public Class getType() { return boolean.class; } /** * Returns the cost based on the given FromList. */ public long subCost(ArrayList<FromItem> fromList) { return _expr.subCost(fromList); } /** * Evaluates the expression as a boolean * * @param rows the current tuple being evaluated * * @return the boolean value */ public int evalBoolean(QueryContext context) throws SQLException { if (_isNot) return ! _expr.isNull(context) ? TRUE : FALSE; else return _expr.isNull(context) ? TRUE : FALSE; } /** * Evaluates the expression as a string. * * @param rows the current tuple being evaluated * * @return the string value */ public String evalString(QueryContext context) throws SQLException { return (evalBoolean(context) == TRUE) ? "1" : "0"; } /** * Evaluates aggregate functions during the group phase. * * @param state the current database tuple */ public void evalGroup(QueryContext context) throws SQLException { _expr.evalGroup(context); } public String toString() { if (_isNot) return _expr + " IS NOT NULL"; else return _expr + " IS NULL"; } }
gpl-2.0
surevine/openfire-bespoke
src/java/org/jivesoftware/util/IntEnum.java
3143
/** * $RCSfile$ * $Revision: 11608 $ * $Date: 2010-02-07 21:03:12 +0000 (Sun, 07 Feb 2010) $ * * Copyright (C) 2004-2008 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.util; import java.util.*; /** * <p>A type safe enumeration object that is keyed by an Int * value for switch statements and storage in DBs.</p> * <p/> * <p>Used for indicating distinct states in a generic manner * where each enum should have an associated int value. The * given int should be unique for each enum value as hashCode * and equals depends solely on the int value given. Most * child classes should extend IntEnum and create static instances.</p> * * @author Iain Shigeoka */ public class IntEnum extends Enum { private int value; protected static Hashtable enumTypes = new Hashtable(); protected IntEnum(String name, int val) { super(name); this.value = val; } /** * Returns the int value associated with the enum. * * @return the int value of the enum. */ public int getValue() { return value; } @Override public boolean equals(Object object) { if (this == object) { return true; } else if ((this.getClass().isInstance(object)) && value == (((IntEnum)object).value)) { return true; } else { return false; } } /** * <p>Checks in an enum for use in the getEnumFromInt() method.</p> * * @param enumeration The enum to be registered */ protected static void register(IntEnum enumeration) { Map enums = (Map)enumTypes.get(enumeration.getClass()); if (enums == null) { enums = new HashMap<Integer,Object>(); enumTypes.put(enumeration.getClass(), enums); } enums.put(enumeration.getValue(), enumeration); } /** * <p>Obtain the enum associated with the given value.</p> * <p>Values must be registered earlier using the register() method.</p> * * @param value the value to lookup the enum for * @return The associated enum or null if no matching enum exists */ protected static IntEnum getEnumFromInt(Class enumClass, int value) { Map enums = (Map)enumTypes.get(enumClass); if (enums != null) { return (IntEnum)enums.get(value); } return null; } @Override public int hashCode() { return value; } @Override public String toString() { return Integer.toString(value) + " " + super.toString(); } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/commons-digester/org/apache/commons/digester/annotations/providers/SetRootRuleProvider.java
1752
/* $Id: SetRootRuleProvider.java 992060 2010-09-02 19:09:47Z simonetripodi $ * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.digester.annotations.providers; import java.lang.reflect.Method; import org.apache.commons.digester.SetRootRule; import org.apache.commons.digester.annotations.AnnotationRuleProvider; import org.apache.commons.digester.annotations.rules.SetRoot; /** * Provides instances of {@link SetRootRule}. * * @since 2.1 */ public final class SetRootRuleProvider implements AnnotationRuleProvider<SetRoot, Method, SetRootRule>{ private String methodName; private String paramType; /** * {@inheritDoc} */ public void init(SetRoot annotation, Method element) { this.methodName = element.getName(); this.paramType = element.getParameterTypes()[0].getName(); } /** * {@inheritDoc} */ public SetRootRule get() { return new SetRootRule(this.methodName, this.paramType); } }
gpl-2.0
CharlesZ-Chen/checker-framework
checker/jtreg/stubs/issue1496/Main.java
289
/* * @test * @summary Test case for Issue 1496 https://github.com/typetools/checker-framework/issues/1496 * @compile -XDrawDiagnostics -processor org.checkerframework.checker.nullness.NullnessChecker -Astubs=ClassAnnotation.astub Main.java */ package issue1496; public class Main {}
gpl-2.0
TheTypoMaster/Scaper
openjdk/langtools/src/share/classes/com/sun/mirror/type/MirroredTypeException.java
3152
/* * Copyright 2004 Sun Microsystems, Inc. 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.mirror.type; import java.lang.annotation.Annotation; import com.sun.mirror.declaration.Declaration; /** * Thrown when an application attempts to access the {@link Class} object * corresponding to a {@link TypeMirror}. * * @deprecated All components of this API have been superseded by the * standardized annotation processing API. The replacement for the * functionality of this exception is {@link * javax.lang.model.type.MirroredTypeException}. * * @see MirroredTypesException * @see Declaration#getAnnotation(Class) */ @Deprecated @SuppressWarnings("deprecation") public class MirroredTypeException extends RuntimeException { private static final long serialVersionUID = 1; private transient TypeMirror type; // cannot be serialized private String name; // type's qualified "name" /** * Constructs a new MirroredTypeException for the specified type. * * @param type the type being accessed */ public MirroredTypeException(TypeMirror type) { super("Attempt to access Class object for TypeMirror " + type); this.type = type; name = type.toString(); } /** * Returns the type mirror corresponding to the type being accessed. * The type mirror may be unavailable if this exception has been * serialized and then read back in. * * @return the type mirror, or <tt>null</tt> if unavailable */ public TypeMirror getTypeMirror() { return type; } /** * Returns the fully qualified name of the type being accessed. * More precisely, returns the canonical name of a class, * interface, array, or primitive, and returns <tt>"void"</tt> for * the pseudo-type representing the type of <tt>void</tt>. * * @return the fully qualified name of the type being accessed */ public String getQualifiedName() { return name; } }
gpl-2.0
JMaNGOS/JMaNGOS
Realm/src/main/java/org/jmangos/realm/network/packet/wow/server/SMSG_POWER_UPDATE.java
1786
/******************************************************************************* * Copyright (C) 2013 JMaNGOS <http://jmangos.org/> * * 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, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.jmangos.realm.network.packet.wow.server; import org.jmangos.commons.enums.Powers; import org.jmangos.commons.model.player.Player; import org.jmangos.realm.network.packet.wow.AbstractWoWServerPacket; /** * The Class SMSG_POWER_UPDATE. */ public class SMSG_POWER_UPDATE extends AbstractWoWServerPacket { private Player player; private Powers power; private int value; public SMSG_POWER_UPDATE() {} public SMSG_POWER_UPDATE(final Player player, final Powers power, final int newValue) { this.player = player; this.power = power; this.value = newValue; } /** * (non-Javadoc) * * @see org.wowemu.common.network.model.SendablePacket#writeImpl() */ @Override public void writeImpl() { writeB(this.player.getCharacterData().getPacketGuid()); writeC(this.power.ordinal() - 1); writeD(this.value); } }
gpl-2.0
michellemulkey/aTunes
src/net/sourceforge/atunes/gui/views/panels/PlayListControlsPanel.java
8857
/** * aTunes 1.6.0 * Copyright (C) 2006-2007 Alex Aranda (fleax) alex.aranda@gmail.com * * http://www.atunes.org * http://sourceforge.net/projects/atunes * * 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. */ package net.sourceforge.atunes.gui.views.panels; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JSeparator; import net.sourceforge.atunes.gui.images.ImageLoader; import net.sourceforge.atunes.gui.views.controls.CustomButton; import net.sourceforge.atunes.gui.views.controls.PopUpButton; import net.sourceforge.atunes.utils.language.LanguageTool; public class PlayListControlsPanel extends JPanel { private static final long serialVersionUID = -1966827894270243002L; private PopUpButton sortPopup; private JCheckBoxMenuItem showTrack; private JCheckBoxMenuItem showArtist; private JCheckBoxMenuItem showAlbum; private JCheckBoxMenuItem showGenre; private JCheckBoxMenuItem showDuration; private JMenuItem sortByTrack; private JMenuItem sortByTitle; private JMenuItem sortByArtist; private JMenuItem sortByAlbum; private JMenuItem sortByGenre; private JButton savePlaylistButton; private JButton loadPlaylistButton; private JButton artistButton; private JButton albumButton; private JButton topButton; private JButton upButton; private JButton deleteButton; private JButton downButton; private JButton bottomButton; private JButton infoButton; private JButton clearButton; private PopUpButton favoritePopup; private JMenuItem favoriteSong; private JMenuItem favoriteAlbum; private JMenuItem favoriteArtist; public PlayListControlsPanel() { super(new GridBagLayout()); addContent(); } private void addContent() { sortPopup = new PopUpButton(LanguageTool.getString("OPTIONS"), PopUpButton.TOP_RIGHT); showTrack = new JCheckBoxMenuItem(LanguageTool.getString("SHOW_TRACKS")); showArtist = new JCheckBoxMenuItem(LanguageTool.getString("SHOW_ARTISTS")); showAlbum = new JCheckBoxMenuItem(LanguageTool.getString("SHOW_ALBUMS")); showGenre = new JCheckBoxMenuItem(LanguageTool.getString("SHOW_GENRE")); showDuration = new JCheckBoxMenuItem(LanguageTool.getString("SHOW_DURATION")); sortByTrack = new JMenuItem(LanguageTool.getString("SORT_BY_TRACK_NUMBER")); sortByTitle = new JMenuItem(LanguageTool.getString("SORT_BY_TITLE")); sortByArtist = new JMenuItem(LanguageTool.getString("SORT_BY_ARTIST")); sortByAlbum = new JMenuItem(LanguageTool.getString("SORT_BY_ALBUM")); sortByGenre = new JMenuItem(LanguageTool.getString("SORT_BY_GENRE")); sortPopup.add(showTrack); sortPopup.add(showArtist); sortPopup.add(showAlbum); sortPopup.add(showGenre); sortPopup.add(showDuration); sortPopup.add(new JSeparator()); sortPopup.add(sortByTrack); sortPopup.add(sortByTitle); sortPopup.add(sortByArtist); sortPopup.add(sortByAlbum); sortPopup.add(sortByGenre); savePlaylistButton = new CustomButton(ImageLoader.SAVE, null); savePlaylistButton.setToolTipText(LanguageTool.getString("SAVE_PLAYLIST_TOOLTIP")); loadPlaylistButton = new CustomButton(ImageLoader.FOLDER, null); loadPlaylistButton.setToolTipText(LanguageTool.getString("LOAD_PLAYLIST_TOOLTIP")); artistButton = new CustomButton(ImageLoader.ARTIST, null); artistButton.setEnabled(false); artistButton.setToolTipText(LanguageTool.getString("ARTIST_BUTTON_TOOLTIP")); albumButton = new CustomButton(ImageLoader.ALBUM, null); albumButton.setEnabled(false); albumButton.setToolTipText(LanguageTool.getString("ALBUM_BUTTON_TOOLTIP")); topButton = new CustomButton(ImageLoader.GO_TOP, null); topButton.setEnabled(false); topButton.setToolTipText(LanguageTool.getString("MOVE_TO_TOP_TOOLTIP")); upButton = new CustomButton(ImageLoader.GO_UP, null); upButton.setEnabled(false); upButton.setToolTipText(LanguageTool.getString("MOVE_UP_TOOLTIP")); deleteButton = new CustomButton(ImageLoader.REMOVE, null); deleteButton.setEnabled(false); deleteButton.setToolTipText(LanguageTool.getString("REMOVE_TOOLTIP")); downButton = new CustomButton(ImageLoader.GO_DOWN, null); downButton.setEnabled(false); downButton.setToolTipText(LanguageTool.getString("MOVE_DOWN_TOOLTIP")); bottomButton = new CustomButton(ImageLoader.GO_BOTTOM, null); bottomButton.setEnabled(false); bottomButton.setToolTipText(LanguageTool.getString("MOVE_BOTTOM_TOOLTIP")); infoButton = new CustomButton(ImageLoader.INFO, null); infoButton.setEnabled(false); infoButton.setToolTipText(LanguageTool.getString("INFO_BUTTON_TOOLTIP")); clearButton = new CustomButton(ImageLoader.CLEAR, null); clearButton.setEnabled(false); clearButton.setToolTipText(LanguageTool.getString("CLEAR_TOOLTIP")); favoritePopup = new PopUpButton(ImageLoader.FAVORITE, PopUpButton.TOP_LEFT); favoritePopup.setEnabled(false); favoritePopup.setToolTipText(LanguageTool.getString("FAVORITE_TOOLTIP")); favoriteSong = new JMenuItem(LanguageTool.getString("SET_FAVORITE_SONG"), ImageLoader.FAVORITE); favoriteAlbum = new JMenuItem(LanguageTool.getString("SET_FAVORITE_ALBUM"), ImageLoader.FAVORITE); favoriteArtist = new JMenuItem(LanguageTool.getString("SET_FAVORITE_ARTIST"), ImageLoader.FAVORITE); favoritePopup.add(favoriteSong); favoritePopup.add(favoriteAlbum); favoritePopup.add(favoriteArtist); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.insets = new Insets(0,0,0,10); add(sortPopup, c); c.gridx = 1; c.gridy = 0; c.insets = new Insets(0,0,0,0); setButton(savePlaylistButton, c); c.gridx = 2; c.gridy = 0; setButton(loadPlaylistButton, c); c.gridx = 3; c.gridy = 0; c.weightx = 1; c.anchor = GridBagConstraints.EAST; setButton(artistButton, c); c.gridx = 4; c.gridy = 0; c.weightx = 0; c.insets = new Insets(0,0,0,10); setButton(albumButton, c); c.gridx = 5; c.gridy = 0; c.insets = new Insets(0,0,0,10); setButton(infoButton, c); c.gridx = 6; c.gridy = 0; c.insets = new Insets(0,0,0,0); setButton(deleteButton, c); c.gridx = 7; c.gridy = 0; setButton(clearButton, c); c.gridx = 8; c.gridy = 0; setButton(topButton, c); c.gridx = 9; c.gridy = 0; setButton(upButton, c); c.gridx = 10; c.gridy = 0; setButton(downButton, c); c.gridx = 11; c.gridy = 0; c.weighty = 1; c.insets = new Insets(0,0,0,10); setButton(bottomButton, c); c.gridx = 12; c.gridy = 0; c.insets = new Insets(0,0,0,0); setButton(favoritePopup, c); } private void setButton(JButton button, GridBagConstraints c) { button.setPreferredSize(new Dimension(20,20)); add(button, c); } public JButton getBottomButton() { return bottomButton; } public JButton getDeleteButton() { return deleteButton; } public JButton getDownButton() { return downButton; } public JButton getInfoButton() { return infoButton; } public JButton getTopButton() { return topButton; } public JButton getUpButton() { return upButton; } public JButton getClearButton() { return clearButton; } public JButton getLoadPlaylistButton() { return loadPlaylistButton; } public JButton getSavePlaylistButton() { return savePlaylistButton; } public JMenuItem getFavoriteAlbum() { return favoriteAlbum; } public JMenuItem getFavoriteArtist() { return favoriteArtist; } public JMenuItem getFavoriteSong() { return favoriteSong; } public PopUpButton getFavoritePopup() { return favoritePopup; } public JMenuItem getSortByTitle() { return sortByTitle; } public JMenuItem getSortByAlbum() { return sortByAlbum; } public JMenuItem getSortByArtist() { return sortByArtist; } public JCheckBoxMenuItem getShowTrack() { return showTrack; } public JCheckBoxMenuItem getShowArtist() { return showArtist; } public JCheckBoxMenuItem getShowAlbum() { return showAlbum; } public JButton getAlbumButton() { return albumButton; } public JButton getArtistButton() { return artistButton; } public JMenuItem getSortByTrack() { return sortByTrack; } public JMenuItem getSortByGenre() { return sortByGenre; } public JCheckBoxMenuItem getShowGenre() { return showGenre; } public JCheckBoxMenuItem getShowDuration() { return showDuration; } }
gpl-2.0
FRC-1902/BCNLib
src/main/java/com/explodingbacon/bcnlib/networking/NetJoystick.java
1421
package com.explodingbacon.bcnlib.networking; import com.explodingbacon.bcnlib.controllers.JoystickInterface; import com.explodingbacon.bcnlib.framework.AbstractOI; /** * A class for reading from NetJoysticks. * * @author Dominic Canora * @version 2016.1.0 */ public class NetJoystick implements JoystickInterface { protected double xVal, yVal, zVal; protected String key; /** * Default Constructor * * @param key A unique key to refer to this NetJoystick */ public NetJoystick(String key) { xVal = 0; yVal = 0; zVal = 0; this.key = key; AbstractOI.addNetJoystick(this); } /** * Refresh the value of this NetJoystick. Automatically handled by AbstractOI. */ public void refresh() { double x = AbstractOI.table.getNumber(key + "_x", 0d); double y = AbstractOI.table.getNumber(key + "_y", 0d); double z = AbstractOI.table.getNumber(key + "_z", 0d); x = Math.max(-1, x); y = Math.max(-1, y); z = Math.max(-1, z); x = Math.min(x, 1); y = Math.min(y, 1); z = Math.min(z, 1); xVal = x; yVal = y; zVal = z; } @Override public double getX() { return xVal; } @Override public double getY() { return yVal; } @Override public double getZ() { return zVal; } }
gpl-2.0
diamonddevgroup/CodenameOne
Ports/JavaSE/src/com/codename1/impl/javase/cef/RequestHandler.java
7355
// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. package com.codename1.impl.javase.cef; import com.codename1.ui.events.BrowserNavigationCallback; import java.awt.Container; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; import org.cef.callback.CefAuthCallback; import org.cef.callback.CefRequestCallback; import org.cef.handler.CefLoadHandler.ErrorCode; import org.cef.handler.CefRequestHandler; import org.cef.handler.CefResourceHandler; import org.cef.handler.CefResourceRequestHandler; import org.cef.handler.CefResourceRequestHandlerAdapter; import org.cef.misc.BoolRef; import org.cef.network.CefPostData; import org.cef.network.CefPostDataElement; import org.cef.network.CefRequest; import java.awt.Frame; import java.util.HashMap; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; //import tests.detailed.dialog.CertErrorDialog; //import tests.detailed.dialog.PasswordDialog; public class RequestHandler extends CefResourceRequestHandlerAdapter implements CefRequestHandler { private final Container owner_; //private BrowserComponent browserComponent_; private BrowserNavigationCallback navigationCallback_; public RequestHandler(Container owner, BrowserNavigationCallback navigationCallback) { owner_ = owner; this.navigationCallback_ = navigationCallback; } @Override public boolean onBeforeBrowse(CefBrowser browser, CefFrame frame, CefRequest request, boolean user_gesture, boolean is_redirect) { if (navigationCallback_ != null) { boolean res = navigationCallback_.shouldNavigate(request.getURL()); if (!res) { return res; } } CefPostData postData = request.getPostData(); if (postData != null) { Vector<CefPostDataElement> elements = new Vector<CefPostDataElement>(); postData.getElements(elements); for (CefPostDataElement el : elements) { int numBytes = el.getBytesCount(); if (numBytes <= 0) continue; byte[] readBytes = new byte[numBytes]; if (el.getBytes(numBytes, readBytes) <= 0) continue; String readString = new String(readBytes); if (readString.indexOf("ignore") > -1) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(owner_, "The request was rejected because you've entered \"ignore\" into the form."); } }); return true; } } } return false; } @Override public CefResourceRequestHandler getResourceRequestHandler(CefBrowser browser, CefFrame frame, CefRequest request, boolean isNavigation, boolean isDownload, String requestInitiator, BoolRef disableDefaultHandling) { return this; } @Override public boolean onBeforeResourceLoad(CefBrowser browser, CefFrame frame, CefRequest request) { // If you send a HTTP-POST request to http://www.google.com/ // google rejects your request because they don't allow HTTP-POST. // // This test extracts the value of the test form. // (see "Show Form" entry within BrowserMenuBar) // and sends its value as HTTP-GET request to Google. if (request.getMethod().equalsIgnoreCase("POST") && request.getURL().equals("http://www.google.com/")) { String forwardTo = "http://www.google.com/#q="; CefPostData postData = request.getPostData(); boolean sendAsGet = false; if (postData != null) { Vector<CefPostDataElement> elements = new Vector<CefPostDataElement>(); postData.getElements(elements); for (CefPostDataElement el : elements) { int numBytes = el.getBytesCount(); if (numBytes <= 0) continue; byte[] readBytes = new byte[numBytes]; if (el.getBytes(numBytes, readBytes) <= 0) continue; String readString = new String(readBytes).trim(); String[] stringPairs = readString.split("&"); for (String s : stringPairs) { int startPos = s.indexOf('='); if (s.startsWith("searchFor")) forwardTo += s.substring(startPos + 1); else if (s.startsWith("sendAsGet")) { sendAsGet = true; } } } if (sendAsGet) postData.removeElements(); } if (sendAsGet) { request.setFlags(0); request.setMethod("GET"); request.setURL(forwardTo); request.setFirstPartyForCookies(forwardTo); HashMap<String, String> headerMap = new HashMap<>(); request.getHeaderMap(headerMap); headerMap.remove("Content-Type"); headerMap.remove("Origin"); request.setHeaderMap(headerMap); } } return false; } @Override public CefResourceHandler getResourceHandler( CefBrowser browser, CefFrame frame, CefRequest request) { // the non existing domain "foo.bar" is handled by the ResourceHandler implementation // E.g. if you try to load the URL http://www.foo.bar, you'll be forwarded // to the ResourceHandler class. if (request.getURL().startsWith("https://cn1app/")) { return new ResourceHandler(); } if (request.getURL().endsWith("seterror.test/")) { return new ResourceSetErrorHandler(); } return null; } @Override public boolean getAuthCredentials(CefBrowser browser, String origin_url, boolean isProxy, String host, int port, String realm, String scheme, CefAuthCallback callback) { //SwingUtilities.invokeLater(new PasswordDialog(owner_, callback)); return true; } @Override public boolean onQuotaRequest( CefBrowser browser, String origin_url, long new_size, CefRequestCallback callback) { return false; } @Override public boolean onCertificateError(CefBrowser browser, ErrorCode cert_error, String request_url, CefRequestCallback callback) { //SwingUtilities.invokeLater(new CertErrorDialog(owner_, cert_error, request_url, callback)); return true; } @Override public void onPluginCrashed(CefBrowser browser, String pluginPath) { System.out.println("Plugin " + pluginPath + "CRASHED"); } @Override public void onRenderProcessTerminated(CefBrowser browser, TerminationStatus status) { System.out.println("render process terminated: " + status); } }
gpl-2.0
GITNE/icedtea-web
tests/reproducers/simple/ParametrizedJarUrl/testcases/ParametrizedJarUrlTests.java
9985
/* SimpleTest1Test.java Copyright (C) 2011 Red Hat, Inc. This file is part of IcedTea. IcedTea 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, version 2. IcedTea 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 IcedTea; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import net.sourceforge.jnlp.ProcessResult; import net.sourceforge.jnlp.ServerAccess; import net.sourceforge.jnlp.ServerLauncher; import net.sourceforge.jnlp.annotations.Bug; import net.sourceforge.jnlp.annotations.TestInBrowsers; import net.sourceforge.jnlp.browsertesting.BrowserTest; import net.sourceforge.jnlp.browsertesting.Browsers; import org.junit.Assert; import org.junit.Test; public class ParametrizedJarUrlTests extends BrowserTest{ private final List<String> l = Collections.unmodifiableList(Arrays.asList(new String[]{"-Xtrustall"})); @Test @TestInBrowsers(testIn = Browsers.one) @Bug(id = "PR905") public void parametrizedAppletTestSignedBrowserTest_hardcodedDifferentCodeBase() throws Exception { ServerLauncher server2 = ServerAccess.getIndependentInstance(); String originalResourceName = "ParametrizedJarUrlSigned.html"; String newResourceName = "ParametrizedJarUrlSigned_COPY2.html"; createCodeBase(originalResourceName, newResourceName, server2.getUrl("")); //set codebase to second server ProcessResult pr = server.executeBrowser(newResourceName); server2.stop(); evaluateSignedApplet(pr); } @Test @TestInBrowsers(testIn = Browsers.one) @Bug(id = "PR905") public void parametrizedAppletTestSignedBrowserTest_hardcodedCodeBase() throws Exception { String originalResourceName = "ParametrizedJarUrlSigned.html"; String newResourceName = "ParametrizedJarUrlSigned_COPY1.html"; createCodeBase(originalResourceName, newResourceName, server.getUrl("")); ProcessResult pr = server.executeBrowser(newResourceName); evaluateSignedApplet(pr); } private void createCodeBase(String originalResourceName, String newResourceName, URL codebase) throws MalformedURLException, IOException { String originalContent = ServerAccess.getContentOfStream(new FileInputStream(new File(server.getDir(), originalResourceName))); String nwContent = originalContent.replaceAll("codebase=\".\"", "codebase=\"" + codebase + "\""); ServerAccess.saveFile(nwContent, new File(server.getDir(), newResourceName)); } @Test @TestInBrowsers(testIn = Browsers.one) @Bug(id = "PR905") public void parametrizedAppletTestSignedBrowserTest() throws Exception { ProcessResult pr = server.executeBrowser("/ParametrizedJarUrlSigned.html"); evaluateSignedApplet(pr); } @Test @TestInBrowsers(testIn=Browsers.one) public void parametrizedAppletInBrowserWithParamTest() throws Exception { ProcessResult pr = server.executeBrowser("/ParametrizedJarUrl.html?giveMeMore?orNot"); evaluateApplet(pr); } @Test public void parametrizedAppletJavawsTest() throws Exception { ProcessResult pr = server.executeJavawsHeadless(null, "/ParametrizedJarAppletUrl2.jnlp"); evaluateApplet(pr); } @Test public void parametrizedAppletJavawsTest2() throws Exception { ProcessResult pr = server.executeJavawsHeadless(null, "/ParametrizedJarAppletUrl2.jnlp?test=123456"); evaluateApplet(pr); } @Test public void parametrizedAppletJavawsTest3() throws Exception { ProcessResult pr = server.executeJavawsHeadless(null, "/ParametrizedJarAppletUrl.jnlp"); evaluateApplet(pr); } @Test public void parametrizedAppletJavawsTestSignedTest() throws Exception { ProcessResult pr = server.executeJavawsHeadless(l, "/ParametrizedJarAppletUrlSigned2.jnlp"); evaluateSignedApplet(pr); } @Test public void parametrizedAppletJavawsTestSigned2Test() throws Exception { ProcessResult pr = server.executeJavawsHeadless(l, "/ParametrizedJarAppletUrlSigned2.jnlp?test=123456"); evaluateSignedApplet(pr); } @Test public void parametrizedAppletJavawsTestSignedTest4() throws Exception { ProcessResult pr = server.executeJavawsHeadless(l, "/ParametrizedJarAppletUrlSigned.jnlp"); evaluateSignedApplet(pr); } private void evaluateSignedApplet(ProcessResult pr) { String s3 = "AppletTestSigned was initialised"; Assert.assertTrue("AppletTestSigned stdout should contain " + s3 + " but didn't", pr.stdout.contains(s3)); String s0 = "AppletTestSigned was started"; Assert.assertTrue("AppletTestSigned stdout should contain " + s0 + " but didn't", pr.stdout.contains(s0)); String s1 = "value1"; Assert.assertTrue("AppletTestSigned stdout should contain " + s1 + " but didn't", pr.stdout.contains(s1)); String s2 = "value2"; Assert.assertTrue("AppletTestSigned stdout should contain " + s2 + " but didn't", pr.stdout.contains(s2)); String s7 = "AppletTestSigned killing himself after 2000 ms of life"; Assert.assertTrue("AppletTestSigned stdout should contain " + s7 + " but didn't", pr.stdout.contains(s7)); } @Test public void testParametrizedJarUrlSigned1() throws Exception { ProcessResult pr = server.executeJavawsHeadless(l, "/ParametrizedJarUrlSigned1.jnlp"); String s = "Good simple javaws exapmle"; Assert.assertTrue("ParametrizedJarUrlSigned1 stdout should contain " + s + " but didn't", pr.stdout.contains(s)); } @Test public void testParametrizedJarUrlSigned2() throws Exception { ProcessResult pr = server.executeJavawsHeadless(l, "/ParametrizedJarUrlSigned2.jnlp"); String s = "Good simple javaws exapmle"; Assert.assertTrue("ParametrizedJarUrlSigned2 stdout should contain " + s + " but didn't", pr.stdout.contains(s)); } @Test public void testParametrizedJarUrlSigned3() throws Exception { ProcessResult pr = server.executeJavawsHeadless(l, "/ParametrizedJarUrlSigned2.jnlp?test=123456"); String s = "Good simple javaws exapmle"; Assert.assertTrue("ParametrizedJarUrlSigned2 stdout should contain " + s + " but didn't", pr.stdout.contains(s)); } @Test public void testParametrizedJarUrl1() throws Exception { ProcessResult pr = server.executeJavawsHeadless(null, "/ParametrizedJarUrl1.jnlp"); String s = "Good simple javaws exapmle"; Assert.assertTrue("ParametrizedJarUrl1 stdout should contain " + s + " but didn't", pr.stdout.contains(s)); } @Test public void testParametrizedJarUrl2() throws Exception { ProcessResult pr = server.executeJavawsHeadless(null, "/ParametrizedJarUrl2.jnlp"); String s = "Good simple javaws exapmle"; Assert.assertTrue("ParametrizedJarUrl2 stdout should contain " + s + " but didn't", pr.stdout.contains(s)); } @Test public void testParametrizedJarUrl3() throws Exception { ProcessResult pr = server.executeJavawsHeadless(null, "/ParametrizedJarUrl2.jnlp?test=123456"); String s = "Good simple javaws exapmle"; Assert.assertTrue("ParametrizedJarUrl2 stdout should contain " + s + " but didn't", pr.stdout.contains(s)); ; } private void evaluateApplet(ProcessResult pr) { String s3 = "applet was initialised"; Assert.assertTrue("AppletTest stdout should contain " + s3 + " but didn't", pr.stdout.contains(s3)); String s0 = "applet was started"; Assert.assertTrue("AppletTest stdout should contain " + s0 + " but didn't", pr.stdout.contains(s0)); String s1 = "value1"; Assert.assertTrue("AppletTest stdout should contain " + s1 + " but didn't", pr.stdout.contains(s1)); String s2 = "value2"; Assert.assertTrue("AppletTest stdout should contain " + s2 + " but didn't", pr.stdout.contains(s2)); String s7 = "Aplet killing himself after 2000 ms of life"; Assert.assertTrue("AppletTest stdout should contain " + s7 + " but didn't", pr.stdout.contains(s7)); } @Test @TestInBrowsers(testIn=Browsers.one) public void parametrizedAppletInBrowserTest() throws Exception { ProcessResult pr = server.executeBrowser("/ParametrizedJarUrl.html"); pr.process.destroy(); evaluateApplet(pr); } }
gpl-2.0
bertrama/resin
modules/resin/src/com/caucho/server/session/SessionManager.java
48325
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.server.session; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import com.caucho.cloud.network.ClusterServer; import com.caucho.cloud.topology.CloudServer; import com.caucho.config.ConfigException; import com.caucho.config.Configurable; import com.caucho.config.types.Period; import com.caucho.distcache.AbstractCache; import com.caucho.distcache.ByteStreamCache; import com.caucho.distcache.ClusterCache; import com.caucho.distcache.ExtCacheEntry; import com.caucho.distcache.ResinCacheBuilder.Scope; import com.caucho.env.meter.AverageSensor; import com.caucho.env.meter.MeterService; import com.caucho.hessian.io.HessianDebugInputStream; import com.caucho.hessian.io.SerializerFactory; import com.caucho.json.JsonOutput; import com.caucho.management.server.SessionManagerMXBean; import com.caucho.security.Authenticator; import com.caucho.server.cluster.ServletService; import com.caucho.server.distcache.CacheBacking; import com.caucho.server.distcache.CacheImpl; import com.caucho.server.distcache.PersistentStoreConfig; import com.caucho.server.webapp.WebApp; import com.caucho.util.Alarm; import com.caucho.util.AlarmListener; import com.caucho.util.Crc64; import com.caucho.util.CurrentTime; import com.caucho.util.L10N; import com.caucho.util.LruCache; import com.caucho.util.RandomUtil; import com.caucho.util.WeakAlarm; import com.caucho.vfs.TempOutputStream; // import com.caucho.server.http.ServletServer; // import com.caucho.server.http.VirtualHost; /** * Manages sessions in a web-webApp. */ public final class SessionManager implements SessionCookieConfig, AlarmListener { private static final L10N L = new L10N(SessionManager.class); private static final Logger log = Logger.getLogger(SessionManager.class.getName()); private static final int FALSE = 0; private static final int COOKIE = 1; private static final int TRUE = 2; private static final int UNSET = 0; private static final int SET_TRUE = 1; private static final int SET_FALSE = 2; private static final int SAVE_BEFORE_HEADERS = 0x1; private static final int SAVE_BEFORE_FLUSH = 0x2; private static final int SAVE_AFTER_REQUEST = 0x4; private static final int SAVE_ON_SHUTDOWN = 0x8; private static final int []DECODE; private final WebApp _webApp; private final SessionManagerAdmin _admin; private final ServletService _servletContainer; private final ClusterServer _selfServer; private final int _selfIndex; private CacheImpl _sessionStore; // active sessions private LruCache<String,SessionImpl> _sessions; // iterator to purge sessions (to reduce gc) private Iterator<SessionImpl> _sessionIter; // array list for session timeout private ArrayList<SessionImpl> _sessionList = new ArrayList<SessionImpl>(); // generate cookies private boolean _enableSessionCookies = true; // allow session rewriting private boolean _enableSessionUrls = true; private boolean _isAppendServerIndex = false; private boolean _isTwoDigitSessionIndex = false; // invalidate the session after the listeners have been called private boolean _isInvalidateAfterListener; // maximum number of sessions private int _sessionMax = 8192; // how long a session will be inactive before it times out private long _sessionTimeout = 30 * 60 * 1000; private String _cookieName = "JSESSIONID"; private String _sslCookieName; // Rewriting strings. private String _sessionSuffix = ";jsessionid="; private String _sessionPrefix; // default cookie version private int _cookieVersion; private String _cookieDomain; private String _cookieDomainRegexp; private boolean _isCookieUseContextPath; private String _cookiePath; private long _cookieMaxAge; private int _isCookieHttpOnly; private String _cookieComment; private String _cookiePort; private int _reuseSessionId = COOKIE; private int _cookieLength = 21; private AtomicLong _sessionIdSequence = new AtomicLong(); private HashSet<SessionTrackingMode> _trackingModes; //Servlet 3.0 plain | ssl session tracking cookies become secure when set to true private boolean _isSecure; // persistence configuration private int _sessionSaveMode = SAVE_AFTER_REQUEST; private boolean _isPersistenceEnabled = false; private boolean _isSaveTriplicate = true; private boolean _isSaveBackup = true; private boolean _isDestroyOnLru = true; // If true, serialization errors should not be logged // XXX: changed for JSF private boolean _ignoreSerializationErrors = true; private boolean _isHessianSerialization = false; private SerializerFactory _hessianFactory; private boolean _isSerializeCollectionType = true; // List of the HttpSessionListeners from the configuration file private ArrayList<HttpSessionListener> _listeners; // List of the HttpSessionListeners from the configuration file private ArrayList<HttpSessionActivationListener> _activationListeners; // List of the HttpSessionAttributeListeners from the configuration file private ArrayList<HttpSessionAttributeListener> _attributeListeners; // // Compatibility fields // // private Store _sessionStore; private int _alwaysLoadSession; private int _alwaysSaveSession; private boolean _isClosed; private String _distributionId; private Alarm _alarm; // statistics private volatile long _sessionCreateCount; private volatile long _sessionTimeoutCount; private volatile long _sessionInvalidateCount; private final AverageSensor _sessionSaveSample; private final Charset UTF_8 = Charset.forName("UTF-8"); /** * Creates and initializes a new session manager * * @param webApp the web-webApp webApp */ public SessionManager(WebApp webApp) throws Exception { _webApp = webApp; _servletContainer = webApp.getServer(); if (_servletContainer == null) { throw new IllegalStateException(L.l("Server is not active in this context {0}", Thread.currentThread().getContextClassLoader())); } _selfServer = _servletContainer.getSelfServer(); _selfIndex = _selfServer.getIndex(); // copy defaults from store for backward compat PersistentStoreConfig cfg = _servletContainer.getPersistentStore(); if (cfg != null) { setAlwaysSaveSession(cfg.isAlwaysSave()); _isSaveBackup = cfg.isSaveBackup(); _isSaveTriplicate = cfg.isSaveTriplicate(); } _sessionSuffix = _servletContainer.getSessionURLPrefix(); _sessionPrefix = _servletContainer.getAlternateSessionURLPrefix(); _cookieName = _servletContainer.getSessionCookie(); _sslCookieName = _servletContainer.getSSLSessionCookie(); long initSequence = CurrentTime.getCurrentTime(); if (CurrentTime.isTest()) { initSequence -= initSequence % 1000; } _sessionIdSequence.set(initSequence); /* if (_sslCookieName != null && ! _sslCookieName.equals(_cookieName)) _isSecure = true; */ String hostName = webApp.getHostName(); String contextPath = webApp.getContextPath(); if (hostName == null || hostName.equals("")) hostName = "default"; String name = hostName + contextPath; if (_distributionId == null) _distributionId = name; _alarm = new WeakAlarm(this); _sessionSaveSample = MeterService.createAverageMeter("Resin|Http|Session Save", "Size"); _admin = new SessionManagerAdmin(this); } /** * Returns the admin. */ public SessionManagerMXBean getAdmin() { return _admin; } /** * Returns the session prefix, ie.. ";jsessionid=". */ public String getSessionPrefix() { return _sessionSuffix; } /** * Returns the alternate session prefix, before the URL for wap. */ public String getAlternateSessionPrefix() { return _sessionPrefix; } /** * Returns the cookie version. */ public int getCookieVersion() { return _cookieVersion; } /** * Sets the cookie version. */ public void setCookieVersion(int cookieVersion) { _cookieVersion = cookieVersion; } /** * Sets the cookie ports. */ public void setCookiePort(String port) { _cookiePort = port; } /** * Sets the cookie ports. */ public void setCookieUseContextPath(boolean isCookieUseContextPath) { _isCookieUseContextPath = isCookieUseContextPath; } /** * Gets the cookie ports. */ public String getCookiePort() { return _cookiePort; } /** * Returns the debug log */ public Logger getDebug() { return log; } /** * Returns the SessionManager's webApp */ WebApp getWebApp() { return _webApp; } ClassLoader getClassLoader() { return getWebApp().getClassLoader(); } /** * Returns the SessionManager's authenticator */ Authenticator getAuthenticator() { return _webApp.getAuthenticator(); } /** * Returns the session cache */ ByteStreamCache getCache() { if (_isPersistenceEnabled) { return _sessionStore; } else { return null; } } /** * True if sessions should always be loadd. */ boolean isAlwaysLoadSession() { return _alwaysLoadSession == SET_TRUE; } /** * True if sessions should always be loadd. */ public void setAlwaysLoadSession(boolean load) { _alwaysLoadSession = load ? SET_TRUE : SET_FALSE; } /** * True if sessions should always be saved. */ boolean getAlwaysSaveSession() { return _alwaysSaveSession == SET_TRUE; } /** * True if sessions should always be saved. */ public void setAlwaysSaveSession(boolean save) { _alwaysSaveSession = save ? SET_TRUE : SET_FALSE; } /** * True if sessions should be saved on shutdown. */ public boolean isSaveOnShutdown() { return (_sessionSaveMode & SAVE_ON_SHUTDOWN) != 0; } /** * True if sessions should only be saved on shutdown. */ public boolean isSaveOnlyOnShutdown() { return (_sessionSaveMode & SAVE_ON_SHUTDOWN) == SAVE_ON_SHUTDOWN; } /** * True if sessions should be saved before the HTTP headers. */ public boolean isSaveBeforeHeaders() { return (_sessionSaveMode & SAVE_BEFORE_HEADERS) != 0; } /** * True if sessions should be saved before each flush. */ public boolean isSaveBeforeFlush() { return (_sessionSaveMode & SAVE_BEFORE_FLUSH) != 0; } /** * True if sessions should be saved after the request. */ public boolean isSaveAfterRequest() { return (_sessionSaveMode & SAVE_AFTER_REQUEST) != 0; } /** * Determines how many digits are used to encode the server */ boolean isTwoDigitSessionIndex() { return _isTwoDigitSessionIndex; } /** * Sets the save-mode: before-flush, before-headers, after-request, * on-shutdown */ public void setSaveMode(String mode) throws ConfigException { /* XXX: probably don't want to implement this. if ("before-flush".equals(mode)) { _sessionSaveMode = (SAVE_BEFORE_FLUSH| SAVE_BEFORE_HEADERS| SAVE_AFTER_REQUEST| SAVE_ON_SHUTDOWN); } else */ if ("before-headers".equals(mode)) { _sessionSaveMode = (SAVE_BEFORE_HEADERS); } else if ("after-request".equals(mode)) { _sessionSaveMode = (SAVE_AFTER_REQUEST); } else if ("on-shutdown".equals(mode)) { _sessionSaveMode = (SAVE_ON_SHUTDOWN); } else throw new ConfigException(L.l("'{0}' is an unknown session save-mode. Values are: before-headers, after-request, and on-shutdown.", mode)); } /** * Returns the string value of the save-mode. */ public String getSaveMode() { if (isSaveBeforeFlush()) return "before-flush"; else if (isSaveBeforeHeaders()) return "before-headers"; else if (isSaveAfterRequest()) return "after-request"; else if (isSaveOnShutdown()) return "on-shutdown"; else return "unknown"; } /** * True if sessions should only be saved on shutdown. */ public void setSaveOnlyOnShutdown(boolean save) { log.warning("<save-only-on-shutdown> is deprecated. Use <save-mode>on-shutdown</save-mode> instead"); if (save) _sessionSaveMode = SAVE_ON_SHUTDOWN; } /** * True if sessions should only be saved on shutdown. */ public void setSaveOnShutdown(boolean save) { log.warning("<save-on-shutdown> is deprecated. Use <save-only-on-shutdown> instead"); setSaveOnlyOnShutdown(save); } /** * Sets the serialization type. */ public void setSerializationType(String type) { if ("hessian".equals(type)) _isHessianSerialization = true; else if ("java".equals(type)) _isHessianSerialization = false; else throw new ConfigException(L.l("'{0}' is an unknown valud for serialization-type. The valid types are 'hessian' and 'java'.", type)); } public void setSerializeCollectionType(boolean isEnable) { _isSerializeCollectionType = isEnable; } /** * Returns true for Hessian serialization. */ public boolean isHessianSerialization() { return _isHessianSerialization; } /** * True if the session should be invalidated after the listener. */ public void setInvalidateAfterListener(boolean inv) { _isInvalidateAfterListener = inv; } /** * True if the session should be invalidated after the listener. */ public boolean isInvalidateAfterListener() { return _isInvalidateAfterListener; } /** * Returns the current number of active sessions. */ public int getActiveSessionCount() { if (_sessions == null) return -1; else return _sessions.size(); } /** * Returns the active sessions. */ public int getSessionActiveCount() { return getActiveSessionCount(); } /** * Returns the created sessions. */ public long getSessionCreateCount() { return _sessionCreateCount; } /** * Returns the timeout sessions. */ public long getSessionTimeoutCount() { return _sessionTimeoutCount; } /** * Returns the invalidate sessions. */ public long getSessionInvalidateCount() { return _sessionInvalidateCount; } /** * Adds a new HttpSessionListener. */ public void addListener(HttpSessionListener listener) { if (_listeners == null) { _listeners = new ArrayList<HttpSessionListener>(); } _listeners.add(listener); } /** * Adds a new HttpSessionListener. */ ArrayList<HttpSessionListener> getListeners() { return _listeners; } /** * Adds a new HttpSessionActivationListener. */ public void addActivationListener(HttpSessionActivationListener listener) { if (_activationListeners == null) _activationListeners = new ArrayList<HttpSessionActivationListener>(); _activationListeners.add(listener); } /** * Returns the activation listeners. */ ArrayList<HttpSessionActivationListener> getActivationListeners() { return _activationListeners; } /** * Adds a new HttpSessionAttributeListener. */ public void addAttributeListener(HttpSessionAttributeListener listener) { if (_attributeListeners == null) _attributeListeners = new ArrayList<HttpSessionAttributeListener>(); _attributeListeners.add(listener); } /** * Gets the HttpSessionAttributeListener. */ ArrayList<HttpSessionAttributeListener> getAttributeListeners() { return _attributeListeners; } /** * True if serialization errors should just fail silently. */ boolean getIgnoreSerializationErrors() { return _ignoreSerializationErrors; } /** * True if serialization errors should just fail silently. */ public void setIgnoreSerializationErrors(boolean ignore) { _ignoreSerializationErrors = ignore; } /** * True if the server should reuse the current session id if the * session doesn't exist. */ public int getReuseSessionId() { return _reuseSessionId; } /** * True if the server should reuse the current session id if the * session doesn't exist. */ public boolean reuseSessionId(boolean fromCookie) { int reuseSessionId = _reuseSessionId; return reuseSessionId == TRUE || fromCookie && reuseSessionId == COOKIE; } /** * True if the server should reuse the current session id if the * session doesn't exist. */ public void setReuseSessionId(String reuse) throws ConfigException { if (reuse == null) _reuseSessionId = COOKIE; else if (reuse.equalsIgnoreCase("true") || reuse.equalsIgnoreCase("yes") || reuse.equalsIgnoreCase("cookie")) _reuseSessionId = COOKIE; else if (reuse.equalsIgnoreCase("false") || reuse.equalsIgnoreCase("no")) _reuseSessionId = FALSE; else if (reuse.equalsIgnoreCase("all")) _reuseSessionId = TRUE; else throw new ConfigException(L.l("'{0}' is an invalid value for reuse-session-id. 'true' or 'false' are the allowed values.", reuse)); } /** * Returns true if the sessions are closed. */ public boolean isClosed() { return _isClosed; } /** * Sets the cluster store. */ public void setUsePersistentStore(boolean enable) throws Exception { _isPersistenceEnabled = enable; } public boolean isUsePersistentStore() { return isPersistenceEnabled(); } public boolean isPersistenceEnabled() { return _isPersistenceEnabled; } public void setDestroyOnLru(boolean isDestroy) { _isDestroyOnLru = isDestroy; } public boolean isDestroyOnLru() { return _isDestroyOnLru || ! isPersistenceEnabled(); } public String getDistributionId() { return _distributionId; } public void setDistributionId(String distributionId) { _distributionId = distributionId; } /** * Returns the default session timeout in milliseconds. */ public long getSessionTimeout() { return _sessionTimeout; } /** * Set the default session timeout in minutes */ public void setSessionTimeout(long timeout) { if (timeout <= 0 || Integer.MAX_VALUE / 2 < timeout) _sessionTimeout = Long.MAX_VALUE / 2; else _sessionTimeout = 60000L * timeout; } /** * Returns the idle time. */ public long getMaxIdleTime() { return _sessionTimeout; } /** * Returns the maximum number of sessions. */ public int getSessionMax() { return _sessionMax; } /** * Returns the maximum number of sessions. */ public void setSessionMax(int max) { if (max < 1) throw new ConfigException(L.l("session-max '{0}' is too small. session-max must be a positive number", max)); _sessionMax = max; } /** * Returns true if sessions use the cookie header. */ public boolean enableSessionCookies() { return _enableSessionCookies; } /** * Returns true if sessions use the cookie header. */ public void setEnableCookies(boolean enableCookies) { _enableSessionCookies = enableCookies; } /** * Returns true if sessions can use the session rewriting. */ public boolean enableSessionUrls() { return _enableSessionUrls; } /** * Returns true if sessions can use the session rewriting. */ public void setEnableUrlRewriting(boolean enableUrls) { _enableSessionUrls = enableUrls; } //SessionCookieConfig implementation (Servlet 3.0) @Override public void setName(String name) { if (! _webApp.isInitializing()) throw new IllegalStateException(); setCookieName(name); } @Override public String getName() { return getCookieName(); } @Override public void setDomain(String domain) { if (! _webApp.isInitializing()) throw new IllegalStateException(); setCookieDomain(domain); } @Override public String getDomain() { return getCookieDomain(); } @Override public void setPath(String path) { if (! _webApp.isInitializing()) throw new IllegalStateException(); _cookiePath = path; } @Override public String getPath() { return _cookiePath; } @Override public void setComment(String comment) { if (! _webApp.isInitializing()) throw new IllegalStateException(); _cookieComment = comment; } @Override public String getComment() { return _cookieComment; } @Override public void setHttpOnly(boolean httpOnly) { if (! _webApp.isInitializing()) throw new IllegalStateException(); setCookieHttpOnly(httpOnly); } @Override public boolean isHttpOnly() { return isCookieHttpOnly(); } @Override public void setSecure(boolean secure) { if (! _webApp.isInitializing()) throw new IllegalStateException(L.l("SessionCookieConfig must be set during initialization")); _isSecure = secure; } @Override public boolean isSecure() { return _isSecure; } @Override public void setMaxAge(int maxAge) { if (! _webApp.isInitializing()) throw new IllegalStateException(); _cookieMaxAge = maxAge * 1000; } @Override public int getMaxAge() { return (int) (_cookieMaxAge / 1000); } @Configurable public SessionCookieConfig createCookieConfig() { return this; } public void setCookieName(String cookieName) { _cookieName = cookieName; } public void setTrackingMode(SessionTrackingMode mode) { if (_trackingModes == null) { _trackingModes = new HashSet<SessionTrackingMode>(); setEnableCookies(false); setEnableUrlRewriting(false); } switch (mode) { case COOKIE: setEnableCookies(true); break; case URL: setEnableUrlRewriting(true); break; } } /** * Returns the default cookie name. */ public String getCookieName() { return _cookieName; } /** * Returns the SSL cookie name. */ public String getSSLCookieName() { if (_sslCookieName != null) return _sslCookieName; else return _cookieName; } /** * Returns the default session cookie domain. */ public String getCookieDomain() { return _cookieDomain; } /** * Sets the default session cookie domain. */ public void setCookieDomain(String domain) { _cookieDomain = domain; } public String getCookieDomainRegexp() { return _cookieDomainRegexp; } public void setCookieDomainRegexp(String regexp) { _cookieDomainRegexp = regexp; } /** * Sets the default session cookie domain. */ public void setCookiePath(String path) { _cookiePath = path; } /** * Returns the max-age of the session cookie. */ public long getCookieMaxAge() { return _cookieMaxAge; } /** * Sets the max-age of the session cookie. */ public void setCookieMaxAge(Period maxAge) { _cookieMaxAge = maxAge.getPeriod(); } /** * Returns the secure of the session cookie. */ public boolean isCookieSecure() { if (_isSecure) return true; else return ! _cookieName.equals(_sslCookieName); } /** * Sets the secure of the session cookie. */ public void setCookieSecure(boolean isSecure) { _isSecure = isSecure; } /** * Returns the http-only of the session cookie. */ public boolean isCookieHttpOnly() { if (_isCookieHttpOnly == SET_TRUE) return true; else if (_isCookieHttpOnly == SET_FALSE) return false; else return getWebApp().getCookieHttpOnly(); } /** * Sets the http-only of the session cookie. */ public void setCookieHttpOnly(boolean httpOnly) { _isCookieHttpOnly = httpOnly ? SET_TRUE : SET_FALSE; } /** * Sets the cookie length */ public void setCookieLength(int cookieLength) { if (cookieLength < 7) cookieLength = 7; _cookieLength = cookieLength; } /** * Returns the cookie length. */ public long getCookieLength() { return _cookieLength; } /** * Sets module session id generation. */ public void setCookieModuloCluster(boolean isModulo) { } /** * Sets module session id generation. */ public void setCookieAppendServerIndex(boolean isAppend) { _isAppendServerIndex = isAppend; } /** * Sets module session id generation. */ public boolean isCookieAppendServerIndex() { return _isAppendServerIndex; } public void init() { if (_sessionSaveMode == SAVE_ON_SHUTDOWN && (_alwaysSaveSession == SET_TRUE || _alwaysLoadSession == SET_TRUE)) throw new ConfigException(L.l("save-mode='on-shutdown' cannot be used with <always-save-session/> or <always-load-session/>")); _sessions = new LruCache<String,SessionImpl>(_sessionMax); _sessionIter = _sessions.values(); if (_isPersistenceEnabled) { AbstractCache cacheBuilder = new ClusterCache(); cacheBuilder.setName("resin:session"); if (_isSaveTriplicate) cacheBuilder.setScopeMode(Scope.CLUSTER); else if (_isSaveBackup) cacheBuilder.setScopeMode(Scope.CLUSTER); else cacheBuilder.setScopeMode(Scope.LOCAL); if (isAlwaysLoadSession()) cacheBuilder.setLocalExpireTimeoutMillis(20); else cacheBuilder.setLocalExpireTimeoutMillis(1000); cacheBuilder.setAccessedExpireTimeoutMillis(_sessionTimeout); cacheBuilder.setLeaseExpireTimeoutMillis(5 * 60 * 1000); // server/0b12 cacheBuilder.setLocalExpireTimeoutMillis(100); PersistentStoreConfig persistConfig = PersistentStoreConfig.getCurrent(); if (persistConfig != null) { CacheBacking<?,?> backing = persistConfig.getBacking(); if (backing != null) { cacheBuilder.setBacking(backing); cacheBuilder.setReadThroughExpireTimeoutMillis(500); } } _sessionStore = cacheBuilder.createIfAbsent(); } if (_cookiePath != null) { } else if (_isCookieUseContextPath) _cookiePath = _webApp.getContextPath(); if (_cookiePath == null || "".equals(_cookiePath)) _cookiePath = "/"; } public void start() throws Exception { _alarm.queue(60000); } /** * Returns the session store. */ public ByteStreamCache getSessionStore() { return _sessionStore; } public SessionSerializer createSessionSerializer(OutputStream os) throws IOException { if (_isHessianSerialization) { if (_hessianFactory == null) _hessianFactory = new SerializerFactory(getClassLoader()); HessianSessionSerializer ser; ser = new HessianSessionSerializer(os, _hessianFactory); ser.setSerializeCollectionType(_isSerializeCollectionType); return ser; } else return new JavaSessionSerializer(os, getClassLoader()); } public SessionDeserializer createSessionDeserializer(InputStream is) throws IOException { if (_isHessianSerialization) return new HessianSessionDeserializer(is, getClassLoader()); else return new JavaSessionDeserializer(is, getClassLoader()); } /** * Returns true if the session exists in this manager. */ public boolean containsSession(String id) { return _sessions.get(id) != null; } /** * Creates a pseudo-random session id. If there's an old id and the * group matches, then use it because different webApps on the * same matchine should use the same cookie. * * @param request current request */ public String createSessionId(HttpServletRequest request) { return createSessionId(request, false); } /** * Creates a pseudo-random session id. If there's an old id and the * group matches, then use it because different webApps on the * same machine should use the same cookie. * * @param request current request */ public String createSessionId(HttpServletRequest request, boolean create) { String id; do { id = createSessionIdImpl(request); } while (create && getSession(id, 0, create, true) != null); if (id == null || id.equals("")) throw new RuntimeException(); return id; } public String createCookieValue() { return createCookieValue(null); } public String createSessionIdImpl(HttpServletRequest request) { // look at caucho.session-server-id for a hint of the owner Object owner = request.getAttribute("caucho.session-server-id"); return createCookieValue(owner); } public boolean isOwner(String id) { return id.startsWith(_selfServer.getServerClusterId()); } protected String createCookieValue(Object owner) { StringBuilder sb = new StringBuilder(); // this section is the host specific session index // the most random bit is the high bit int index = _selfIndex; CloudServer server = _selfServer.getCloudServer(); if (owner == null) { } else if (owner instanceof Number) { index = ((Number) owner).intValue(); int podIndex = _selfServer.getCloudPod().getIndex(); server = _selfServer.getCluster().findServer(podIndex, index); if (server == null) server = _selfServer.getCloudServer(); } else if (owner instanceof String) { server = _selfServer.getCluster().findServer((String) owner); if (server == null) server = _selfServer.getCloudServer(); } index = server.getIndex(); ClusterServer clusterServer = server.getData(ClusterServer.class); clusterServer.generateIdPrefix(sb); // XXX: _cluster.generateBackup(sb, index); int length = _cookieLength; length -= sb.length(); long random = RandomUtil.getRandomLong(); for (int i = 0; i < 11 && length-- > 0; i++) { sb.append(convert(random)); random = random >> 6; } if (length > 0) { long seq = _sessionIdSequence.incrementAndGet(); /* // The QA needs to add a millisecond for each server start so the // clustering test will work, but all the session ids are generated // based on the timestamp. So QA sessions don't have milliseconds if (CurrentTime.isTest()) time -= time % 1000; */ for (int i = 0; i < 7 && length-- > 0; i++) { sb.append(convert(seq)); seq = seq >> 6; } } while (length > 0) { random = RandomUtil.getRandomLong(); for (int i = 0; i < 11 && length-- > 0; i++) { sb.append(convert(random)); random = random >> 6; } } if (_isAppendServerIndex) { sb.append('.'); sb.append((index + 1)); } return sb.toString(); } /** * Finds a session in the session store, creating one if 'create' is true * * @param isCreate if the session doesn't exist, create it * @param request current request * @sessionId a desired sessionId or null * @param now the time in milliseconds * @param fromCookie true if the session id comes from a cookie * * @return the cached session. */ public SessionImpl createSession(boolean isCreate, HttpServletRequest request, String sessionId, long now, boolean fromCookie) { if (_sessions == null) { return null; } SessionImpl session = _sessions.get(sessionId); if (session != null) { if (! session.isValid()) { session = null; } else if (! session.getId().equals(sessionId)) { log.warning("Session creation issue. Old session " + session.getId() + " " + sessionId); session = null; } } boolean isNew = false; if (session == null && sessionId != null && _sessionStore != null) { ExtCacheEntry entry = _sessionStore.getExtCacheEntry(sessionId); if (entry != null && ! entry.isValueNull()) { session = create(sessionId, now, isCreate); isNew = true; } } if (session != null) { synchronized (session) { if (session.isTimeout(now)) { session.invalidateTimeout(); session = null; } else if (session.load(isNew)) { session.addUse(); if (isCreate) { // TCK only set access on create session.setAccess(now); } return session; } else { // if the load failed, then the session died out from underneath if (! isNew) { if (log.isLoggable(Level.FINER)) log.fine(session + " load failed for existing session"); // server/0174 session.reset(0); /* session.setModified(); // Return the existing session for timing reasons, e.g. // if a second request hits before the first has finished saving return session; */ } } } } if (! isCreate) { return null; } if (sessionId == null || sessionId.length() <= 6 || ! reuseSessionId(fromCookie)) { sessionId = createSessionId(request, true); } session = new SessionImpl(this, sessionId, now); // If another thread has created and stored a new session, // putIfNew will return the old session session = _sessions.putIfNew(sessionId, session); if (! sessionId.equals(session.getId())) throw new IllegalStateException(sessionId + " != " + session.getId()); if (! session.addUse()) throw new IllegalStateException(L.l("Can't use session for unknown reason")); _sessionCreateCount++; session.create(now, true); handleCreateListeners(session); return session; } /** * Returns a session from the session store, returning null if there's * no cached session. * * @param key the session id * @param now the time in milliseconds * * @return the cached session. */ public SessionImpl getSession(String key, long now, boolean create, boolean fromCookie) { SessionImpl session; boolean isNew = false; boolean killSession = false; if (_sessions == null) return null; session = _sessions.get(key); if (session != null && ! session.getId().equals(key)) throw new IllegalStateException(key + " != " + session.getId()); if (now <= 0) { // just generating id return session; } if (session != null) { if (! session.addUse()) { session = null; } } if (session == null && _sessionStore != null) { /* if (! _objectManager.isInSessionGroup(key)) return null; */ session = create(key, now, create); if (! session.addUse()) session = null; isNew = true; } if (session == null) { return null; } synchronized (session) { if (isNew) { killSession = ! load(session, now, create); isNew = killSession; } else if (! session.load(isNew)) { // if the load failed, then the session died out from underneath if (log.isLoggable(Level.FINER)) log.fine(session + " load failed for existing session"); session.setModified(); isNew = true; } } if (killSession && (! create || ! reuseSessionId(fromCookie))) { // XXX: session.setClosed(); session.endUse(); _sessions.remove(key); // XXX: // session._isValid = false; return null; } else if (isNew) handleCreateListeners(session); //else //session.setAccess(now); return session; } public SessionImpl getSession(String key) { LruCache<String, SessionImpl> sessions = _sessions; if (sessions != null) { return sessions.get(key); } else { return null; } } /** * Create a new session. * * @param oldId the id passed to the request. Reuse if possible. * @param request - current HttpServletRequest * @param fromCookie */ public SessionImpl createSession(String oldId, long now, HttpServletRequest request, boolean fromCookie) { if (_sessions == null) { log.fine(this + " createSession called when sessionManager closed"); return null; } String id = oldId; if (id == null || id.length() < 4 || ! reuseSessionId(fromCookie)) { // server/0175 // || ! _objectManager.isInSessionGroup(id) id = createSessionId(request, true); } SessionImpl session = create(id, now, true); if (session == null) return null; session.addUse(); _sessionCreateCount++; synchronized (session) { if (_isPersistenceEnabled && id.equals(oldId)) load(session, now, true); else session.create(now, true); } // after load so a reset doesn't clear any setting handleCreateListeners(session); return session; } /** * Creates a session. It's already been established that the * key does not currently have a session. */ private SessionImpl create(String key, long now, boolean isCreate) { SessionImpl session = new SessionImpl(this, key, now); // If another thread has created and stored a new session, // putIfNew will return the old session session = _sessions.putIfNew(key, session); if (! key.equals(session.getId())) throw new IllegalStateException(key + " != " + session.getId()); return session; } /** * Notification from the cluster. */ public void notifyRemove(String id) { SessionImpl session = _sessions.get(id); if (session != null) session.invalidateRemote(); } private void handleCreateListeners(SessionImpl session) { ArrayList<HttpSessionListener> listeners = _listeners; if (listeners != null) { HttpSessionEvent event = new HttpSessionEvent(session); for (int i = 0; i < listeners.size(); i++) { HttpSessionListener listener = listeners.get(i); listener.sessionCreated(event); } } } /** * Loads the session from the backing store. The caller must synchronize * the session. * * @param session the session to load. * @param now current time in milliseconds. */ private boolean load(SessionImpl session, long now, boolean isCreate) { try { // XXX: session.setNeedsLoad(false); /* if (session.getUseCount() > 1) { // if used by more than just us, return true; } else*/ if (now <= 0) { return false; } else if (session.load(true)) { // load for a newly created session session.setAccess(now); return true; } else { session.create(now, isCreate); } } catch (Exception e) { log.log(Level.FINE, e.toString(), e); session.reset(now); } return false; } /** * Adds a session from the cache. */ void addSession(SessionImpl session) { _sessions.put(session.getId(), session); } /** * Removes a session from the cache. */ void removeSession(SessionImpl session) { _sessions.remove(session.getId()); } /** * Adds a new session save event */ void addSessionSaveSample(long size) { _sessionSaveSample.add(size); } /** * Returns a debug string for the session */ public String getSessionSerializationDebug(String id) { ByteStreamCache cache = getCache(); if (cache == null) return null; try { TempOutputStream os = new TempOutputStream(); if (cache.get(id, os)) { InputStream is = os.getInputStream(); StringWriter writer = new StringWriter(); HessianDebugInputStream dis = new HessianDebugInputStream(is, new PrintWriter(writer)); while (dis.read() >= 0) { } return writer.toString(); } os.close(); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); return e.toString(); } return null; } public String getSessionAsJsonString(String id) { SessionImpl session = getSession(id); if (session == null) return null; TempOutputStream buffer = new TempOutputStream(); PrintWriter out = new PrintWriter(new OutputStreamWriter(buffer, UTF_8)); JsonOutput jsonOutput = new JsonOutput(out); try { jsonOutput.writeObject(session, true); jsonOutput.flush(); jsonOutput.close(); out.flush(); return new String(buffer.toByteArray(), UTF_8); } catch (IOException e) { if (log.isLoggable(Level.FINE)) log.log(Level.FINE, L.l("can't serialize session {0} due to {1}", session, e), e); } return null; } public String []sessionIdList() { ArrayList<String> sessionIds = new ArrayList<String>(); synchronized (_sessions) { Iterator<LruCache.Entry<String, SessionImpl>> sessionsIterator = _sessions.iterator(); while (sessionsIterator.hasNext()) { sessionIds.add(sessionsIterator.next().getKey()); } } String []ids= new String[sessionIds.size()]; sessionIds.toArray(ids); return ids; } public String getSessionsAsJsonString() { List<SessionImpl> sessionList; synchronized (_sessions) { sessionList = new ArrayList<SessionImpl>(_sessions.size()); Iterator<LruCache.Entry<String, SessionImpl>> sessionsIterator = _sessions.iterator(); while (sessionsIterator.hasNext()) { sessionList.add(sessionsIterator.next().getValue()); } } SessionImpl []sessions = new SessionImpl[sessionList.size()]; sessionList.toArray(sessions); TempOutputStream buffer = new TempOutputStream(); PrintWriter out = new PrintWriter(new OutputStreamWriter(buffer, UTF_8)); JsonOutput jsonOutput = new JsonOutput(out); try { jsonOutput.writeObject(sessions, true); jsonOutput.flush(); jsonOutput.close(); out.flush(); return new String(buffer.toByteArray(), UTF_8); } catch (IOException e) { if (log.isLoggable(Level.FINE)) log.log(Level.FINE, L.l("can't serialize sessions due to {0}", e), e); } return null; } public long getEstimatedMemorySize() { Iterator<SessionImpl> sessions = _sessions.values(); long l = 0; while (sessions.hasNext()) { l += sessions.next().getLastSaveLength(); } return l; } /** * Timeout for reaping old sessions * * @return number of live sessions for stats */ @Override public void handleAlarm(Alarm alarm) { try { _sessionList.clear(); int liveSessions = 0; if (_isClosed) return; long now = CurrentTime.getCurrentTime(); synchronized (_sessions) { _sessionIter = _sessions.values(_sessionIter); while (_sessionIter.hasNext()) { SessionImpl session = _sessionIter.next(); if (session.isTimeout(now)) _sessionList.add(session); else liveSessions++; } } _sessionTimeoutCount += _sessionList.size(); for (int i = 0; i < _sessionList.size(); i++) { SessionImpl session = _sessionList.get(i); try { _sessions.remove(session.getId()); session.timeout(); } catch (Throwable e) { log.log(Level.FINE, e.toString(), e); } } } finally { if (! _isClosed) _alarm.queue(60000); } } /** * Cleans up the sessions when the WebApp shuts down gracefully. */ public void close() { synchronized (this) { if (_isClosed) return; _isClosed = true; } if (_sessions == null) return; Alarm alarm = _alarm; _alarm = null; if (alarm != null) alarm.dequeue(); ArrayList<SessionImpl> list = new ArrayList<SessionImpl>(); // XXX: messy way of dealing with saveOnlyOnShutdown synchronized (_sessions) { _sessionIter = _sessions.values(_sessionIter); while (_sessionIter.hasNext()) { SessionImpl session = _sessionIter.next(); if (session.isValid()) list.add(session); } // XXX: if cleared here, will remove the session // _sessions.clear(); } boolean isError = false; for (int i = list.size() - 1; i >= 0; i--) { SessionImpl session = list.get(i); if (! session.isValid()) continue; if (log.isLoggable(Level.FINE)) log.fine("close session " + session.getId()); try { session.saveOnShutdown(); } catch (Exception e) { if (! isError) log.log(Level.WARNING, "Can't store session: " + e, e); isError = true; } try { if (session.isValid()) _sessions.remove(session.getId()); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } if (_admin != null) _admin.unregister(); _sessionList = new ArrayList<SessionImpl>(); } /** * Converts an integer to a printable character */ private static char convert(long code) { code = code & 0x3f; if (code < 26) return (char) ('a' + code); else if (code < 52) return (char) ('A' + code - 26); else if (code < 62) return (char) ('0' + code - 52); else if (code == 62) return '_'; else return '-'; } static int getServerCode(String id, int count) { if (id == null) return -1; if (count == 0) { return decode(id.charAt(0)); } long hash = Crc64.generate(id); for (int i = 0; i < count; i++) { hash >>= 6; } return (int) (hash & 0x3f); } private static int decode(int code) { return DECODE[code & 0x7f]; } @Override public String toString() { return getClass().getSimpleName() + "[" + _webApp.getContextPath() + "]"; } static { DECODE = new int[128]; for (int i = 0; i < 64; i++) DECODE[(int) convert(i)] = i; } }
gpl-2.0
league/rngzip
libs/bali/org/kohsuke/bali/automaton/Transition.java
721
package org.kohsuke.bali.automaton; /** * * * @author Kohsuke Kawaguchi (kk@kohsuke.org) */ public final class Transition { /** Alphabet of this transition. */ public final Alphabet alphabet; /** State for the first child. */ public final State left; /** State for the next sibling. */ public final State right; public Transition( Alphabet a, State l, State r ) { this.alphabet = a; this.left = l; this.right = r; // sanity check if( (a instanceof ElementAlphabet) || (a instanceof AttributeAlphabet) ) if(l==null) throw new InternalError(); } }
gpl-2.0
md-5/jdk10
test/jdk/java/foreign/TestVarHandleCombinators.java
6805
/* * Copyright (c) 2019, 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. * * 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. * */ /* * @test * @run testng TestVarHandleCombinators */ import jdk.incubator.foreign.MemoryHandles; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import jdk.incubator.foreign.MemoryAddress; import jdk.incubator.foreign.MemorySegment; import java.lang.invoke.VarHandle; import java.nio.ByteOrder; import static org.testng.Assert.assertEquals; public class TestVarHandleCombinators { @Test public void testElementAccess() { VarHandle vh = MemoryHandles.varHandle(byte.class, ByteOrder.nativeOrder()); vh = MemoryHandles.withStride(vh, 1); byte[] arr = { 0, 0, -1, 0 }; MemorySegment segment = MemorySegment.ofArray(arr); MemoryAddress addr = segment.baseAddress(); assertEquals((byte) vh.get(addr, 2), (byte) -1); } @Test(expectedExceptions = IllegalArgumentException.class) public void testUnalignedElement() { VarHandle vh = MemoryHandles.varHandle(byte.class, 4, ByteOrder.nativeOrder()); MemoryHandles.withStride(vh, 2); } @Test(expectedExceptions = IllegalArgumentException.class) public void testBadStrideElement() { VarHandle vh = MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder()); MemoryHandles.withStride(vh, 0); //scale factor cant be zero } @Test(expectedExceptions = IllegalArgumentException.class) public void testAlignNotPowerOf2() { VarHandle vh = MemoryHandles.varHandle(byte.class, 3, ByteOrder.nativeOrder()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAlignNegative() { VarHandle vh = MemoryHandles.varHandle(byte.class, -1, ByteOrder.nativeOrder()); } @Test public void testAlign() { VarHandle vh = MemoryHandles.varHandle(byte.class, 2, ByteOrder.nativeOrder()); MemorySegment segment = MemorySegment.allocateNative(1, 2); MemoryAddress address = segment.baseAddress(); vh.set(address, (byte) 10); // fine, memory region is aligned assertEquals((byte) vh.get(address), (byte) 10); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAlignBadAccess() { VarHandle vh = MemoryHandles.varHandle(byte.class, 2, ByteOrder.nativeOrder()); vh = MemoryHandles.withOffset(vh, 1); // offset by 1 byte MemorySegment segment = MemorySegment.allocateNative(2, 2); MemoryAddress address = segment.baseAddress(); vh.set(address, (byte) 10); // should be bad align } @Test(expectedExceptions = IllegalArgumentException.class) public void testOffsetNegative() { VarHandle vh = MemoryHandles.varHandle(byte.class, ByteOrder.nativeOrder()); MemoryHandles.withOffset(vh, -1); } @Test(expectedExceptions = IllegalArgumentException.class) public void testUnalignedOffset() { VarHandle vh = MemoryHandles.varHandle(byte.class, 4, ByteOrder.nativeOrder()); MemoryHandles.withOffset(vh, 2); } @Test public void testOffset() { VarHandle vh = MemoryHandles.varHandle(byte.class, ByteOrder.nativeOrder()); vh = MemoryHandles.withOffset(vh, 1); MemorySegment segment = MemorySegment.ofArray(new byte[2]); MemoryAddress address = segment.baseAddress(); vh.set(address, (byte) 10); assertEquals((byte) vh.get(address), (byte) 10); } @Test public void testByteOrderLE() { VarHandle vh = MemoryHandles.varHandle(short.class, 2, ByteOrder.LITTLE_ENDIAN); byte[] arr = new byte[2]; MemorySegment segment = MemorySegment.ofArray(arr); MemoryAddress address = segment.baseAddress(); vh.set(address, (short) 0xFF); assertEquals(arr[0], (byte) 0xFF); assertEquals(arr[1], (byte) 0); } @Test public void testByteOrderBE() { VarHandle vh = MemoryHandles.varHandle(short.class, 2, ByteOrder.BIG_ENDIAN); byte[] arr = new byte[2]; MemorySegment segment = MemorySegment.ofArray(arr); MemoryAddress address = segment.baseAddress(); vh.set(address, (short) 0xFF); assertEquals(arr[0], (byte) 0); assertEquals(arr[1], (byte) 0xFF); } @Test public void testNestedSequenceAccess() { int outer_size = 10; int inner_size = 5; //[10 : [5 : [x32 i32]]] VarHandle vh = MemoryHandles.varHandle(int.class, ByteOrder.nativeOrder()); vh = MemoryHandles.withOffset(vh, 4); VarHandle inner_vh = MemoryHandles.withStride(vh, 8); VarHandle outer_vh = MemoryHandles.withStride(inner_vh, 5 * 8); int count = 0; try (MemorySegment segment = MemorySegment.allocateNative(inner_size * outer_size * 8)) { for (long i = 0; i < outer_size; i++) { for (long j = 0; j < inner_size; j++) { outer_vh.set(segment.baseAddress(), i, j, count); assertEquals( (int)inner_vh.get(segment.baseAddress().offset(i * inner_size * 8), j), count); count++; } } } } @Test(dataProvider = "badCarriers", expectedExceptions = IllegalArgumentException.class) public void testBadCarrier(Class<?> carrier) { MemoryHandles.varHandle(carrier, ByteOrder.nativeOrder()); } @DataProvider(name = "badCarriers") public Object[][] createBadCarriers() { return new Object[][] { { void.class }, { boolean.class }, { Object.class }, { int[].class }, { MemoryAddress.class } }; } }
gpl-2.0
rex-xxx/mt6572_x201
packages/providers/ContactsProvider/src/com/android/providers/contacts/DataRowHandlerForSipAddress.java
18081
package com.android.providers.contacts; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import android.net.sip.SipManager; import android.provider.CallLog.Calls; import android.provider.ContactsContract.CommonDataKinds.SipAddress; import android.util.Log; import com.android.providers.contacts.ContactsDatabaseHelper.DialerSearchLookupColumns; import com.android.providers.contacts.ContactsDatabaseHelper.DialerSearchLookupType; import com.android.providers.contacts.ContactsDatabaseHelper.Tables; import com.android.providers.contacts.SearchIndexManager.IndexBuilder; import com.android.providers.contacts.aggregation.ContactAggregator; import com.mediatek.providers.contacts.ContactsFeatureConstants; import com.mediatek.providers.contacts.ContactsFeatureConstants.FeatureOption; /* * Feature Fix by Mediatek End. */ public class DataRowHandlerForSipAddress extends DataRowHandlerForCommonDataKind { private static final String TAG = "DataRowHandlerForSipAddress"; private static final boolean DBG = ContactsFeatureConstants.DBG_DIALER_SEARCH; private Context mContext; private ContactsDatabaseHelper mDbHelper; private SQLiteStatement mDialerSearchNumDelByCallLogIdDelete;; private SQLiteStatement mDialerSearchNewRecordInsert; private SQLiteStatement mCallsNewInsertDataIdUpdate; private SQLiteStatement mCallsGetLatestCallLogIdForOneContactQuery; private SQLiteStatement mCallsReplaceDataIdUpdate; private SQLiteStatement mDialerSearchNoNameCallLogNumDataIdUpdate; private SQLiteStatement mDialerSearchContactNumDelete; public DataRowHandlerForSipAddress(Context context, ContactsDatabaseHelper dbHelper, ContactAggregator aggregator) { super(context, dbHelper, aggregator, SipAddress.CONTENT_ITEM_TYPE, SipAddress.TYPE, SipAddress.LABEL); mContext = context; mDbHelper = dbHelper; } @Override public int delete(SQLiteDatabase db, TransactionContext txContext, Cursor c) { if (!SipManager.isVoipSupported(mContext)) { return 0; } long dataId = c.getLong(DataDeleteQuery._ID); int count = super.delete(db, txContext, c); if (FeatureOption.MTK_SEARCH_DB_SUPPORT) { log("[delete] dataId: " + dataId); // For callLog, remove raw_contact_id and data_id if (mCallsReplaceDataIdUpdate == null) { mCallsReplaceDataIdUpdate = db.compileStatement( "UPDATE " + Tables.CALLS + " SET " + Calls.DATA_ID + "=?, " + Calls.RAW_CONTACT_ID + "=? " + " WHERE " + Calls.DATA_ID + " =? "); } mCallsReplaceDataIdUpdate.bindNull(1); mCallsReplaceDataIdUpdate.bindNull(2); mCallsReplaceDataIdUpdate.bindLong(3, dataId); mCallsReplaceDataIdUpdate.execute(); log("[delete] Remove raw_contact_id and data_id data in CallLog. "); // For dialer search, CallLog contacts // change the number record to NO NAME CALLLOG in dialer search // table if (mDialerSearchNoNameCallLogNumDataIdUpdate == null) { mDialerSearchNoNameCallLogNumDataIdUpdate = db.compileStatement( "UPDATE " + Tables.DIALER_SEARCH + " SET " + DialerSearchLookupColumns.RAW_CONTACT_ID + " = -" + DialerSearchLookupColumns.CALL_LOG_ID + "," + DialerSearchLookupColumns.DATA_ID + " = -" + DialerSearchLookupColumns.CALL_LOG_ID + " WHERE " + DialerSearchLookupColumns.DATA_ID + " = ? AND " + DialerSearchLookupColumns.CALL_LOG_ID + " > 0 AND " + DialerSearchLookupColumns.NAME_TYPE + " = " + DialerSearchLookupType.PHONE_EXACT); } mDialerSearchNoNameCallLogNumDataIdUpdate.bindLong(1, dataId); mDialerSearchNoNameCallLogNumDataIdUpdate.execute(); log("[update] Change old record in dialer_search table to a NO NAME CALLLOG. "); // For dialer search, No call log contacts if (mDialerSearchContactNumDelete == null) { mDialerSearchContactNumDelete = db.compileStatement( "DELETE FROM " + Tables.DIALER_SEARCH + " WHERE " + DialerSearchLookupColumns.DATA_ID + " =? AND " + DialerSearchLookupColumns.CALL_LOG_ID + " = 0 AND " + DialerSearchLookupColumns.NAME_TYPE + " = " + DialerSearchLookupType.PHONE_EXACT); } mDialerSearchContactNumDelete.bindLong(1, dataId); mDialerSearchContactNumDelete.execute(); log("[delete] delete dialer search table."); } return count; } @Override public long insert(SQLiteDatabase db, TransactionContext txContext, long rawContactId, ContentValues values) { if (!SipManager.isVoipSupported(mContext)) { return 0; } long dataId; if (values.containsKey(SipAddress.SIP_ADDRESS)) { dataId = super.insert(db, txContext, rawContactId, values); if (FeatureOption.MTK_SEARCH_DB_SUPPORT) { String sipNumber = values.getAsString(SipAddress.SIP_ADDRESS); // update call Log record, and get the Latest call_log_id of the // inserted number int mLatestCallLogId = updateCallsInfoForNewInsertNumber(db, sipNumber, rawContactId, dataId); log("[insert] latest call log id: " + mLatestCallLogId); // delete NO Name CALLLOG in dialer search table. if (mLatestCallLogId > 0) { if (mDialerSearchNumDelByCallLogIdDelete == null) { mDialerSearchNumDelByCallLogIdDelete = db.compileStatement( "DELETE FROM " + Tables.DIALER_SEARCH + " WHERE " + DialerSearchLookupColumns.CALL_LOG_ID + " =? " + " AND " + DialerSearchLookupColumns.NAME_TYPE + " = " + DialerSearchLookupType.PHONE_EXACT); } mDialerSearchNumDelByCallLogIdDelete.bindLong(1, mLatestCallLogId); mDialerSearchNumDelByCallLogIdDelete.execute(); log("[insert]delete no name call log. "); } // insert new data into dialer search table with latest call log // id. if (mDialerSearchNewRecordInsert == null) { mDialerSearchNewRecordInsert = db.compileStatement( "INSERT INTO " + Tables.DIALER_SEARCH + "(" + DialerSearchLookupColumns.RAW_CONTACT_ID + "," + DialerSearchLookupColumns.DATA_ID + "," + DialerSearchLookupColumns.NORMALIZED_NAME + "," + DialerSearchLookupColumns.NAME_TYPE + "," + DialerSearchLookupColumns.CALL_LOG_ID + "," + DialerSearchLookupColumns.NORMALIZED_NAME_ALTERNATIVE + ")" + " VALUES (?,?,?,?,?,?)"); } mDialerSearchNewRecordInsert.bindLong(1, rawContactId); mDialerSearchNewRecordInsert.bindLong(2, dataId); bindString(mDialerSearchNewRecordInsert, 3, sipNumber); mDialerSearchNewRecordInsert.bindLong(4, DialerSearchLookupType.PHONE_EXACT); mDialerSearchNewRecordInsert.bindLong(5, mLatestCallLogId); bindString(mDialerSearchNewRecordInsert, 6, sipNumber); mDialerSearchNewRecordInsert.executeInsert(); log("[insert] insert new data into dialer search table. "); } } else { dataId = super.insert(db, txContext, rawContactId, values); } return dataId; } @Override public boolean update(SQLiteDatabase db, TransactionContext txContext, ContentValues values, Cursor c, boolean callerIsSyncAdapter) { if (!SipManager.isVoipSupported(mContext)) { return false; } if (!super.update(db, txContext, values, c, callerIsSyncAdapter)) return false; if (values.containsKey(SipAddress.SIP_ADDRESS)) { if (FeatureOption.MTK_SEARCH_DB_SUPPORT == true) { long dataId = c.getLong(DataUpdateQuery._ID); long rawContactId = c.getLong(DataUpdateQuery.RAW_CONTACT_ID); String sipNumber = values.getAsString(SipAddress.SIP_ADDRESS); String mStrDataId = String.valueOf(dataId); String mStrRawContactId = String.valueOf(rawContactId); log("[update]update: sipNumber: " + sipNumber + " || mStrRawContactId: " + mStrRawContactId + " || mStrDataId: " + mStrDataId); // update calls table to clear raw_contact_id and data_id, if // the changing number or the changed number exists in call log. int mDeletedCallLogId = 0; // update records in calls table to no name callLog if (mCallsReplaceDataIdUpdate == null) { mCallsReplaceDataIdUpdate = db.compileStatement( "UPDATE " + Tables.CALLS + " SET " + Calls.DATA_ID + "=?, " + Calls.RAW_CONTACT_ID + "=? " + " WHERE " + Calls.DATA_ID + " =? "); } mCallsReplaceDataIdUpdate.bindNull(1); mCallsReplaceDataIdUpdate.bindNull(2); mCallsReplaceDataIdUpdate.bindLong(3, dataId); mCallsReplaceDataIdUpdate.execute(); log("[update] Change the old records in calls table to a NO NAME CALLLOG."); // update records in dialer search table to no name call if // callLogId>0 if (mDialerSearchNoNameCallLogNumDataIdUpdate == null) { mDialerSearchNoNameCallLogNumDataIdUpdate = db.compileStatement( "UPDATE " + Tables.DIALER_SEARCH + " SET " + DialerSearchLookupColumns.RAW_CONTACT_ID + " = -" + DialerSearchLookupColumns.CALL_LOG_ID + "," + DialerSearchLookupColumns.DATA_ID + " = -" + DialerSearchLookupColumns.CALL_LOG_ID + " WHERE " + DialerSearchLookupColumns.DATA_ID + " = ? AND " + DialerSearchLookupColumns.CALL_LOG_ID + " > 0 AND " + DialerSearchLookupColumns.NAME_TYPE + " = " + DialerSearchLookupType.PHONE_EXACT); } mDialerSearchNoNameCallLogNumDataIdUpdate.bindLong(1, dataId); mDialerSearchNoNameCallLogNumDataIdUpdate.execute(); log("[update]Change old records in dialer_search to NO NAME CALLLOG FOR its callLogId>0."); // delete records in dialer search table if callLogId = 0 if (mDialerSearchContactNumDelete == null) { mDialerSearchContactNumDelete = db.compileStatement( "DELETE FROM " + Tables.DIALER_SEARCH + " WHERE " + DialerSearchLookupColumns.DATA_ID + " =? AND " + DialerSearchLookupColumns.CALL_LOG_ID + " = 0 AND " + DialerSearchLookupColumns.NAME_TYPE + " = " + DialerSearchLookupType.PHONE_EXACT); } mDialerSearchContactNumDelete.bindLong(1, dataId); mDialerSearchContactNumDelete.execute(); log("[update]Delete old records in dialer_search FOR its callLogId=0."); // update new number's callLog info(dataId & rawContactId) if // exists int mLatestCallLogId = updateCallsInfoForNewInsertNumber(db, sipNumber, rawContactId, dataId); log("[update] latest call log id: " + mLatestCallLogId); // delete NO Name CALLLOG in dialer search table. if (mLatestCallLogId > 0) { if (mDialerSearchNumDelByCallLogIdDelete == null) { mDialerSearchNumDelByCallLogIdDelete = db.compileStatement( "DELETE FROM " + Tables.DIALER_SEARCH + " WHERE " + DialerSearchLookupColumns.CALL_LOG_ID + " =? " + " AND " + DialerSearchLookupColumns.NAME_TYPE + " = " + DialerSearchLookupType.PHONE_EXACT); } mDialerSearchNumDelByCallLogIdDelete.bindLong(1, mLatestCallLogId); mDialerSearchNumDelByCallLogIdDelete.execute(); log("[update]delete no name call log for udpated number. "); } // insert new number into dialer search table with latest call // log id. if (mDialerSearchNewRecordInsert == null) { mDialerSearchNewRecordInsert = db.compileStatement( "INSERT INTO " + Tables.DIALER_SEARCH + "(" + DialerSearchLookupColumns.RAW_CONTACT_ID + "," + DialerSearchLookupColumns.DATA_ID + "," + DialerSearchLookupColumns.NORMALIZED_NAME + "," + DialerSearchLookupColumns.NAME_TYPE + "," + DialerSearchLookupColumns.CALL_LOG_ID + "," + DialerSearchLookupColumns.NORMALIZED_NAME_ALTERNATIVE + ")" + " VALUES (?,?,?,?,?,?)"); } mDialerSearchNewRecordInsert.bindLong(1, rawContactId); mDialerSearchNewRecordInsert.bindLong(2, dataId); bindString(mDialerSearchNewRecordInsert, 3, sipNumber); mDialerSearchNewRecordInsert.bindLong(4, DialerSearchLookupType.PHONE_EXACT); mDialerSearchNewRecordInsert.bindLong(5, mLatestCallLogId); bindString(mDialerSearchNewRecordInsert, 6, sipNumber); mDialerSearchNewRecordInsert.executeInsert(); log("[update] insert new data into dialer search table. "); } } return true; } int updateCallsInfoForNewInsertNumber(SQLiteDatabase db, String number, long rawContactId, long dataId) { if (mCallsNewInsertDataIdUpdate == null) { mCallsNewInsertDataIdUpdate = db.compileStatement( "UPDATE " + Tables.CALLS + " SET " + Calls.DATA_ID + "=?, " + Calls.RAW_CONTACT_ID + "=? " + " WHERE " + Calls.NUMBER + "=? AND " + Calls.DATA_ID + " IS NULL "); } if (mCallsGetLatestCallLogIdForOneContactQuery == null) { mCallsGetLatestCallLogIdForOneContactQuery = db.compileStatement( "SELECT " + Calls._ID + " FROM " + Tables.CALLS + " WHERE " + Calls.DATE + " = (" + " SELECT MAX( " + Calls.DATE + " ) " + " FROM " + Tables.CALLS + " WHERE " + Calls.DATA_ID + " =? )"); } mCallsNewInsertDataIdUpdate.bindLong(1, dataId); mCallsNewInsertDataIdUpdate.bindLong(2, rawContactId); bindString(mCallsNewInsertDataIdUpdate, 3, number); mCallsNewInsertDataIdUpdate.execute(); int mCallLogId = 0; try { mCallsGetLatestCallLogIdForOneContactQuery.bindLong(1, dataId); mCallLogId = (int) mCallsGetLatestCallLogIdForOneContactQuery.simpleQueryForLong(); } catch (android.database.sqlite.SQLiteDoneException e) { return 0; } catch (NullPointerException e) { return 0; } // Commount out call log notification since ICS call still uses the // default one. // if (mCallLogId > 0) { // notifyCallsChanged(); // } return mCallLogId; } void bindString(SQLiteStatement stmt, int index, String value) { if (value == null) { stmt.bindNull(index); } else { stmt.bindString(index, value); } } private void log(String msg) { if (DBG) { Log.d(TAG, msg); } } /* * Feature Fix by Mediatek Begin Original Android code: */ @Override public boolean hasSearchableData() { return true; } @Override public boolean containsSearchableColumns(ContentValues values) { return values.containsKey(SipAddress.SIP_ADDRESS); } @Override public void appendSearchableData(IndexBuilder builder) { builder.appendContentFromColumn(SipAddress.SIP_ADDRESS); } /* * Feature Fix by Mediatek End */ }
gpl-2.0
asiekierka/Chisel-1.7.2
src/main/java/info/jbcs/minecraft/chisel/block/BlockCarvableGlass.java
1881
package info.jbcs.minecraft.chisel.block; import info.jbcs.minecraft.chisel.CarvableHelper; import info.jbcs.minecraft.chisel.CarvableVariation; import info.jbcs.minecraft.chisel.Chisel; import info.jbcs.minecraft.chisel.api.Carvable; import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.BlockGlass; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.util.IIcon; public class BlockCarvableGlass extends BlockGlass implements Carvable { public CarvableHelper carverHelper; private boolean isAlpha = false; public BlockCarvableGlass() { super(Material.glass, false); carverHelper = new CarvableHelper(); setCreativeTab(Chisel.tabChisel); } public BlockCarvableGlass setStained(boolean a) { this.isAlpha = a; return this; } @Override public boolean renderAsNormalBlock() { return false; } @Override public int getRenderType() { return Chisel.RenderCTMId; } @Override public IIcon getIcon(int side, int metadata) { return carverHelper.getIcon(side, metadata); } @Override public int damageDropped(int i) { return i; } @Override public void registerBlockIcons(IIconRegister register) { carverHelper.registerBlockIcons("Chisel",this,register); } @Override public void getSubBlocks(Item item, CreativeTabs tabs, List list){ carverHelper.registerSubBlocks(this,tabs,list); } @Override public CarvableVariation getVariation(int metadata) { return carverHelper.getVariation(metadata); } @Override @SideOnly(Side.CLIENT) public int getRenderBlockPass() { return isAlpha ? 1 : 0; } }
gpl-2.0
zhang123shuo/javamop
src/javamop/parser/ast/expr/NullLiteralExpr.java
1487
/* * Copyright (C) 2007 Julio Vilmar Gesser. * * This file is part of Java 1.5 parser and Abstract Syntax Tree. * * Java 1.5 parser and Abstract Syntax Tree is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java 1.5 parser and Abstract Syntax Tree 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 Java 1.5 parser and Abstract Syntax Tree. If not, see <http://www.gnu.org/licenses/>. */ /* * Created on 02/03/2007 */ package javamop.parser.ast.expr; import javamop.parser.ast.visitor.GenericVisitor; import javamop.parser.ast.visitor.VoidVisitor; /** * @author Julio Vilmar Gesser */ public final class NullLiteralExpr extends LiteralExpr { public NullLiteralExpr(int line, int column) { super(line, column); } @Override public <A> void accept(VoidVisitor<A> v, A arg) { v.visit(this, arg); } @Override public <R, A> R accept(GenericVisitor<R, A> v, A arg) { return v.visit(this, arg); } }
gpl-2.0
myth/trashcan
tdt4186/src/ex3/Memory.java
2741
package ex3; /** * This class implements functionality associated with * the memory device of the simulated system. */ public class Memory { /** The queue of processes waiting for free memory */ private Queue memoryQueue; /** A reference to the statistics collector */ private Statistics statistics; /** The amount of memory in the memory device */ private long memorySize; /** The amount of free memory in the memory device */ private long freeMemory; /** * Creates a new memory device with the given parameters. * @param memoryQueue The memory queue to be used. * @param memorySize The amount of memory in the memory device. * @param statistics A reference to the statistics collector. */ public Memory(Queue memoryQueue, long memorySize, Statistics statistics) { this.memoryQueue = memoryQueue; this.memorySize = memorySize; this.statistics = statistics; freeMemory = memorySize; } /** * Returns the amount of memory in the memory device. * @return The size of the memory device. */ public long getMemorySize() { return memorySize; } /** * Adds a process to the memory queue. * @param p The process to be added. */ public void insertProcess(Process p) { memoryQueue.insert(p); } /** * Checks whether or not there is enough free memory to let * the first process in the memory queue proceed to the cpu queue. * If there is, the process that was granted memory is returned, * otherwise null is returned. * @param clock The current time. */ public Process checkMemory(long clock) { if(!memoryQueue.isEmpty()) { Process nextProcess = (Process)memoryQueue.getNext(); if(nextProcess.getMemoryNeeded() <= freeMemory) { // Allocate memory to this process freeMemory -= nextProcess.getMemoryNeeded(); nextProcess.leftMemoryQueue(clock); memoryQueue.removeNext(); return nextProcess; } } return null; } /** * This method is called when a discrete amount of time has passed. * @param timePassed The amount of time that has passed since the last call to this method. */ public void timePassed(long timePassed) { statistics.memoryQueueLengthTime += memoryQueue.getQueueLength()*timePassed; if (memoryQueue.getQueueLength() > statistics.memoryQueueLargestLength) { statistics.memoryQueueLargestLength = memoryQueue.getQueueLength(); } } /** * This method is called when a process is exiting the system. * The memory allocated to this process is freed. * @param p The process that is leaving the system. */ public void processCompleted(Process p) { freeMemory += p.getMemoryNeeded(); } }
gpl-2.0
krishnact/binmsg
src/org/himalay/msgs/runtime/ByteArray.java
8263
package org.himalay.msgs.runtime; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; public class ByteArray implements ComplexBinMessage { public static enum enLenghType { EOS, FIRST_UI8, FIRST_UI16, FIRST_UI24, FIRST_UI32, FIXED, EXTERNAL, NULLTERMINATED }; byte[] data; enLenghType sizeType; public ByteArray() { super(); } // public ByteArray(byte[] data, String sizeType) { // super(); // this.data = data; // setSize(sizeType); // } // public ByteArray(String sizeType) { // this(null, sizeType); // } // public ByteArray(int size, String sizeType) { // this(null, sizeType); // data = new byte[size]; // } public int read(DataInputStream istream) throws IOException { int iRead = 0; switch (sizeType) { case EOS: { byte[] ba = new byte[1014 * 10]; if (istream.available() > 0) { iRead = istream.read(ba); if ( iRead > 0) { data = new byte[iRead]; System.arraycopy(ba, 0, data, 0, iRead); }else { iRead = 0; } } else { data = new byte[0]; } break; } case FIRST_UI8: { iRead = 0x00 | istream.read(); data = new byte[iRead]; if (data.length > 0) iRead = istream.read(data)+1; break; } case FIRST_UI16: { iRead = 0x00 | istream.readUnsignedShort(); data = new byte[iRead]; if (data.length > 0) iRead = istream.read(data)+2; break; } case FIRST_UI24: { iRead = BinPrimitive.readUI24(istream); data = new byte[iRead]; if (data.length > 0) iRead = istream.read(data)+3; break; } case FIRST_UI32: { iRead = (int)BinPrimitive.readUI32(istream); data = new byte[iRead]; if (data.length > 0) iRead = istream.read(data)+4; break; } case EXTERNAL: { if (data.length > 0) iRead = istream.read(data); break; } case FIXED: { if (data.length > 0) iRead = istream.read(data); break; } case NULLTERMINATED: this.data = readZString(istream); if (data.length > 0) iRead = this.data.length; break; } return iRead; } private byte[] readZString(InputStream is) throws IOException { // Allocate a byte byffer int buffLength = 1024; byte[] retVal = new byte[buffLength]; int iCnt = 0; int justRead =0; do { justRead = is.read(); retVal[iCnt++]= (byte)justRead; if ( iCnt == retVal.length) { buffLength+= 1024; byte [] newBuff = new byte[buffLength]; System.arraycopy(retVal, 0, newBuff, 0, retVal.length); retVal = newBuff; } }while( justRead != 0); byte[] rr = new byte[iCnt]; System.arraycopy(retVal, 0, rr, 0, rr.length); return rr; } public void setSizeType(String size) { this.sizeType = enLenghType.valueOf(size); } public void setSize(String size) { setSize(Integer.parseInt(size)); } public void setSize(int size) { data = new byte[size]; } public void dump(DumpContext dc) { // pstream.print("Dumping " + this.data.length+"\n"); // HexDump.dumpHexData(pstream, "", this.data, this.data.length); dump(dc, this.data); } public static void dump(DumpContext dc, byte [] bytes) { // pstream.print("Dumping " + this.data.length+"\n"); // HexDump.dumpHexData(pstream, "", this.data, this.data.length); int width = 16; if ( bytes != null) { try { for (int index = 0; index < bytes.length; index += width) { dc.getPs().print(dc.getIndentString()); printHex(dc, bytes, index, width); printAscii(dc, bytes, index, width); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { dc.indent(); dc.ps.println("null"); } } public static void dump(DumpContext dc, byte [] bytes, int offsetStart, int length) { // pstream.print("Dumping " + this.data.length+"\n"); // HexDump.dumpHexData(pstream, "", this.data, this.data.length); int width = 16; if ( bytes != null) { int iEnd = (offsetStart + length )< bytes.length?(offsetStart + length ):bytes.length; try { for (int index = offsetStart; index < iEnd ; index += width) { dc.getPs().print(dc.getIndentString()); printHex(dc, bytes, index, width); printAscii(dc, bytes, index, width); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { dc.indent(); dc.ps.println("null"); } } @Override public int getSize() { if (this.data != null) return this.data.length; else return 0; } public int write(DataOutputStream ostream) throws IOException { // if the length is not external then we have to write length also int retVal = 0; switch (sizeType) { case FIRST_UI16: if ( this.data != null) { ostream.write(this.data.length >> 8); ostream.write(this.data.length); }else { ostream.writeShort(0); } retVal +=2; ostream.write(data); break; case FIRST_UI8: if ( this.data != null) { ostream.write(this.data.length); }else { ostream.write(0); } ostream.write(data); retVal +=1; break; case FIRST_UI24: { int iWrt = 0; if ( this.data != null) { iWrt = this.data.length; } ostream.write((iWrt >> 16)&(0x000000FF)); ostream.write((iWrt >> 8)&(0x000000FF)); ostream.write((iWrt)&(0x000000FF)); retVal +=3; ostream.write(data); break; } case FIRST_UI32: int iWrt = 0; if ( this.data != null) { iWrt = this.data.length; } ostream.writeInt(iWrt); retVal +=4; ostream.write(data); break; case EOS: case EXTERNAL: case FIXED: if ( this.data != null) ostream.write(data); break; case NULLTERMINATED: if ( this.data != null) { ostream.write(data); } ostream.write(0); break; } retVal += data.length; return retVal; } public void setData(byte[] newData) { if ( this.sizeType == enLenghType.FIXED) { this.copyData(newData); }else this.data = newData; } public void copyData(byte[] newData, int offset, int length) { System.arraycopy(newData, offset, this.data, 0, length>this.data.length?this.data.length:length); } public void copyData(byte[] newData) { copyData(newData,0,newData.length); } private static void printHex(DumpContext dc, byte[] bytes, int offset, int width) { for (int index = 0; index < width; index++) { if (index + offset < bytes.length) { dc.getPs().printf("%02x ", bytes[index + offset]); } else { dc.getPs().print(" "); } } } private static void printAscii(DumpContext dc, byte[] bytes, int index, int width) throws UnsupportedEncodingException { if (index < bytes.length) { width = Math.min(width, bytes.length - index); //String str = new String(bytes, index, width, "UTF-8"); byte[] bytes1 = new byte[width];//str.getBytes(); System.arraycopy(bytes, index, bytes1,0,width); for (int i = 0; i < bytes1.length; i++) { if ( bytes1[i] < 32) { bytes1[i] = '.'; } } dc.getPs().println(new String(bytes1)); } else { dc.getPs().println(); } } public byte [] getData() { return data; } public static DataInputStream createDataInputStream(byte[] data, int offset, int length){ return new DataInputStream(new ByteArrayInputStream(data, offset, length)); } public static DataInputStream createDataInputStream(byte[] data){ return createDataInputStream(data, 0, data.length); } public String getAsStringFromUTF8() throws UnsupportedEncodingException { return new String(this.getData(),"UTF-8"); } public void setFromUTF8String(String strData) throws UnsupportedEncodingException { setData(strData.getBytes("UTF-8")); } public String getAsASCIIFromUTF8() throws UnsupportedEncodingException { return new String(this.getData(),"ASCII"); } public void setFromASCIIString(String strData) throws UnsupportedEncodingException { setData(strData.getBytes("ASCII")); } @Override public String toString() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.dump(new DumpContext(baos)); return new String(baos.toByteArray()); } }
gpl-2.0
lorenzopardini/uniformization
main/it/unifi/oris/sirio/uniformization/main/FoxGlynnWeighter.java
5697
package it.unifi.oris.sirio.uniformization.main; /** * Questa classe realizza il calcolo dei weights e del Total Weight necessari ad effettuare * un'approssimazione dell'andamento di una distribuzione di Poisson secondo Fox e Glynn. * @author Samuele Foni & Lorenzo Pardini * */ public final class FoxGlynnWeighter extends PoissonWeighterTechnique{ //Singleton Pattern private static PoissonWeighterTechnique istance = null; private FoxGlynnWeighter(){}; protected static PoissonWeighterTechnique getIstance(){ if(FoxGlynnWeighter.istance == null){ FoxGlynnWeighter.istance = new FoxGlynnWeighter(); } return FoxGlynnWeighter.istance; } //End - Singleton /** * This method implements the WEIGHTER function of "Computing Poisson Probabilities". * @param lambda (input) is the rate of the Poisson distribution. * @param tau is the underflow threshold. * @param omega is the overflow threshold. * @param epsilon (input) is the wanted accuracy. * @param L (input) is the left truncation point. * @param R (input/output) is the right truncation point. Warning: Don't use defensive copy! * This method may had to change R's value. * @param F (output) is the flag for successful ending of the method. Should be checked by the caller. * @param weights (output) is the array of weights. * @param totalWeight (output) is the sum of the weights. Warning: don't use defensive copy! */ protected DataContainer weighter(DataContainer myData){ double lambda =myData.getLambda(); double tau =myData.getUnderFlowLimit(); double omega=myData.getOverFlowLimit(); double epsilon=myData.getWantedAccuracy(); Integer L=myData.getL(); Integer R=myData.getR(); Boolean F=myData.getFoxGlynnFlagF(); double[] weights = new double[R.intValue()-L.intValue()+1]; Double totalWeight; double m = Math.floor(lambda); /** * CALCOLO DI w(m): * w(m) rappresenta il valore medio della moda da cui si parte per * effettuare il calcolo dei restanti weights. La scelta di w(m) deve essere fatta * a priori. Il valore ideale sarebbe pari ad 1 (v. pg. 441 Computing Poisson Probabilities). * Ma per evitare eventuali errori di underflow, lo poniamo uguale a Omega/(10^10)*(R-L). * Questa scelta euristica garantisce che il Total Weights sarà tale da risultare minore * o uguale di Omega/(10^10) (v. pg. 443 Computing Poisson Probabilities). * Dove con Omega si intende il massimo valore rappresentabile. */ double LL=L.doubleValue(); double RR=R.doubleValue(); double omega_m = omega/(Math.pow((double)10, (double)10)*(RR-LL)); //TEST //System.out.println("\n Starting Weighter... \n\t L="+LL+" R="+RR+" omega_m="+omega_m); int mm = (int)m - L.intValue(); //indice del valore della moda traslato sul vettore tra 0 ed R-L. weights[mm] = omega_m; //Caso L int j = (int) m; while(j>L.intValue()){ weights[mm - 1] = ((double)j/lambda)*weights[mm]; mm=mm-1; j=j-1; } if(lambda<400&&R.intValue()>600){ F = Boolean.FALSE; myData.setFoxGlynnFlagF(F); //System.out.println("\t Case: (lambda<400 && R>660) --> FAIL!"); return myData; } if(lambda<400 && R.intValue()<=600){ j = (int) m; mm = (int)m - L.intValue(); double q = 0.0; while(j<R.intValue()){ q = lambda/(((double)j)+((double)1)); if(weights[mm]>(tau/q)){ weights[mm+1] = q*weights[mm]; mm = mm+1; j = j+1; }else{ R=Integer.valueOf(j); //System.out.println("\t Special: R was updated to: "+R); } } } if(lambda>=400){ j = (int) m; mm = (int)m - L.intValue(); while(j<R.intValue()){ weights[mm+1]=(lambda/(((double)j)+((double)1)))*weights[mm]; j=j+1; mm=mm+1; } } totalWeight = Double.valueOf(computeW(L, R, weights)); //System.out.println("\n\t Total Weight = "+totalWeight); myData.setFoxGlynnFlagF(F); myData.setR(R); myData.setFoxGlynnTotalWeight(totalWeight); myData.setFoxGlynnWeights(weights); return myData; } /** * This method compute the Total Weight W adding the weights between L and R. * For numerical stability (see Computing Poisson Probabilities pg. 441) small weights * are added first. * @param R the right truncation point * @param L the left truncation point * @param weights the array of weights * @return the Total Weight W */ private double computeW( Integer L, Integer R, double[] weights){ int s = 0; //Sarebbe L-L int t = R.intValue() - L.intValue(); double W = 0.0; while(s<t){ if(weights[s]<=weights[t]){ W = W + weights[s]; s = s+1; }else{ W = W + weights[t]; t = t-1; } } // A questo punto s==t e rappresenta la moda. // Quindi sommo il weights centrale: omega_m. W = W + weights[s]; return W; } }
gpl-2.0
Ajibola/texs-ui-j2me
texs_ui_src/src/net/texsoftware/lib/Compatibility.java
1021
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.texsoftware.lib; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Graphics; /** * * @author Jibz7 */ public class Compatibility { public static boolean touchSupported = false; private static Compatibility INSTANCE = null; private Compatibility() { TouchChecker checkTouch = new TouchChecker(); touchSupported = checkTouch.touchEnabled(); } public static Compatibility getInstance() { if (INSTANCE == null) { INSTANCE = new Compatibility(); } return INSTANCE; } private class TouchChecker extends Canvas { /** * Checks wheter pointer events are supported */ public boolean touchEnabled() { touchSupported = this.hasPointerEvents(); return touchSupported; } protected void paint(Graphics g) { } } }
gpl-2.0
christianchristensen/resin
modules/kernel/src/com/caucho/vfs/Jar.java
19795
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.vfs; import com.caucho.loader.EnvironmentLocal; import com.caucho.make.CachedDependency; import com.caucho.util.Alarm; import com.caucho.util.CacheListener; import com.caucho.util.Log; import com.caucho.util.LruCache; import com.caucho.util.L10N; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.security.cert.Certificate; import java.util.*; import java.util.jar.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; /** * Jar is a cache around a jar file to avoid scanning through the whole * file on each request. * * <p>When the Jar is created, it scans the file and builds a directory * of the Jar entries. */ public class Jar implements CacheListener { private static final Logger log = Log.open(Jar.class); private static final L10N L = new L10N(Jar.class); private static LruCache<Path,Jar> _jarCache; private static EnvironmentLocal<Integer> _jarSize = new EnvironmentLocal<Integer>("caucho.vfs.jar-size"); private Path _backing; private boolean _backingIsFile; private JarDepend _depend; // saved last modified time private long _lastModified; // saved length private long _length; // last time the file was checked private long _lastTime; // cached zip file to read jar entries private SoftReference<JarFile> _jarFileRef; // last time the zip file was modified private long _jarLastModified; private long _jarLength; private Boolean _isSigned; // file to be closed private SoftReference<JarFile> _closeJarFileRef; /** * Creates a new Jar. * * @param path canonical path */ private Jar(Path backing) { if (backing instanceof JarPath) throw new IllegalStateException(); _backing = backing; _backingIsFile = (_backing.getScheme().equals("file") && _backing.canRead()); } /** * Return a Jar for the path. If the backing already exists, return * the old jar. */ static Jar create(Path backing) { if (_jarCache == null) { int size = 256; Integer iSize = _jarSize.get(); if (iSize != null) size = iSize.intValue(); _jarCache = new LruCache<Path,Jar>(size); } Jar jar = _jarCache.get(backing); if (jar == null) { jar = new Jar(backing); jar = _jarCache.putIfNew(backing, jar); } return jar; } /** * Return a Jar for the path. If the backing already exists, return * the old jar. */ static Jar getJar(Path backing) { if (_jarCache != null) { Jar jar = _jarCache.get(backing); return jar; } return null; } /** * Return a Jar for the path. If the backing already exists, return * the old jar. */ public static PersistentDependency createDepend(Path backing) { Jar jar = create(backing); return jar.getDepend(); } /** * Return a Jar for the path. If the backing already exists, return * the old jar. */ public static PersistentDependency createDepend(Path backing, long digest) { Jar jar = create(backing); return new JarDigestDepend(jar.getJarDepend(), digest); } /** * Returns the backing path. */ Path getBacking() { return _backing; } /** * Returns the dependency. */ public PersistentDependency getDepend() { return getJarDepend(); } /** * Returns the dependency. */ private JarDepend getJarDepend() { if (_depend == null || _depend.isModified()) _depend = new JarDepend(new Depend(getBacking())); return _depend; } private boolean isSigned() { Boolean isSigned = _isSigned; if (isSigned != null) return isSigned; try { Manifest manifest = getManifest(); if (manifest == null) { _isSigned = Boolean.FALSE; return false; } Map<String,Attributes> entries = manifest.getEntries(); if (entries == null) { _isSigned = Boolean.FALSE; return false; } for (Attributes attr : entries.values()) { for (Object key : attr.keySet()) { String keyString = String.valueOf(key); if (keyString.contains("Digest")) { _isSigned = Boolean.TRUE; return true; } } } } catch (IOException e) { log.log(Level.FINE, e.toString(), e); } _isSigned = Boolean.FALSE; return false; } /** * Returns true if the entry is a file in the jar. * * @param path the path name inside the jar. */ public Manifest getManifest() throws IOException { Manifest manifest; synchronized (this) { JarFile jarFile = getJarFile(); if (jarFile == null) manifest = null; else manifest = jarFile.getManifest(); } closeJarFile(); return manifest; } /** * Returns any certificates. */ public Certificate []getCertificates(String path) { if (! isSigned()) return null; if (path.length() > 0 && path.charAt(0) == '/') path = path.substring(1); try { if (! _backing.canRead()) return null; JarFile jarFile = new JarFile(_backing.getNativePath()); JarEntry entry; InputStream is = null; try { entry = jarFile.getJarEntry(path); if (entry != null) { is = jarFile.getInputStream(entry); while (is.skip(65536) > 0) { } is.close(); return entry.getCertificates(); } } finally { jarFile.close(); } } catch (IOException e) { log.log(Level.FINE, e.toString(), e); return null; } return null; } /** * Returns true if the entry exists in the jar. * * @param path the path name inside the jar. */ public boolean exists(String path) { // server/249f, server/249g // XXX: facelets vs issue of meta-inf (i.e. lower case) boolean result = false; synchronized (this) { try { ZipEntry entry = getJarEntry(path); result = entry != null; } catch (IOException e) { log.log(Level.FINE, e.toString(), e); } } closeJarFile(); return result; } /** * Returns true if the entry is a directory in the jar. * * @param path the path name inside the jar. */ public boolean isDirectory(String path) { boolean result = false; synchronized (this) { try { ZipEntry entry = getJarEntry(path); result = entry != null && entry.isDirectory(); } catch (IOException e) { log.log(Level.FINE, e.toString(), e); } } closeJarFile(); return result; } /** * Returns true if the entry is a file in the jar. * * @param path the path name inside the jar. */ public boolean isFile(String path) { boolean result = false; synchronized (this) { try { ZipEntry entry = getJarEntry(path); result = entry != null && ! entry.isDirectory(); } catch (IOException e) { log.log(Level.FINE, e.toString(), e); } } closeJarFile(); return result; } /** * Returns the length of the entry in the jar file. * * @param path full path to the jar entry * @return the length of the entry */ public long getLastModified(String path) { long result = -1; synchronized (this) { try { ZipEntry entry = getJarEntry(path); result = entry != null ? entry.getTime() : -1; } catch (IOException e) { log.log(Level.FINE, e.toString(), e); } } closeJarFile(); return result; } /** * Returns the length of the entry in the jar file. * * @param path full path to the jar entry * @return the length of the entry */ public long getLength(String path) { long result = -1; synchronized (this) { try { ZipEntry entry = getJarEntry(path); result = entry != null ? entry.getSize() : -1; } catch (IOException e) { log.log(Level.FINE, e.toString(), e); } } closeJarFile(); return result; } /** * Readable if the jar is readable and the path refers to a file. */ public boolean canRead(String path) { boolean result = false; synchronized (this) { try { ZipEntry entry = getJarEntry(path); result = entry != null && ! entry.isDirectory(); } catch (IOException e) { log.log(Level.FINE, e.toString(), e); return false; } } closeJarFile(); return result; } /** * Can't write to jars. */ public boolean canWrite(String path) { return false; } /** * Lists all the files in this directory. */ public String []list(String path) throws IOException { // XXX: return new String[0]; } /** * Opens a stream to an entry in the jar. * * @param path relative path into the jar. */ public StreamImpl openReadImpl(Path path) throws IOException { String pathName = path.getPath(); if (pathName.length() > 0 && pathName.charAt(0) == '/') pathName = pathName.substring(1); ZipFile zipFile = new ZipFile(_backing.getNativePath()); ZipEntry entry; InputStream is = null; try { entry = zipFile.getEntry(pathName); if (entry != null) { is = zipFile.getInputStream(entry); return new ZipStreamImpl(zipFile, is, null, path); } else { throw new FileNotFoundException(path.toString()); } } finally { if (is == null) { zipFile.close(); } } } public String toString() { return _backing.toString(); } /** * Clears any cached JarFile. */ public void clearCache() { JarFile jarFile = null; synchronized (this) { SoftReference<JarFile> jarFileRef = _jarFileRef; _jarFileRef = null; if (jarFileRef != null) jarFile = jarFileRef.get(); } try { if (jarFile != null) jarFile.close(); } catch (Exception e) { } } private ZipEntry getJarEntry(String path) throws IOException { if (path.startsWith("/")) path = path.substring(1); JarFile jarFile = getJarFile(); if (jarFile != null) return jarFile.getJarEntry(path); else return null; } /** * Returns the Java ZipFile for this Jar. Accessing the entries with * the ZipFile is faster than scanning through them. * * getJarFile is not thread safe. */ private JarFile getJarFile() throws IOException { JarFile jarFile = null; isCacheValid(); SoftReference<JarFile> jarFileRef = _jarFileRef; if (jarFileRef != null) { jarFile = jarFileRef.get(); if (jarFile != null) return jarFile; } SoftReference<JarFile> oldJarRef = _jarFileRef; _jarFileRef = null; JarFile oldFile = null; if (oldJarRef == null) { } else if (_closeJarFileRef == null) _closeJarFileRef = oldJarRef; else oldFile = oldJarRef.get(); if (oldFile != null) { try { oldFile.close(); } catch (Throwable e) { e.printStackTrace(); } } if (_backingIsFile) { try { jarFile = new JarFile(_backing.getNativePath()); } catch (IOException ex) { if (log.isLoggable(Level.FINE)) log.log(Level.FINE, L.l("Error opening jar file '{0}'", _backing.getNativePath())); throw ex; } _jarFileRef = new SoftReference<JarFile>(jarFile); _jarLastModified = getLastModifiedImpl(); } return jarFile; } /** * Returns the last modified time for the path. * * @param path path into the jar. * * @return the last modified time of the jar in milliseconds. */ private long getLastModifiedImpl() { isCacheValid(); return _lastModified; } /** * Returns the last modified time for the path. * * @param path path into the jar. * * @return the last modified time of the jar in milliseconds. */ private boolean isCacheValid() { long now = Alarm.getCurrentTime(); if ((now - _lastTime < 1000) && ! Alarm.isTest()) return true; long oldLastModified = _lastModified; long oldLength = _length; _lastModified = _backing.getLastModified(); _length = _backing.getLength(); _lastTime = now; if (_lastModified == oldLastModified && _length == oldLength) return true; else { // If the file has changed, close the old file SoftReference<JarFile> oldFileRef = _jarFileRef; _jarFileRef = null; _jarLastModified = 0; _depend = null; _isSigned = null; JarFile oldCloseFile = null; if (_closeJarFileRef != null) oldCloseFile = _closeJarFileRef.get(); _closeJarFileRef = oldFileRef; if (oldCloseFile != null) { try { oldCloseFile.close(); } catch (Throwable e) { } } return false; } } /** * Closes any old jar waiting for close. */ private void closeJarFile() { JarFile jarFile = null; synchronized (this) { if (_closeJarFileRef != null) jarFile = _closeJarFileRef.get(); _closeJarFileRef = null; } if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { log.log(Level.WARNING, e.toString(), e); } } } public void close() { removeEvent(); } public void removeEvent() { JarFile jarFile = null; synchronized (this) { if (_jarFileRef != null) jarFile = _jarFileRef.get(); _jarFileRef = null; } try { if (jarFile != null) jarFile.close(); } catch (Throwable e) { log.log(Level.FINE, e.toString(), e); } closeJarFile(); } public boolean equals(Object o) { if (this == o) return true; else if (o == null || ! getClass().equals(o.getClass())) return false; Jar jar = (Jar) o; return _backing.equals(jar._backing); } /** * Clears all the cached files in the jar. Needed to avoid some * windows NT issues. */ public static void clearJarCache() { LruCache<Path,Jar> jarCache = _jarCache; if (jarCache == null) return; ArrayList<Jar> jars = new ArrayList<Jar>(); synchronized (jarCache) { Iterator<Jar> iter = jarCache.values(); while (iter.hasNext()) jars.add(iter.next()); } for (int i = 0; i < jars.size(); i++) { Jar jar = jars.get(i); if (jar != null) jar.clearCache(); } } /** * StreamImpl to read from a ZIP file. */ static class ZipStreamImpl extends StreamImpl { private ZipFile _zipFile; private InputStream _zis; private InputStream _is; /** * Create the new stream impl. * * @param zis the underlying zip stream. * @param is the backing stream. * @param path the path to the jar entry. */ ZipStreamImpl(ZipFile file, InputStream zis, InputStream is, Path path) { _zipFile = file; _zis = zis; _is = is; setPath(path); } /** * Returns true since this is a read stream. */ public boolean canRead() { return true; } public int getAvailable() throws IOException { if (_zis == null) return -1; else return _zis.available(); } public int read(byte []buf, int off, int len) throws IOException { int readLen = _zis.read(buf, off, len); return readLen; } public void close() throws IOException { ZipFile zipFile = _zipFile; _zipFile = null; InputStream zis = _zis; _zis = null; InputStream is = _is; _is = null; try { if (zis != null) zis.close(); } catch (Throwable e) { } try { if (zipFile != null) zipFile.close(); } catch (Throwable e) { } if (is != null) is.close(); } protected void finalize() throws IOException { close(); } } static class JarDepend extends CachedDependency implements PersistentDependency { private Depend _depend; private boolean _isDigestModified; /** * Create a new dependency. * * @param source the source file */ JarDepend(Depend depend) { _depend = depend; } /** * Create a new dependency. * * @param source the source file */ JarDepend(Depend depend, long digest) { _depend = depend; _isDigestModified = _depend.getDigest() != digest; } /** * Returns the underlying depend. */ Depend getDepend() { return _depend; } /** * Returns true if the dependency is modified. */ public boolean isModifiedImpl() { return _isDigestModified || _depend.isModified(); } /** * Returns true if the dependency is modified. */ public boolean logModified(Logger log) { return _depend.logModified(log); } /** * Returns the string to recreate the Dependency. */ public String getJavaCreateString() { String sourcePath = _depend.getPath().getPath(); long digest = _depend.getDigest(); return ("new com.caucho.vfs.Jar.createDepend(" + "com.caucho.vfs.Vfs.lookup(\"" + sourcePath + "\"), " + digest + "L)"); } public String toString() { return "Jar$JarDepend[" + _depend.getPath() + "]"; } } static class JarDigestDepend implements PersistentDependency { private JarDepend _jarDepend; private Depend _depend; private boolean _isDigestModified; /** * Create a new dependency. * * @param source the source file */ JarDigestDepend(JarDepend jarDepend, long digest) { _jarDepend = jarDepend; _depend = jarDepend.getDepend(); _isDigestModified = _depend.getDigest() != digest; } /** * Returns true if the dependency is modified. */ public boolean isModified() { return _isDigestModified || _jarDepend.isModified(); } /** * Returns true if the dependency is modified. */ public boolean logModified(Logger log) { return _depend.logModified(log) || _jarDepend.logModified(log); } /** * Returns the string to recreate the Dependency. */ public String getJavaCreateString() { String sourcePath = _depend.getPath().getPath(); long digest = _depend.getDigest(); return ("new com.caucho.vfs.Jar.createDepend(" + "com.caucho.vfs.Vfs.lookup(\"" + sourcePath + "\"), " + digest + "L)"); } } }
gpl-2.0
dquinteros/Pingeso
Amasy/Amasy-ejb/src/java/DTOs/AssistanceListCourseUnitDTO.java
1473
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package DTOs; import javax.ejb.Stateless; import javax.ejb.LocalBean; /** * * @author Pingeso */ @Stateless @LocalBean public class AssistanceListCourseUnitDTO { private String text; private boolean present; private boolean textAssistance; private boolean textRutName; private Long idBlockClass; private String assistanceState; public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isPresent() { return present; } public void setPresent(boolean present) { this.present = present; } public boolean isTextAssistance() { return textAssistance; } public void setTextAssistance(boolean textAssistance) { this.textAssistance = textAssistance; } public boolean isTextRutName() { return textRutName; } public void setTextRutName(boolean textRutName) { this.textRutName = textRutName; } public Long getIdBlockClass() { return idBlockClass; } public void setIdBlockClass(Long idBlockClass) { this.idBlockClass = idBlockClass; } public String getAssistanceState() { return assistanceState; } public void setAssistanceState(String assistanceState) { this.assistanceState = assistanceState; } }
gpl-2.0
jensnerche/plantuml
src/net/sourceforge/plantuml/sequencediagram/teoz/StairsPosition.java
1966
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML 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. * * PlantUML 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * Original Author: Arnaud Roques * * Revision $Revision: 6054 $ * */ package net.sourceforge.plantuml.sequencediagram.teoz; public class StairsPosition implements Comparable<StairsPosition> { private final double value; private final boolean destroy; public StairsPosition(double value, boolean destroy) { this.value = value; this.destroy = destroy; } @Override public String toString() { return "" + value + "-(" + destroy + ")"; } public double getValue() { return value; } public int compareTo(StairsPosition other) { if (this.value > other.value) { return 1; } if (this.value < other.value) { return -1; } return 0; } public boolean isDestroy() { return destroy; } }
gpl-2.0
deif2005/ices-school-v1.2
management/src/main/java/cn/mteach/management/controller/page/admin/QuestionPageAdmin.java
6879
package cn.mteach.management.controller.page.admin; import cn.mteach.common.domain.question.Field; import cn.mteach.common.domain.question.Question; import cn.mteach.common.domain.question.QuestionFilter; import cn.mteach.common.domain.question.QuestionQueryResult; import cn.mteach.common.util.Page; import cn.mteach.common.util.PagingUtil; import cn.mteach.common.util.QuestionAdapter; import cn.mteach.management.service.QuestionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @Controller public class QuestionPageAdmin { @Autowired private QuestionService questionService; @RequestMapping(value = "/admin/question/question-list", method = RequestMethod.GET) public String questionListPage(Model model) { return "redirect:question-list/filter-0-0-0-0-0-1.html"; } @RequestMapping(value = "/admin/question/question-list/filter-{fieldId}-{knowledge}-{questionType}-{tag}-{searchParam}-{page}.html", method = RequestMethod.GET) public String questionListFilterPage(Model model, @PathVariable("fieldId") int fieldId, @PathVariable("knowledge") int knowledge, @PathVariable("questionType") int questionType, @PathVariable("tag") int tag, @PathVariable("searchParam") String searchParam, @PathVariable("page") int page) { QuestionFilter qf = new QuestionFilter(); qf.setFieldId(fieldId); qf.setKnowledge(knowledge); qf.setQuestionType(questionType); qf.setTag(tag); if (searchParam.equals("0")) searchParam = "-1"; qf.setSearchParam(searchParam); Page<Question> pageModel = new Page<Question>(); pageModel.setPageNo(page); pageModel.setPageSize(10); //TODO 查找questionlist的时候需要tag List<Question> questionList = questionService.getQuestionList( pageModel, qf); String pageStr = PagingUtil.getPageBtnlink(page, pageModel.getTotalPage()); List<Field> fieldList = questionService.getAllField(null); model.addAttribute("fieldList", fieldList); /*if(fieldList.size() > 0) fieldId = fieldList.get(0).getFieldId();*/ model.addAttribute("knowledgeList", questionService.getKnowledgePointByFieldId(fieldId,null)); model.addAttribute("questionTypeList", questionService.getQuestionTypeList()); model.addAttribute("questionFilter", qf); model.addAttribute("questionList", questionList); model.addAttribute("pageStr", pageStr); model.addAttribute("tagList", questionService.getTags(null)); //保存筛选信息,删除后跳转页面时使用 model.addAttribute("fieldId", fieldId); model.addAttribute("knowledge", knowledge); model.addAttribute("questionType", questionType); model.addAttribute("searchParam", "-1".equals(searchParam)?"":searchParam); return "question-list"; } /** * 题库页面 * * @param model * @return */ @RequestMapping(value = "/admin/question/question-list/filterdialog-{fieldId}-{knowledge}-{questionType}-{searchParam}-{page}.html", method = RequestMethod.GET) public String questionListFilterDialogPage(Model model, @PathVariable("fieldId") int fieldId, @PathVariable("knowledge") int knowledge, @PathVariable("questionType") int questionType, @PathVariable("searchParam") String searchParam, @PathVariable("page") int page) { QuestionFilter qf = new QuestionFilter(); qf.setFieldId(fieldId); qf.setKnowledge(knowledge); qf.setQuestionType(questionType); if (searchParam.equals("0")) searchParam = "-1"; qf.setSearchParam(searchParam); Page<Question> pageModel = new Page<Question>(); pageModel.setPageNo(page); pageModel.setPageSize(20); List<Question> questionList = questionService.getQuestionList( pageModel, qf); String pageStr = PagingUtil.getPageBtnlink(page, pageModel.getTotalPage()); model.addAttribute("fieldList", questionService.getAllField(null)); model.addAttribute("knowledgeList", questionService.getKnowledgePointByFieldId(fieldId,null)); model.addAttribute("questionTypeList", questionService.getQuestionTypeList()); model.addAttribute("questionFilter", qf); model.addAttribute("questionList", questionList); model.addAttribute("pageStr", pageStr); //保存筛选信息,删除后跳转页面时使用 model.addAttribute("fieldId", fieldId); model.addAttribute("knowledge", knowledge); model.addAttribute("questionType", questionType); model.addAttribute("searchParam", searchParam); model.addAttribute("tagList", questionService.getTags(null)); return "question-list-dialog"; } /** * 添加试题页面 * * @param model * @return */ @RequestMapping(value = "/admin/question/question-add", method = RequestMethod.GET) public String questionAddPage(Model model) { List<Field> fieldList = questionService.getAllField(null); model.addAttribute("fieldList", fieldList); return "question-add"; } /** * 试题导入页面 * * @param model * @return */ @RequestMapping(value = "/admin/question/question-import", method = RequestMethod.GET) public String questionImportPage(Model model) { List<Field> fieldList = questionService.getAllField(null); model.addAttribute("fieldList", fieldList); return "question-import"; } @RequestMapping(value = "/admin/question/question-preview/{questionId}", method = RequestMethod.GET) public String questionPreviewPage(Model model, @PathVariable("questionId") int questionId, HttpServletRequest request){ String strUrl = "http://" + request.getServerName() //服务器地址 + ":" + request.getServerPort() + "/"; Question question = questionService.getQuestionByQuestionId(questionId); List<Integer> idList = new ArrayList<Integer>(); idList.add(questionId); List<QuestionQueryResult> questionQueryList = questionService.getQuestionDescribeListByIdList(idList); HashMap<Integer, QuestionQueryResult> questionMap = new HashMap<Integer, QuestionQueryResult>(); for (QuestionQueryResult qqr : questionQueryList) { if (questionMap.containsKey(qqr.getQuestionId())) { QuestionQueryResult a = questionMap.get(qqr.getQuestionId()); questionMap.put(qqr.getQuestionId(), a); } else { questionMap.put(qqr.getQuestionId(), qqr); } } QuestionAdapter adapter = new QuestionAdapter(question,null,questionMap.get(questionId),strUrl); String strHtml = adapter.getStringFromXML(true, false, true); model.addAttribute("strHtml", strHtml); model.addAttribute("question", question); return "question-preview"; } }
gpl-2.0
BiglySoftware/BiglyBT
uis/src/com/biglybt/ui/swt/views/DownloadActivityView.java
23037
/* * Created on 2 juil. 2003 * * Copyright (C) Azureus Software, Inc, All Rights Reserved. * * 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 ( see the LICENSE file ). * * 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 com.biglybt.ui.swt.views; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import com.biglybt.core.config.COConfigurationManager; import com.biglybt.core.config.ParameterListener; import com.biglybt.core.download.DownloadManager; import com.biglybt.core.download.DownloadManagerStats; import com.biglybt.core.internat.MessageText; import com.biglybt.core.util.DisplayFormatters; import com.biglybt.core.util.GeneralUtils; import com.biglybt.core.util.GeneralUtils.SmoothAverage; import com.biglybt.core.util.TimeFormatter; import com.biglybt.core.util.average.AverageFactory; import com.biglybt.core.util.average.MovingImmediateAverage; import com.biglybt.ui.common.ToolBarItem; import com.biglybt.ui.mdi.MdiEntry; import com.biglybt.ui.selectedcontent.SelectedContent; import com.biglybt.ui.selectedcontent.SelectedContentManager; import com.biglybt.ui.swt.Messages; import com.biglybt.ui.swt.TorrentUtil; import com.biglybt.ui.swt.Utils; import com.biglybt.ui.swt.components.Legend; import com.biglybt.ui.swt.components.graphics.MultiPlotGraphic; import com.biglybt.ui.swt.components.graphics.ValueFormater; import com.biglybt.ui.swt.components.graphics.ValueSource; import com.biglybt.ui.swt.mainwindow.Colors; import com.biglybt.ui.swt.mdi.MdiSWTMenuHackListener; import com.biglybt.ui.swt.mdi.TabbedEntry; import com.biglybt.ui.swt.pif.UISWTView; import com.biglybt.ui.swt.pif.UISWTViewEvent; import com.biglybt.ui.swt.pifimpl.UISWTViewCoreEventListener; import com.biglybt.pif.ui.UIPluginViewToolBarListener; /** * aka "Speed" sub view */ public class DownloadActivityView implements UISWTViewCoreEventListener, UIPluginViewToolBarListener, MdiSWTMenuHackListener, ParameterListener { public static final String MSGID_PREFIX = "DownloadActivityView"; private static Color[] mpg_colors = { Colors.fadedGreen, Colors.fadedGreen, Colors.blues[Colors.BLUES_DARKEST], Colors.blues[Colors.BLUES_DARKEST], Colors.light_grey }; private static final int ETA_AVERAGE_TICKS = 30; private static Color[] eta_colors = { Colors.fadedGreen, Colors.light_grey }; private UISWTView swtView; private boolean legend_at_bottom = true; private Composite panel; private boolean viewBuilt; private MultiPlotGraphic mpg; private MultiPlotGraphic eta; private List<DownloadManager> managers = new ArrayList<>(); private Composite parent; private boolean show_time = true; public DownloadActivityView() { } private String getFullTitle() { return( MessageText.getString(MSGID_PREFIX + ".title.full" )); } public void initialize( Composite parent ) { this.parent = parent; if ( panel == null || panel.isDisposed()){ viewBuilt = false; } panel = new Composite(parent,SWT.NULL); panel.setLayout( new FormLayout()); } private void fillPanel() { Utils.disposeComposite(panel, false); GridData gridData; // download graphic Composite mpg_panel = new Composite( panel, SWT.NULL ); { FormData formData = new FormData(); formData.left = new FormAttachment( 0, 0 ); formData.right = new FormAttachment( show_time?75:100, 0 ); formData.top = new FormAttachment( 0, 0 ); formData.bottom = new FormAttachment( 100, 0 ); mpg_panel.setLayoutData( formData ); mpg_panel.setLayout(new GridLayout(legend_at_bottom?1:2, false)); ValueFormater formatter = new ValueFormater() { @Override public String format( int value) { return DisplayFormatters.formatByteCountToKiBEtcPerSec( value ); } }; final ValueSourceImpl[] sources = { new ValueSourceImpl( "Up", 0, mpg_colors, true, false, false ) { @Override public int getValue() { List<DownloadManager> dms = managers; int res = 0; for ( DownloadManager dm: dms ){ DownloadManagerStats stats = dm.getStats(); res += (int)(stats.getDataSendRate()); } return( res ); } }, new ValueSourceImpl( "Up Smooth", 1, mpg_colors, true, false, true ) { @Override public int getValue() { List<DownloadManager> dms = managers; int res = 0; for ( DownloadManager dm: dms ){ DownloadManagerStats stats = dm.getStats(); res += (int)(stats.getSmoothedDataSendRate()); } return( res ); } }, new ValueSourceImpl( "Down", 2, mpg_colors, false, false, false ) { @Override public int getValue() { List<DownloadManager> dms = managers; int res = 0; for ( DownloadManager dm: dms ){ DownloadManagerStats stats = dm.getStats(); res += (int)(stats.getDataReceiveRate()); } return( res ); } }, new ValueSourceImpl( "Down Smooth", 3, mpg_colors, false, false, true ) { @Override public int getValue() { List<DownloadManager> dms = managers; int res = 0; for ( DownloadManager dm: dms ){ DownloadManagerStats stats = dm.getStats(); res += (int)(stats.getSmoothedDataReceiveRate()); } return( res ); } }, new ValueSourceImpl( "Swarm Peer Average", 4, mpg_colors, false, true, false ) { @Override public int getValue() { List<DownloadManager> dms = managers; int res = 0; for ( DownloadManager dm: dms ){ res += (int)(dm.getStats().getTotalAveragePerPeer()); } return( res ); } } }; if ( mpg != null ){ mpg.dispose(); } final MultiPlotGraphic f_mpg = mpg = MultiPlotGraphic.getInstance( sources, formatter ); String[] color_configs = new String[] { "DownloadActivityView.legend.up", "DownloadActivityView.legend.up_smooth", "DownloadActivityView.legend.down", "DownloadActivityView.legend.down_smooth", "DownloadActivityView.legend.peeraverage", }; Legend.LegendListener legend_listener = new Legend.LegendListener() { private int hover_index = -1; @Override public void hoverChange( boolean entry, int index ) { if ( hover_index != -1 ){ sources[hover_index].setHover( false ); } if ( entry ){ hover_index = index; sources[index].setHover( true ); } f_mpg.refresh( true ); } @Override public void visibilityChange( boolean visible, int index ) { sources[index].setVisible( visible ); f_mpg.refresh( true ); } }; if ( !legend_at_bottom ){ gridData = new GridData( GridData.FILL_VERTICAL ); gridData.verticalAlignment = SWT.CENTER; Legend.createLegendComposite(mpg_panel, mpg_colors, color_configs, null, gridData, false, legend_listener ); } Composite gSpeed = new Composite(mpg_panel,SWT.NULL); gridData = new GridData(GridData.FILL_BOTH); gSpeed.setLayoutData(gridData); gSpeed.setLayout(new GridLayout()); if ( legend_at_bottom ){ gridData = new GridData(GridData.FILL_HORIZONTAL); Legend.createLegendComposite(mpg_panel, mpg_colors, color_configs, null, gridData, true, legend_listener ); } Canvas speedCanvas = new Canvas(gSpeed,SWT.NO_BACKGROUND); gridData = new GridData(GridData.FILL_BOTH); speedCanvas.setLayoutData(gridData); mpg.initialize( speedCanvas, false ); } // time panel if ( show_time ){ Composite time_panel = new Composite( panel, SWT.NULL ); FormData formData = new FormData(); formData.left = new FormAttachment( mpg_panel, 0 ); formData.right = new FormAttachment( 100, 0 ); formData.top = new FormAttachment( 0, 0 ); formData.bottom = new FormAttachment( 100, 0 ); time_panel.setLayoutData( formData ); time_panel.setLayout(new GridLayout(legend_at_bottom?1:2, false)); ValueFormater formatter = new ValueFormater() { @Override public String format( int value) { return TimeFormatter.format( value ); } }; final ValueSourceImpl[] sources = { new ValueSourceImpl( "ETA", 0, eta_colors, ValueSource.STYLE_BLOB, false, false ) { @Override public int getValue() { List<DownloadManager> dms = managers; int res = 0; for ( DownloadManager dm: dms ){ DownloadManagerStats stats = dm.getStats(); res = Math.max( res, Math.max((int)(stats.getETA()), 0 )); } return( res ); } }, new ValueSourceImpl( "ETA Average", 1, eta_colors, ValueSource.STYLE_BLOB, true, false ) { @Override public int getValue() { return( eta.getAverage( ETA_AVERAGE_TICKS )[0]); } } }; if ( eta != null ){ eta.dispose(); } final MultiPlotGraphic f_eta = eta = MultiPlotGraphic.getInstance( 500, sources, formatter ); String[] color_configs = new String[] { "DownloadActivityView.legend.eta", "DownloadActivityView.legend.etaAverage", }; Legend.LegendListener legend_listener = new Legend.LegendListener() { private int hover_index = -1; @Override public void hoverChange( boolean entry, int index ) { if ( hover_index != -1 ){ sources[hover_index].setHover( false ); } if ( entry ){ hover_index = index; sources[index].setHover( true ); } f_eta.refresh( true ); } @Override public void visibilityChange( boolean visible, int index ) { sources[index].setVisible( visible ); f_eta.refresh( true ); } }; if ( !legend_at_bottom ){ gridData = new GridData( GridData.FILL_VERTICAL ); gridData.verticalAlignment = SWT.CENTER; Legend.createLegendComposite(time_panel, eta_colors, color_configs, null, gridData, false, legend_listener ); } Composite gSpeed = new Composite(time_panel,SWT.NULL); gridData = new GridData(GridData.FILL_BOTH); gSpeed.setLayoutData(gridData); gSpeed.setLayout(new GridLayout()); if ( legend_at_bottom ){ gridData = new GridData(GridData.FILL_HORIZONTAL); Legend.createLegendComposite(time_panel, eta_colors, color_configs, null, gridData, true, legend_listener ); } Canvas speedCanvas = new Canvas(gSpeed,SWT.NO_BACKGROUND); gridData = new GridData(GridData.FILL_BOTH); speedCanvas.setLayoutData(gridData); eta.initialize( speedCanvas, false ); } } private void refresh( boolean force ) { if ( mpg != null ){ mpg.refresh( force ); } if ( eta != null ){ eta.refresh( force ); } } public Composite getComposite() { return( panel ); } private boolean comp_visible; private Object visible_pending_ds; private void setVisible( boolean vis ) { if ( vis ){ comp_visible = true; dataSourceChanged( visible_pending_ds ); }else{ visible_pending_ds = managers; dataSourceChanged( null ); comp_visible = false; } } public void dataSourceChanged( Object newDataSource ) { if ( !comp_visible ){ visible_pending_ds = newDataSource; return; } List<DownloadManager> newManagers = ViewUtils.getDownloadManagersFromDataSource( newDataSource, managers ); if ( viewBuilt ){ if ( newManagers.size() == managers.size()){ boolean same = true; for ( int i=0;i<managers.size();i++){ if ( newManagers.get(i) != managers.get(i)){ same = false; break; } } if ( same ){ return; } } } managers = newManagers; viewBuilt = true; rebuild(); } private void rebuild() { Utils.execSWTThread(()->{ if ( panel == null || panel.isDisposed()){ return; } Utils.disposeComposite(panel, false); List<DownloadManager> dms = managers; if ( !dms.isEmpty()){ fillPanel(); parent.layout(true, true); int min_history_secs = Integer.MAX_VALUE; for ( DownloadManager dm: managers ){ DownloadManagerStats stats = dm.getStats(); stats.setRecentHistoryRetention( true ); int[][] _history = stats.getRecentHistory(); int[] send_history = _history[0]; min_history_secs = Math.min( min_history_secs, send_history.length ); } int[] t_recv = new int[min_history_secs]; int[] t_send = new int[min_history_secs]; int[] t_swarm_peer_av = new int[min_history_secs]; int[] t_eta = new int[min_history_secs]; for ( DownloadManager dm: managers ){ DownloadManagerStats stats = dm.getStats(); int[][] _history = stats.getRecentHistory(); // reconstitute the smoothed values to the best of our ability (good enough unless we decide we want // to throw more memory at remembering this more accurately...) int[] send_history = _history[0]; int[] recv_history = _history[1]; int[] sp_history = _history[2]; int[] eta_history = _history[3]; for ( int i=0;i<min_history_secs;i++){ t_send[i] += send_history[i]; t_recv[i] += recv_history[i]; t_swarm_peer_av[i] += sp_history[i]; t_eta[i] = Math.max( t_eta[i], eta_history[i]); } } int[] t_smoothed_recv = new int[min_history_secs]; int[] t_smoothed_send = new int[min_history_secs]; SmoothAverage send_average = GeneralUtils.getSmoothAverageForReplay(); SmoothAverage recv_average = GeneralUtils.getSmoothAverageForReplay(); int smooth_interval = GeneralUtils.getSmoothUpdateInterval(); int current_smooth_send = 0; int current_smooth_recv = 0; int pending_smooth_send = 0; int pending_smooth_recv = 0; for ( int i=0;i<min_history_secs;i++){ pending_smooth_send += t_send[i]; pending_smooth_recv += t_recv[i]; if ( i % smooth_interval == 0 ){ send_average.addValue( pending_smooth_send ); current_smooth_send = (int)send_average.getAverage(); recv_average.addValue( pending_smooth_recv ); current_smooth_recv = (int)recv_average.getAverage(); pending_smooth_send = 0; pending_smooth_recv = 0; } t_smoothed_send[i] = current_smooth_send; t_smoothed_recv[i] = current_smooth_recv; } int[][] mpg_history = { t_send, t_smoothed_send, t_recv, t_smoothed_recv, t_swarm_peer_av }; mpg.reset( mpg_history ); mpg.setActive( true ); // ETA Stuff if ( eta != null ){ int[] t_eta_average = new int[min_history_secs]; MovingImmediateAverage eta_average = AverageFactory.MovingImmediateAverage( ETA_AVERAGE_TICKS ); for ( int i=0;i<min_history_secs;i++ ){ eta_average.update( t_eta[i] ); t_eta_average[i] = (int)eta_average.getAverage(); } int[][] eta_history = { t_eta, t_eta_average }; eta.reset( eta_history ); eta.setActive( true ); } }else{ ViewUtils.setViewRequiresOneOrMoreDownloads( panel ); if ( mpg != null ){ mpg.setActive( false ); mpg.reset( new int[5][0] ); } if ( eta != null ){ eta.setActive( false ); eta.reset( new int[2][0] ); } } }); } @Override public void menuWillBeShown( MdiEntry entry, Menu menu) { MenuItem mi = new MenuItem( menu, SWT.CHECK ); mi.setSelection( show_time ); mi.setText( MessageText.getString( "ColumnProgressETA.showETA" )); mi.addListener( SWT.Selection, (ev)->{ COConfigurationManager.setParameter( "DownloadActivity.show.eta", !show_time ); }); new MenuItem( menu, SWT.SEPARATOR ); } @Override public void parameterChanged( String parameterName ) { show_time = COConfigurationManager.getBooleanParameter( "DownloadActivity.show.eta" ); rebuild(); } private void create() { swtView.setTitle(getFullTitle()); swtView.setToolBarListener(this); COConfigurationManager.addParameterListener( "DownloadActivity.show.eta", this ); show_time = COConfigurationManager.getBooleanParameter( "DownloadActivity.show.eta" ); if (swtView instanceof TabbedEntry) { TabbedEntry tabView = (TabbedEntry)swtView; tabView.addListener( this ); legend_at_bottom = tabView.getMDI().getAllowSubViews(); } } private void delete() { Utils.disposeComposite( panel ); COConfigurationManager.removeParameterListener( "DownloadActivity.show.eta", this ); if ( mpg != null ){ mpg.dispose(); mpg = null; } if ( eta != null ){ eta.dispose(); eta = null; } if ( swtView instanceof TabbedEntry ){ TabbedEntry tabView = (TabbedEntry)swtView; tabView.removeListener( this ); } } @Override public boolean eventOccurred( UISWTViewEvent event ) { switch( event.getType()){ case UISWTViewEvent.TYPE_CREATE:{ swtView = event.getView(); create(); break; } case UISWTViewEvent.TYPE_DESTROY:{ delete(); break; } case UISWTViewEvent.TYPE_INITIALIZE:{ initialize((Composite)event.getData()); break; } case UISWTViewEvent.TYPE_REFRESH:{ refresh( false ); break; } case UISWTViewEvent.TYPE_LANGUAGEUPDATE:{ Messages.updateLanguageForControl(getComposite()); swtView.setTitle(getFullTitle()); break; } case UISWTViewEvent.TYPE_DATASOURCE_CHANGED:{ dataSourceChanged(event.getData()); break; } case UISWTViewEvent.TYPE_SHOWN:{ String id = "DMDetails_DownloadGraph"; setVisible( true ); // do this here to pick up corrent manager before rest of code if ( managers != null ){ List<SelectedContent> sc = new ArrayList<>(); for ( DownloadManager dm: managers ){ sc.add( new SelectedContent( dm )); if ( dm.getTorrent() != null ){ id += "." + dm.getInternalName(); }else{ id += ":" + dm.getSize(); } } SelectedContentManager.changeCurrentlySelectedContent(id, sc.toArray( new SelectedContent[0] )); }else{ SelectedContentManager.changeCurrentlySelectedContent(id, null); } refresh( true ); break; } case UISWTViewEvent.TYPE_HIDDEN:{ setVisible( false ); SelectedContentManager.clearCurrentlySelectedContent(); break; } } return( true ); } /* (non-Javadoc) * @see com.biglybt.pif.ui.toolbar.UIToolBarActivationListener#toolBarItemActivated(ToolBarItem, long, java.lang.Object) */ @Override public boolean toolBarItemActivated(ToolBarItem item, long activationType, Object datasource) { return false; // default handler will handle it } /* (non-Javadoc) * @see com.biglybt.pif.ui.UIPluginViewToolBarListener#refreshToolBarItems(java.util.Map) */ @Override public void refreshToolBarItems(Map<String, Long> list) { Map<String, Long> states = TorrentUtil.calculateToolbarStates( SelectedContentManager.getCurrentlySelectedContent(), null); list.putAll(states); } private abstract static class ValueSourceImpl implements ValueSource { private String name; private int index; private Color[] colours; private int base_style; private boolean trimmable; private boolean is_hover; private boolean is_invisible; private boolean is_dotted; private ValueSourceImpl( String _name, int _index, Color[] _colours, boolean _is_up, boolean _trimmable, boolean _is_dotted ) { name = _name; index = _index; colours = _colours; trimmable = _trimmable; is_dotted = _is_dotted; base_style = _is_up?STYLE_UP:STYLE_DOWN; } private ValueSourceImpl( String _name, int _index, Color[] _colours, int _base_style, boolean _trimmable, boolean _is_dotted ) { name = _name; index = _index; colours = _colours; trimmable = _trimmable; is_dotted = _is_dotted; base_style = _base_style; } @Override public String getName() { return( name ); } @Override public Color getLineColor() { return( colours[index] ); } @Override public boolean isTrimmable() { return( trimmable ); } private void setHover( boolean h ) { is_hover = h; } private void setVisible( boolean visible ) { is_invisible = !visible; } @Override public int getStyle() { if ( is_invisible ){ return( STYLE_INVISIBLE ); } int style = base_style; if ( is_hover ){ style |= STYLE_BOLD; } if ( is_dotted ){ style |= STYLE_HIDE_LABEL; } return( style ); } @Override public int getAlpha() { return( is_dotted?128:255 ); } } }
gpl-2.0
lorenzopardini/uniformization
main/it/unifi/oris/sirio/uniformization/main/OldWeighter.java
1168
package it.unifi.oris.sirio.uniformization.main; import it.unifi.oris.sirio.models.gspn.*; import java.util.*; public class OldWeighter extends PoissonWeighterTechnique{ //Singleton Pattern private static PoissonWeighterTechnique istance = null; private OldWeighter(){}; protected static PoissonWeighterTechnique getIstance(){ if(OldWeighter.istance == null){ OldWeighter.istance = new OldWeighter(); } return OldWeighter.istance; } //End - Singleton protected DataContainer weighter(DataContainer myData){ // Copia difensiva, non sappiamo se il costruttore di Pair fa la copia difensiva Pair <Integer,Integer> LR = new Pair<Integer,Integer>(Integer.valueOf(myData.getL().intValue()),Integer.valueOf(myData.getR().intValue())); LinkedList<Double> weightList = TransientAndSteadyMatrixes.calculateConstants(LR, 1.0, myData.getLambda()); double[] w = new double[weightList.size()]; for (int i=0; i<weightList.size();i++){ w[i] = weightList.get(i).doubleValue(); } myData.setFoxGlynnWeights(w); return myData; } }
gpl-2.0
Sleenker/Code_Jam
Store Credit/console.java
3130
//------------------------------------------------------------------------------------------------------------------------------------------------- import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedReader; import java.util.StringTokenizer; //------------------------------------------------------------------------------------------------------------------------------------------------- /** * Engineered and developed by Jhonny Trejos Barrios. * Technology: Java. * Version: Java Development Kit 1.8.0_31, Standard Edition. * Development Environment: Sublime Text 3. * ------------------------------------------------------------------------------------------------------------------------------------------------ * ------------------------------------------------------------------------------------------------------------------------------------------------ * Additional Info. * * Source Code Target: * * * * Licence: Personal, not for commercial purposes. * Developer Contact: jtrejosb@live.com || jtrejosb@gmail.com || jtrejosb@icloud.com * Mobile: --. */ //------------------------------------------------------------------------------------------------------------------------------------------------- public class Console { FileReader FR; FileWriter FW; BufferedReader BR; //--------------------------------------------------------------------------------------------------------------------------------------------- public static void main( String[] args ) { new Console().calculateCredits(); } //--------------------------------------------------------------------------------------------------------------------------------------------- public void calculateCredits() { try { FR = new FileReader( "filePath/a-large-practice.in.txt" ); BR = new BufferedReader( FR ); FW = new FileWriter( "filePath/Output.txt" ); int cases = Integer.parseInt( BR.readLine() ); for( int c = 0; c < cases; c++ ) { int item1 = 1, item2 = 1, credits = Integer.parseInt( BR.readLine() ); int[] prices = new int[ Integer.parseInt( BR.readLine() ) ]; StringTokenizer tokens = new StringTokenizer( BR.readLine(), " " ); for( int i = 0; i < prices.length; i++ ) { prices[ i ] = Integer.parseInt( tokens.nextToken() ); } for( int i = 0; i < prices.length - 1; i++ ) { for( int j = i + 1; j < prices.length; j++ ) { if( prices[ i ] + prices[ j ] == credits ) { item1 = ( i + 1 ); item2 = ( j + 1 ); break; } } } System.out.println( "Case #" + ( c + 1 ) + ": " + item1 + " " + item2 ); FW.write( "Case #" + ( c + 1 ) + ": " + item1 + " " + item2 + "\n" ); } FW.close(); FR.close(); } catch( Exception e ) { e.printStackTrace(); } } //--------------------------------------------------------------------------------------------------------------------------------------------- } //-------------------------------------------------------------------------------------------------------------------------------------------------
gpl-2.0
carvalhomb/tsmells
sample/argouml/argouml/org/argouml/uml/ui/behavior/state_machines/ActionNewSignalEvent.java
2491
// $Id: ActionNewSignalEvent.java 8472 2005-07-03 09:48:47Z mvw $ // Copyright (c) 1996-2005 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui.behavior.state_machines; import org.argouml.i18n.Translator; import org.argouml.model.Model; /** * @since Dec 15, 2002 * @author jaap.branderhorst@xs4all.nl */ public class ActionNewSignalEvent extends ActionNewEvent { private static ActionNewSignalEvent singleton = new ActionNewSignalEvent(); /** * Constructor for ActionNewSignalEvent. */ protected ActionNewSignalEvent() { super(); putValue(NAME, Translator.localize("button.new-signalevent")); } /** * @see org.argouml.uml.ui.behavior.state_machines.ActionNewEvent#createEvent() */ protected Object createEvent(Object ns) { return Model.getStateMachinesFactory().buildSignalEvent(ns); } /** * @return Returns the singleton. */ public static ActionNewSignalEvent getSingleton() { return singleton; } }
gpl-2.0
Lythimus/lptv
apache-solr-3.6.0/solr/core/src/java/org/apache/solr/analysis/DictionaryCompoundWordTokenFilterFactory.java
3204
/** * 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.solr.analysis; import org.apache.lucene.analysis.CharArraySet; import org.apache.lucene.analysis.compound.*; import org.apache.solr.util.plugin.ResourceLoaderAware; import org.apache.solr.common.ResourceLoader; import org.apache.solr.common.SolrException; import org.apache.lucene.analysis.TokenStream; import java.util.Map; import java.io.IOException; /** * Factory for {@link DictionaryCompoundWordTokenFilter}. * <pre class="prettyprint" > * &lt;fieldType name="text_dictcomp" class="solr.TextField" positionIncrementGap="100"&gt; * &lt;analyzer&gt; * &lt;tokenizer class="solr.WhitespaceTokenizerFactory"/&gt; * &lt;filter class="solr.DictionaryCompoundWordTokenFilterFactory" dictionary="dictionary.txt" * minWordSize="5" minSubwordSize="2" maxSubwordSize="15" onlyLongestMatch="true"/&gt; * &lt;/analyzer&gt; * &lt;/fieldType&gt;</pre> * @version $Id: DictionaryCompoundWordTokenFilterFactory.java 1073344 2011-02-22 14:35:02Z koji $ */ public class DictionaryCompoundWordTokenFilterFactory extends BaseTokenFilterFactory implements ResourceLoaderAware { private CharArraySet dictionary; private String dictFile; private int minWordSize; private int minSubwordSize; private int maxSubwordSize; private boolean onlyLongestMatch; @Override public void init(Map<String, String> args) { super.init(args); assureMatchVersion(); dictFile = args.get("dictionary"); if (null == dictFile) { throw new SolrException( SolrException.ErrorCode.SERVER_ERROR, "Missing required parameter: dictionary"); } minWordSize= getInt("minWordSize",CompoundWordTokenFilterBase.DEFAULT_MIN_WORD_SIZE); minSubwordSize= getInt("minSubwordSize",CompoundWordTokenFilterBase.DEFAULT_MIN_SUBWORD_SIZE); maxSubwordSize= getInt("maxSubwordSize",CompoundWordTokenFilterBase.DEFAULT_MAX_SUBWORD_SIZE); onlyLongestMatch = getBoolean("onlyLongestMatch",true); } public void inform(ResourceLoader loader) { try { dictionary = super.getWordSet(loader, dictFile, false); } catch (IOException e) { throw new RuntimeException(e); } } public DictionaryCompoundWordTokenFilter create(TokenStream input) { return new DictionaryCompoundWordTokenFilter(luceneMatchVersion,input,dictionary,minWordSize,minSubwordSize,maxSubwordSize,onlyLongestMatch); } }
gpl-2.0
rcandidosilva/paas-iot-platform
iot-platform/src/main/java/platform/web/ide/widget/ui/UIPieComponent.java
1151
package platform.web.ide.widget.ui; import javax.enterprise.context.Dependent; import javax.inject.Named; import platform.model.Widget; import platform.model.WidgetType; /** * * @author rodrigo */ @Named @Dependent public class UIPieComponent implements WidgetComponent { private String widgetId; private String title; private Widget widget; public UIPieComponent(Widget widget) { this.widget = widget; } @Override public Object createComponent(String widgetId) { this.widgetId = widgetId; // TODO return null; } @Override public String getTitle() { return title; } @Override public void update() { // TODO } @Override public String getType() { return WidgetType.PIE; } @Override public Widget getWidget() { return widget; } @Override public void setService(Object service) { // TODO } @Override public void setWidgetId(String widgetId) { this.widgetId = widgetId; } @Override public String getWidgetId() { return widgetId; } }
gpl-2.0
SONIAGroup/S.O.N.I.A.
GATE_Developer_8.0/plugins/TermRaider/src/gate/termraider/bank/HyponymyTermbank.java
6726
/* * Copyright (c) 2008--2014, The University of Sheffield. See the file * COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt * * This file is part of GATE (see http://gate.ac.uk/), and is free * software, licenced under the GNU Library General Public License, * Version 2, June 1991 (in the distribution as file licence.html, * and also available at http://gate.ac.uk/gate/licence.html). * * $Id: HyponymyTermbank.java 17968 2014-05-11 16:37:34Z ian_roberts $ */ package gate.termraider.bank; import gate.Annotation; import gate.AnnotationSet; import gate.Document; import gate.FeatureMap; import gate.Utils; import gate.creole.metadata.CreoleParameter; import gate.creole.metadata.CreoleResource; import gate.gui.ActionsPublisher; import gate.termraider.modes.Normalization; import gate.termraider.util.ScoreType; import gate.termraider.util.Term; import gate.termraider.util.Utilities; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @CreoleResource(name = "HyponymyTermbank", icon = "termbank-lr.png", comment = "TermRaider Termbank derived from head/string hyponymy", helpURL = "http://gate.ac.uk/userguide/sec:creole:termraider:hyponymy") public class HyponymyTermbank extends AbstractTermbank implements ActionsPublisher { private static final long serialVersionUID = -2382834479385875682L; /* EXTRA CREOLE PARAMETERS */ protected List<String> inputHeadFeatures; private Normalization normalization; /* EXTRA DATA FOR ANALYSIS */ private Map<Term, Set<String>> termHeads; private Map<Term, Set<String>> termHyponyms; private ScoreType termFrequencyST, hyponymsST, localDocFrequencyST, rawScoreST; /* Methods for the debugging GUI to get the data */ public Map<Term, Set<String>> getTermHeads() { return this.termHeads; } public Map<Term, Set<String>> getTermHyponyms() { return this.termHyponyms; } private double calculateOneRawScore(Term term) { Integer hyponyms = Utilities.getStringSetFromMap(termHyponyms, term).size(); Integer docFreq = Utilities.getStringSetFromMap(termDocuments, term).size(); Utilities.setScoreTermValue(scores, hyponymsST, term, hyponyms); return docFreq.doubleValue() * (1.0F + hyponyms.doubleValue()); } protected void processDocument(Document document) { documentCount++; String documentSource = Utilities.sourceOrName(document); AnnotationSet candidates = document.getAnnotations(inputASName).get(inputAnnotationTypes); for (Annotation candidate : candidates) { Term term = makeTerm(candidate, document); FeatureMap features = candidate.getFeatures(); String head = Utils.stringFor(document, candidate); for (String key : inputHeadFeatures) { if (features.containsKey(key)) { head = features.get(key).toString(); break; } } Utilities.addToMapSet(termDocuments, term, documentSource); Utilities.addToMapSet(termHeads, term, head); Utilities.incrementScoreTermValue(scores, termFrequencyST, term, 1); } } public void calculateScores() { Set<Term> terms = termHeads.keySet(); Set<String> headsI, headsJ; for (Term termI : terms) { headsI = termHeads.get(termI); for (Term termJ : terms) { if (termJ.getTermString().contains(termI.getTermString()) && (! termI.equals(termJ))) { headsJ = termHeads.get(termJ); hyponymLoop: for (String headI : headsI) { for (String headJ : headsJ) { if (headI.endsWith(headJ)) { Utilities.addToMapSet(termHyponyms, termI, termJ.getTermString()); break hyponymLoop; } } } } } } for (Term term : terms) { this.languages.add(term.getLanguageCode()); this.types.add(term.getType()); double rawScore = calculateOneRawScore(term); double normalized = Normalization.calculate(normalization, rawScore); Utilities.setScoreTermValue(scores, rawScoreST, term, rawScore); Utilities.setScoreTermValue(scores, getDefaultScoreType(), term, normalized); int localDF = this.termDocuments.get(term).size(); Utilities.setScoreTermValue(scores, localDocFrequencyST, term, localDF); } if (debugMode) { System.out.println("Termbank: nbr of terms = " + termDocuments.size()); } } protected void resetScores() { scores = new HashMap<ScoreType, Map<Term,Number>>(); for (ScoreType st : scoreTypes) { scores.put(st, new HashMap<Term, Number>()); } termHeads = new HashMap<Term, Set<String>>(); termHyponyms = new HashMap<Term, Set<String>>(); termDocuments = new HashMap<Term, Set<String>>(); languages = new HashSet<String>(); types = new HashSet<String>(); } protected void initializeScoreTypes() { this.scoreTypes = new ArrayList<ScoreType>(); this.scoreTypes.add(new ScoreType(scoreProperty)); this.rawScoreST = new ScoreType(scoreProperty + RAW_SUFFIX); this.scoreTypes.add(rawScoreST); this.termFrequencyST = new ScoreType("termFrequency"); this.scoreTypes.add(termFrequencyST); this.hyponymsST = new ScoreType("hyponymCount"); this.scoreTypes.add(hyponymsST); this.localDocFrequencyST = new ScoreType("localDocFrequency"); this.scoreTypes.add(localDocFrequencyST); } /***** CREOLE PARAMETERS *****/ @CreoleParameter(comment = "Annotation features (in order) to be scanned as terms' heads") public void setInputHeadFeatures(List<String> list) { this.inputHeadFeatures = list; } public List<String> getInputHeadFeatures() { return this.inputHeadFeatures; } /* override default value from AbstractTermbank */ @CreoleParameter(defaultValue = "kyotoDomainRelevance") public void setScoreProperty(String name) { super.setScoreProperty(name); } @CreoleParameter(comment = "score normalization", defaultValue = "Sigmoid") public void setNormalization(Normalization mode) { this.normalization = mode; } public Normalization getNormalization() { return this.normalization; } @Override public Map<String, String> getMiscDataForGui() { Map<String, String> result = new HashMap<String, String>(); result.put("nbr of local documents", String.valueOf(this.documentCount)); result.put("nbr of terms", String.valueOf(this.getDefaultScores().size())); return result; } }
gpl-2.0
biblelamp/JavaEE
Spring.gb/lesson3/dbase/src/main/java/spring/config/AppConfig.java
2928
package spring.config; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import java.util.Properties; @Configuration public class AppConfig { @Bean(name="dataSource") public DataSource getDataSource(){ // источник данных DriverManagerDataSource dataSource = new DriverManagerDataSource(); // параметры подключения к базе данных dataSource.setDriverClassName("org.sqlite.JDBC"); dataSource.setUrl("jdbc:sqlite:mysqlite.db"); dataSource.setUsername(""); dataSource.setPassword(""); return dataSource; } @Bean(name="entityManagerFactory") public LocalContainerEntityManagerFactoryBean getEntityManager(){ // класса фабрики реализующей интерфейс FactoryBean<EntityManagerFactory> LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); // источник подключения factory.setDataSource(getDataSource()); // адаптера для конкретной реализации JPA, // указывает, какая библиотека будет использоваться в качестве постовщика factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); // указание пакета в котором находятся классы-сущности factory.setPackagesToScan("spring.domain"); //создание свойств для настройки Hibernate Properties jpaProperties = new Properties(); // диалект базы данных,необходимо для генерации запросов Hibernate к БД jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.SQLiteDialect"); // максимальная глубины связи(будет рассмотрено в след. уроке) jpaProperties.put("hibernate.max_fetch_depth", 3); // максимальное число строк, возвращаемых за один запрос из БД jpaProperties.put("hibernate.jdbc.fetch_size", 50); // максимальное число запросов при использовании пакетных операций jpaProperties.put("hibernate.jdbc.batch_size", 10); // включает логгирование jpaProperties.put("hibernate.show_sql", true); factory.setJpaProperties(jpaProperties); return factory; } }
gpl-2.0
aktion-hip/vif
org.hip.vif.core/src/org/hip/vif/core/bom/impl/JoinRatingsToQuestionHome.java
4474
/* This package is part of the application VIF. Copyright (C) 2009, Benno Luthiger 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 org.hip.vif.core.bom.impl; import java.sql.SQLException; import org.hip.kernel.bom.KeyObject; import org.hip.kernel.bom.QueryResult; import org.hip.kernel.bom.impl.JoinedDomainObjectHomeImpl; import org.hip.kernel.bom.impl.KeyObjectImpl; import org.hip.kernel.exc.VException; import org.hip.vif.core.bom.QuestionHome; /** Home to retrieve all questions that have to be rated during the same event. * * @author Luthiger Created: 30.08.2009 */ @SuppressWarnings("serial") public class JoinRatingsToQuestionHome extends JoinedDomainObjectHomeImpl { private final static String OBJECT_CLASS_NAME = "org.hip.vif.core.bom.impl.JoinRatingsToQuestion"; private final static String XML_OBJECT_DEF = "<?xml version='1.0' encoding='ISO-8859-1'?> " + "<joinedObjectDef objectName='JoinRatingsToQuestion' parent='org.hip.kernel.bom.ReadOnlyDomainObject' version='1.0'> " + " <columnDefs> " + " <columnDef columnName='" + RatingsQuestionHome.KEY_RATINGEVENTS_ID + "' domainObject='org.hip.vif.core.bom.impl.RatingsQuestion'/> \n" + " <columnDef columnName='" + QuestionHome.KEY_ID + "' domainObject='org.hip.vif.core.bom.impl.QuestionImpl'/> \n" + " <columnDef columnName='" + QuestionHome.KEY_QUESTION + "' domainObject='org.hip.vif.core.bom.impl.QuestionImpl'/> \n" + " <columnDef columnName='" + QuestionHome.KEY_QUESTION_DECIMAL + "' domainObject='org.hip.vif.core.bom.impl.QuestionImpl'/> \n" + " </columnDefs> " + " <joinDef joinType='EQUI_JOIN'> " + " <objectDesc objectClassName='org.hip.vif.core.bom.impl.RatingsQuestion'/> " + " <objectDesc objectClassName='org.hip.vif.core.bom.impl.QuestionImpl'/> " + " <joinCondition> " + " <columnDef columnName='" + RatingsQuestionHome.KEY_QUESTION_ID + "' domainObject='org.hip.vif.core.bom.impl.RatingsQuestion'/> \n" + " <columnDef columnName='" + QuestionHome.KEY_ID + "' domainObject='org.hip.vif.core.bom.impl.QuestionImpl'/> \n" + " </joinCondition> " + " </joinDef> " + "</joinedObjectDef>"; /** Returns the name of the objects which this home can create. * * @return java.lang.String */ @Override public String getObjectClassName() { return OBJECT_CLASS_NAME; } /** Returns the object definition string of the class managed by this home. * * @return java.lang.String */ @Override protected String getObjectDefString() { return XML_OBJECT_DEF; } /** Returns all questions that have to be rated during the specified rating events ID. * * @param inRatingEventsID Long * @return QueryResult * @throws VException * @throws SQLException */ public QueryResult getQuestionsToBeRated(final Long inRatingEventsID) throws VException, SQLException { final KeyObject lKey = new KeyObjectImpl(); lKey.setValue(RatingsHome.KEY_RATINGEVENTS_ID, inRatingEventsID); return select(lKey); } }
gpl-2.0
Daniel-Dos/DEITEL
Capitulo 4 Instruções de Controle_parte 1/EstudoDeCasoGUI/DrawPanelTest.java
706
package EstudoDeCasoGUI; //Aplicativo para exibir um DrawPanel import javax.swing.JFrame; public class DrawPanelTest { public static void main( String [] args ) { //cria um painel que contem nosso desenho DrawPanel panel = new DrawPanel() ; //cria um novo quadro para armazenar o painel JFrame application = new JFrame(); //configura o frame para ser encerrado quando ele é fechado. application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.add( panel ); //adiciona o painel ao frame application.setSize( 250 ,250 ) ; //configura o tamanho do Frame application.setVisible(true) ;//torna o frame visivel. }//fim de main }//fim da classe
gpl-2.0
Creativa3d/box3d
paquetesGUIx/src/utilesGUI/TextFieldCZ.java
9478
package utilesGUI; import java.awt.*; import java.awt.event.*; import utiles.*; import ListDatos.*; import utilesGUI.tiposTextos.ITipoTexto; import utilesGUI.tiposTextos.JTipoTextoEstandar; import utilesGUI.tiposTextos.KeyEventCZ; /**Componente de texto*/ public class TextFieldCZ extends TextField implements utilesGUI.tabla.IComponentParaTabla { public static int mlTipoDefectoCadenaBD = JTipoTextoEstandar.mclTextCadena; private ITipoTexto moTipo = new JTipoTextoEstandar(mlTipoDefectoCadenaBD); //efecto cuando coge el foco private Color moBackColorConFoco = new Color(51,255,255); private Color moBackColor = null; private Color moForeColorCambio = new Color(255,0,0); private Color moForeColorNormal = null; /**Constructor*/ public TextFieldCZ() { super(); enableEvents(AWTEvent.FOCUS_EVENT_MASK); enableEvents(AWTEvent.KEY_EVENT_MASK); enableEvents(AWTEvent.TEXT_EVENT_MASK); } /** * setValorOriginal * si el valor original es null, se anula el efecto * si el valor original es <> null se activa el efecto * @param psValor valor */ public void setValorOriginal(final String psValor){ moTipo.setTextOriginal(psValor); ponerColorSiCambio(); } /** * Valor original * @return el valor */ public String getValorOriginal(){ return moTipo.getTextOriginal(); } /**Color de letra si cambia el valor * @return color */ public Color getForeColorCambio(){ return moForeColorCambio; } /** * Color de letra si cambia el valor * @param poColor el color */ public void setForeColorCambio(Color poColor){ moForeColorCambio = poColor; ponerColorSiCambio(); } /** * devuelve el si el texto a cabiado y si hay un valor orioginal * @return si ha cambiado */ public boolean getTextoCambiado(){ return moTipo.isTextoCambiado(); } /**pone el color si el texto cambia con respecto al valor original*/ public void ponerColorSiCambio(){ if(!moTipo.isTextoCambiado()){ if(moForeColorNormal!=null){ setForeground(moForeColorNormal); } }else{ if(getForeColorCambio()!=getForeground()){ moForeColorNormal = getForeground(); } setForeground(getForeColorCambio()); } } /** * el tipo del textbox(numerico, texto, fecha, DNI) * @return tipo */ public int getTipo(){ return moTipo.getTipo(); } /** * establecemos el tipo del textbox(numerico, texto, fecha, DNI) * @param plTipo el tipo */ public void setTipo(final int plTipo){ setTipo(new JTipoTextoEstandar(plTipo)); } /** * establecemos el tipo del textbox * @param poTipo el tipo de texto */ public void setTipo(final ITipoTexto poTipo){ String lsTexto = moTipo.getText(); String lsTextoO = moTipo.getTextOriginal(); moTipo = poTipo; moTipo.setText(lsTexto); moTipo.setTextOriginal(lsTextoO); } /** * Estabecemos el tipo que viene directo de un JListDatos * y el tamaño del campo * @param plTipoBD tipo de Base datos(de JListDatos) * @param plTamano tamaño máximo */ public void setTipoBD(int plTipoBD, int plTamano){ setTipoBD(plTipoBD); if(plTamano>0){ setColumns(plTamano); } } /** * Estabecemos el tipo que viene directo de un JListDatos * @param plTipoBD tipo */ public void setTipoBD(final int plTipoBD){ switch(plTipoBD){ case JListDatos.mclTipoFecha: setTipo(JTipoTextoEstandar.mclTextFecha); break; case JListDatos.mclTipoNumeroDoble: setTipo(JTipoTextoEstandar.mclTextNumeroDoble); break; case JListDatos.mclTipoMoneda3Decimales: setTipo(JTipoTextoEstandar.mclTextMoneda3Decimales); break; case JListDatos.mclTipoMoneda: setTipo(JTipoTextoEstandar.mclTextMoneda); break; case JListDatos.mclTipoPorcentual3Decimales: setTipo(JTipoTextoEstandar.mclTextPorcentual3Decimales); break; case JListDatos.mclTipoPorcentual: setTipo(JTipoTextoEstandar.mclTextPorcentual); break; case JListDatos.mclTipoNumero: setTipo(JTipoTextoEstandar.mclTextNumeroEntero); break; default: setTipo(mlTipoDefectoCadenaBD); } } /** * color de fondo cuando tiene el foco * @return color */ public Color getBackColorConFoco(){ return moBackColorConFoco; } /** * color de fondo cuando tiene el foco * @param poColor color */ public void setBackColorConFoco(Color poColor){ moBackColorConFoco = poColor; } public void setBackground(Color poColor){ super.setBackground(poColor); moBackColor=poColor; } private void setBackgroundP(Color poColor){ super.setBackground(poColor); } protected void processFocusEvent(FocusEvent e){ boolean lbContinuar = true; int id = e.getID(); switch(id) { case FocusEvent.FOCUS_GAINED: super.setText(moTipo.getText()); moBackColor = getBackground(); setBackgroundP(moBackColorConFoco); setSelectionStart(0); setSelectionEnd(moTipo.getText().length()); break; case FocusEvent.FOCUS_LOST: setBackgroundP(moBackColor); String lsTexto = super.getText(); if (moTipo.isTipoCorrecto(lsTexto)) { moTipo.lostFocus(lsTexto); super.setText(moTipo.getTextFormateado()); }else{ lbContinuar = !moTipo.isTipoCorrectoObligatorio(); if(lbContinuar){ moTipo.lostFocus(lsTexto); super.setText(moTipo.getTextFormateado()); } utilesGUI.msgbox.JDialogo.showDialog(null, moTipo.getTextoError(lsTexto)); } //anulamos la seleccion para que solo haya un campo con todo seleccionado if(lbContinuar ){ setSelectionStart(0); setSelectionEnd(0); ponerColorSiCambio(); } break; default: } super.processFocusEvent(e); //no se hace esto pq en windows se mete en un bucle infinito // if(lbContinuar) // super.processFocusEvent(e); // else // this.requestFocus(); } public void forzarLostFocus(){ processFocusEvent(new FocusEvent(this, FocusEvent.FOCUS_LOST)); } /** * Devuelve si el texto que hay en el componente es del tipo correcto, según mlTipo * @return si es correcto */ public boolean isTipoCorrecto(){ return moTipo.isTipoCorrecto(moTipo.getText()); } protected void processKeyEvent(final KeyEvent e){ int id = e.getID(); switch(id) { case KeyEvent.KEY_TYPED: KeyEventCZ loKey = new KeyEventCZ(e.getKeyChar()); moTipo.getTecla(super.getText(),loKey); e.setKeyChar(loKey.getKeyChar()); break; case KeyEvent.KEY_PRESSED: if(e.getKeyCode()==e.VK_ENTER){ e.setKeyCode(0); transferFocus(); } if(e.getKeyCode()==e.VK_ESCAPE){ e.setKeyCode(0); moTipo.restaurarTexto(); super.setText(moTipo.getText()); } break; case KeyEvent.KEY_RELEASED: break; default: } super.processKeyEvent(e); } protected void processTextEvent(TextEvent e) { int id = e.getID(); switch (id) { case TextEvent.TEXT_VALUE_CHANGED: ponerColorSiCambio(); break; default: } super.processTextEvent(e); } /**Devuelve el valor actual*/ public Object getValueTabla() { return getText(); } public String getText() { return moTipo.getText(); } public void setText(final String t) { moTipo.setText(t); super.setText(moTipo.getTextFormateado()); } /** * Establece el valor del text y el valor original, para lo del cambio de color si cambia * @param poValor valor */ public void setValueTabla(final Object poValor) { String lsValor; if(poValor==null){ lsValor = ""; }else{ lsValor = poValor.toString(); } moTipo.setText(lsValor); moTipo.setTextOriginal(moTipo.getText()); super.setText(moTipo.getTextFormateado()); } }
gpl-2.0
thuri/OpenLogbook
Android/src/net/lueckonline/android/openlogbook/activities/base/BaseActivity.java
2303
/** * OpenLogbook - App logging driven distances and times * Copyright (C) 2012 Michael Lück * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.lueckonline.android.openlogbook.activities.base; import gueei.binding.app.BindingActivity; import net.lueckonline.android.openlogbook.dataaccess.ILogbookRepository; import net.lueckonline.android.openlogbook.dataaccess.RepositoryFactory; import net.lueckonline.android.openlogbook.viewmodels.common.FinishDelegate; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; /** * @author thuri * */ public abstract class BaseActivity extends BindingActivity implements FinishDelegate { private ILogbookRepository repository; private AlertDialog.Builder okAlert; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.repository = RepositoryFactory.getInstance(getApplicationContext()); okAlert = new AlertDialog.Builder(this); okAlert.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); } @Override public void Finish() { this.finish(); } public void Finish(boolean condition, String message){ if(condition) this.finish(); else { getOkAlert().setMessage(message); getOkAlert().create().show(); } } public ILogbookRepository getRepository(){ return this.repository; } public AlertDialog.Builder getOkAlert() { return okAlert; } }
gpl-2.0
smeny/JPC
src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/vm/fdiv_ST2_ST2.java
2124
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package com.github.smeny.jpc.emulator.execution.opcodes.vm; import com.github.smeny.jpc.emulator.execution.*; import com.github.smeny.jpc.emulator.execution.decoder.*; import com.github.smeny.jpc.emulator.processor.*; import com.github.smeny.jpc.emulator.processor.fpu64.*; import static com.github.smeny.jpc.emulator.processor.Processor.*; public class fdiv_ST2_ST2 extends Executable { public fdiv_ST2_ST2(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double freg0 = cpu.fpu.ST(2); double freg1 = cpu.fpu.ST(2); if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1))) cpu.fpu.setInvalidOperation(); if ((freg0 == 0.0) && !Double.isNaN(freg1) && !Double.isInfinite(freg1)) cpu.fpu.setZeroDivide(); cpu.fpu.setST(2, freg0/freg1); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
unktomi/form-follows-function
f3_fmod/NativeFmodEx/Src/NativeFmodEx/Java/org/jouvieje/FmodEx/Enumerations/FMOD_TAGTYPE.java
7356
/** * NativeFmodEx Project * * Want to use FMOD Ex API (www.fmod.org) in the Java language ? NativeFmodEx is made for you. * Copyright © 2005-2008 Jérôme JOUVIE (Jouvieje) * * Created on 23 feb. 2005 * @version file v1.0.0 * @author Jérôme JOUVIE (Jouvieje) * * * WANT TO CONTACT ME ? * E-mail : * jerome.jouvie@gmail.com * My web sites : * http://jerome.jouvie.free.fr/ * * * INTRODUCTION * FMOD Ex is an API (Application Programming Interface) that allow you to use music * and creating sound effects with a lot of sort of musics. * FMOD is at : * http://www.fmod.org/ * The reason of this project is that FMOD Ex can't be used direcly with Java, so I've created * this project to do this. * * * GNU LESSER GENERAL PUBLIC LICENSE * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the * Free Software Foundation, Inc., * 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package org.jouvieje.FmodEx.Enumerations; import org.jouvieje.FmodEx.*; import org.jouvieje.FmodEx.Exceptions.*; import org.jouvieje.FmodEx.Callbacks.*; import org.jouvieje.FmodEx.*; import org.jouvieje.FmodEx.Defines.*; import org.jouvieje.FmodEx.Enumerations.*; import org.jouvieje.FmodEx.Structures.*; import java.nio.*; import org.jouvieje.FmodEx.Misc.*; import org.jouvieje.FmodEx.System; import java.util.HashMap; /** * <BR> * <BR> * List of tag types that could be stored within a sound. These include id3 tags, metadata from netstreams and vorbis/asf data.<BR> * <BR> * <BR><U><B>Remarks</B></U><BR><BR> * <BR> * <BR><U><B>Platforms Supported</B></U><BR><BR> * Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii, Solaris<BR> * <BR> * <BR><U><B>See Also</B></U><BR><BR> * Sound::getTag<BR> * */ public class FMOD_TAGTYPE implements Enumeration, Comparable { /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_UNKNOWN = new FMOD_TAGTYPE("FMOD_TAGTYPE_UNKNOWN", 0); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_ID3V1 = new FMOD_TAGTYPE("FMOD_TAGTYPE_ID3V1", EnumerationJNI.get_FMOD_TAGTYPE_ID3V1()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_ID3V2 = new FMOD_TAGTYPE("FMOD_TAGTYPE_ID3V2", EnumerationJNI.get_FMOD_TAGTYPE_ID3V2()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_VORBISCOMMENT = new FMOD_TAGTYPE("FMOD_TAGTYPE_VORBISCOMMENT", EnumerationJNI.get_FMOD_TAGTYPE_VORBISCOMMENT()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_SHOUTCAST = new FMOD_TAGTYPE("FMOD_TAGTYPE_SHOUTCAST", EnumerationJNI.get_FMOD_TAGTYPE_SHOUTCAST()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_ICECAST = new FMOD_TAGTYPE("FMOD_TAGTYPE_ICECAST", EnumerationJNI.get_FMOD_TAGTYPE_ICECAST()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_ASF = new FMOD_TAGTYPE("FMOD_TAGTYPE_ASF", EnumerationJNI.get_FMOD_TAGTYPE_ASF()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_MIDI = new FMOD_TAGTYPE("FMOD_TAGTYPE_MIDI", EnumerationJNI.get_FMOD_TAGTYPE_MIDI()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_PLAYLIST = new FMOD_TAGTYPE("FMOD_TAGTYPE_PLAYLIST", EnumerationJNI.get_FMOD_TAGTYPE_PLAYLIST()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_FMOD = new FMOD_TAGTYPE("FMOD_TAGTYPE_FMOD", EnumerationJNI.get_FMOD_TAGTYPE_FMOD()); /** */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_USER = new FMOD_TAGTYPE("FMOD_TAGTYPE_USER", EnumerationJNI.get_FMOD_TAGTYPE_USER()); /** Maximum number of tag types supported. */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_MAX = new FMOD_TAGTYPE("FMOD_TAGTYPE_MAX", EnumerationJNI.get_FMOD_TAGTYPE_MAX()); /** Makes sure this enum is signed 32bit. */ public final static FMOD_TAGTYPE FMOD_TAGTYPE_FORCEINT = new FMOD_TAGTYPE("FMOD_TAGTYPE_FORCEINT", 65536); private final static HashMap VALUES = new HashMap(2*13); static { VALUES.put(new Integer(FMOD_TAGTYPE_UNKNOWN.asInt()), FMOD_TAGTYPE_UNKNOWN); VALUES.put(new Integer(FMOD_TAGTYPE_ID3V1.asInt()), FMOD_TAGTYPE_ID3V1); VALUES.put(new Integer(FMOD_TAGTYPE_ID3V2.asInt()), FMOD_TAGTYPE_ID3V2); VALUES.put(new Integer(FMOD_TAGTYPE_VORBISCOMMENT.asInt()), FMOD_TAGTYPE_VORBISCOMMENT); VALUES.put(new Integer(FMOD_TAGTYPE_SHOUTCAST.asInt()), FMOD_TAGTYPE_SHOUTCAST); VALUES.put(new Integer(FMOD_TAGTYPE_ICECAST.asInt()), FMOD_TAGTYPE_ICECAST); VALUES.put(new Integer(FMOD_TAGTYPE_ASF.asInt()), FMOD_TAGTYPE_ASF); VALUES.put(new Integer(FMOD_TAGTYPE_MIDI.asInt()), FMOD_TAGTYPE_MIDI); VALUES.put(new Integer(FMOD_TAGTYPE_PLAYLIST.asInt()), FMOD_TAGTYPE_PLAYLIST); VALUES.put(new Integer(FMOD_TAGTYPE_FMOD.asInt()), FMOD_TAGTYPE_FMOD); VALUES.put(new Integer(FMOD_TAGTYPE_USER.asInt()), FMOD_TAGTYPE_USER); VALUES.put(new Integer(FMOD_TAGTYPE_MAX.asInt()), FMOD_TAGTYPE_MAX); VALUES.put(new Integer(FMOD_TAGTYPE_FORCEINT.asInt()), FMOD_TAGTYPE_FORCEINT); } private final String name; private final int nativeValue; private FMOD_TAGTYPE(String name, int nativeValue) { this.name = name; this.nativeValue = nativeValue; } public int asInt() { return nativeValue; } public String toString() { return name; } public boolean equals(Object object) { if(object instanceof FMOD_TAGTYPE) return asInt() == ((FMOD_TAGTYPE)object).asInt(); return false; } public int compareTo(Object object) { return asInt() - ((FMOD_TAGTYPE)object).asInt(); } /** * Retrieve a FMOD_TAGTYPE enum field with his integer value * @param nativeValue the integer value of the field to retrieve * @return the FMOD_TAGTYPE enum field that correspond to the integer value */ public static FMOD_TAGTYPE get(int nativeValue) { return (FMOD_TAGTYPE)VALUES.get(new Integer(nativeValue)); } /** * Retrieve a FMOD_TAGTYPE enum field from a Pointer * @param pointer a pointer holding an FMOD_TAGTYPE enum field * @return the FMOD_TAGTYPE enum field that correspond to the enum field in the pointer */ public static FMOD_TAGTYPE get(Pointer pointer) { return get(pointer.asInt()); } /** * @return an <code>Iterator</code> over the elements in this enumeration.<BR> * Can be cast to <code>Iterator<FMOD_TAGTYPE></code> in Java 1.5. */ public static java.util.Iterator iterator() { return new java.util.Iterator(){ private java.util.Iterator i = VALUES.values().iterator(); //Wrapper of the HashMap iterator public boolean hasNext() { return i.hasNext(); } public Object next() { return i.next(); } public void remove() { throw new UnsupportedOperationException(); } }; } }
gpl-2.0
arthurmelo88/palmetalADP
adempierelbr/dbPort/src/org/adempierelbr/model/X_LBR_TaxConfig_ProductGroup.java
8553
/****************************************************************************** * Product: AdempiereLBR ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.adempierelbr.model; import java.sql.ResultSet; import java.util.Properties; import org.compiere.model.*; /** Generated Model for LBR_TaxConfig_ProductGroup * @author ADempiereLBR (generated) * @version Release 3.6.0LTS - $Id$ */ public class X_LBR_TaxConfig_ProductGroup extends PO implements I_LBR_TaxConfig_ProductGroup, I_Persistent { /** * */ private static final long serialVersionUID = 20110202L; /** Standard Constructor */ public X_LBR_TaxConfig_ProductGroup (Properties ctx, int LBR_TaxConfig_ProductGroup_ID, String trxName) { super (ctx, LBR_TaxConfig_ProductGroup_ID, trxName); /** if (LBR_TaxConfig_ProductGroup_ID == 0) { setLBR_TaxConfig_ProductGroup_ID (0); setLBR_TaxConfiguration_ID (0); setLBR_Tax_ID (0); } */ } /** Load Constructor */ public X_LBR_TaxConfig_ProductGroup (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_LBR_TaxConfig_ProductGroup[") .append(get_ID()).append("]"); return sb.toString(); } public org.adempierelbr.model.I_LBR_FiscalGroup_Product getLBR_FiscalGroup_Product() throws RuntimeException { return (org.adempierelbr.model.I_LBR_FiscalGroup_Product)MTable.get(getCtx(), org.adempierelbr.model.I_LBR_FiscalGroup_Product.Table_Name) .getPO(getLBR_FiscalGroup_Product_ID(), get_TrxName()); } /** Set Fiscal Group - Product. @param LBR_FiscalGroup_Product_ID Primary key table LBR_FiscalGroup_Product */ public void setLBR_FiscalGroup_Product_ID (int LBR_FiscalGroup_Product_ID) { throw new IllegalArgumentException ("LBR_FiscalGroup_Product_ID is virtual column"); } /** Get Fiscal Group - Product. @return Primary key table LBR_FiscalGroup_Product */ public int getLBR_FiscalGroup_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LBR_FiscalGroup_Product_ID); if (ii == null) return 0; return ii.intValue(); } public org.adempierelbr.model.I_LBR_LegalMessage getLBR_LegalMessage() throws RuntimeException { return (org.adempierelbr.model.I_LBR_LegalMessage)MTable.get(getCtx(), org.adempierelbr.model.I_LBR_LegalMessage.Table_Name) .getPO(getLBR_LegalMessage_ID(), get_TrxName()); } /** Set Legal Message. @param LBR_LegalMessage_ID Defines the Legal Message */ public void setLBR_LegalMessage_ID (int LBR_LegalMessage_ID) { if (LBR_LegalMessage_ID < 1) set_Value (COLUMNNAME_LBR_LegalMessage_ID, null); else set_Value (COLUMNNAME_LBR_LegalMessage_ID, Integer.valueOf(LBR_LegalMessage_ID)); } /** Get Legal Message. @return Defines the Legal Message */ public int getLBR_LegalMessage_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LBR_LegalMessage_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Product Group Exception. @param LBR_TaxConfig_ProductGroup_ID Primary key table LBR_TaxConfig_ProductGroup */ public void setLBR_TaxConfig_ProductGroup_ID (int LBR_TaxConfig_ProductGroup_ID) { if (LBR_TaxConfig_ProductGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_LBR_TaxConfig_ProductGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_LBR_TaxConfig_ProductGroup_ID, Integer.valueOf(LBR_TaxConfig_ProductGroup_ID)); } /** Get Product Group Exception. @return Primary key table LBR_TaxConfig_ProductGroup */ public int getLBR_TaxConfig_ProductGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LBR_TaxConfig_ProductGroup_ID); if (ii == null) return 0; return ii.intValue(); } public org.adempierelbr.model.I_LBR_TaxConfiguration getLBR_TaxConfiguration() throws RuntimeException { return (org.adempierelbr.model.I_LBR_TaxConfiguration)MTable.get(getCtx(), org.adempierelbr.model.I_LBR_TaxConfiguration.Table_Name) .getPO(getLBR_TaxConfiguration_ID(), get_TrxName()); } /** Set Tax Configuration. @param LBR_TaxConfiguration_ID Primary key table LBR_TaxConfiguration */ public void setLBR_TaxConfiguration_ID (int LBR_TaxConfiguration_ID) { if (LBR_TaxConfiguration_ID < 1) set_ValueNoCheck (COLUMNNAME_LBR_TaxConfiguration_ID, null); else set_ValueNoCheck (COLUMNNAME_LBR_TaxConfiguration_ID, Integer.valueOf(LBR_TaxConfiguration_ID)); } /** Get Tax Configuration. @return Primary key table LBR_TaxConfiguration */ public int getLBR_TaxConfiguration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LBR_TaxConfiguration_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Brazilian Tax. @param LBR_Tax_ID Primary key table LBR_Tax */ public void setLBR_Tax_ID (int LBR_Tax_ID) { if (LBR_Tax_ID < 1) set_Value (COLUMNNAME_LBR_Tax_ID, null); else set_Value (COLUMNNAME_LBR_Tax_ID, Integer.valueOf(LBR_Tax_ID)); } /** Get Brazilian Tax. @return Primary key table LBR_Tax */ public int getLBR_Tax_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LBR_Tax_ID); if (ii == null) return 0; return ii.intValue(); } /** lbr_TaxStatus AD_Reference_ID=1000029 */ public static final int LBR_TAXSTATUS_AD_Reference_ID=1000029; /** 00 - Tributada integralmente = 00 */ public static final String LBR_TAXSTATUS_00_TributadaIntegralmente = "00"; /** 10 - Tributada e com cobranca do ICMS por Sub. Tributaria = 10 */ public static final String LBR_TAXSTATUS_10_TributadaEComCobrancaDoICMSPorSubTributaria = "10"; /** 20 - Com reducao de base de calculo = 20 */ public static final String LBR_TAXSTATUS_20_ComReducaoDeBaseDeCalculo = "20"; /** 30 - Isenta ou nao-trib. e com cobr. do ICMS por Sub. Tribut = 30 */ public static final String LBR_TAXSTATUS_30_IsentaOuNao_TribEComCobrDoICMSPorSubTribut = "30"; /** 40 - Isenta = 40 */ public static final String LBR_TAXSTATUS_40_Isenta = "40"; /** 41 - Nao-tributada = 41 */ public static final String LBR_TAXSTATUS_41_Nao_Tributada = "41"; /** 50 - Suspensao = 50 */ public static final String LBR_TAXSTATUS_50_Suspensao = "50"; /** 51 - Diferimento = 51 */ public static final String LBR_TAXSTATUS_51_Diferimento = "51"; /** 60 - ICMS cobrado anteriormente por substituicao tributaria = 60 */ public static final String LBR_TAXSTATUS_60_ICMSCobradoAnteriormentePorSubstituicaoTributaria = "60"; /** 70 - Com red. de base de calc. e cobr. do ICMS por Sub. Trib = 70 */ public static final String LBR_TAXSTATUS_70_ComRedDeBaseDeCalcECobrDoICMSPorSubTrib = "70"; /** 90 - Outras = 90 */ public static final String LBR_TAXSTATUS_90_Outras = "90"; /** Set Tax Status. @param lbr_TaxStatus Defines the Tax Status */ public void setlbr_TaxStatus (String lbr_TaxStatus) { set_Value (COLUMNNAME_lbr_TaxStatus, lbr_TaxStatus); } /** Get Tax Status. @return Defines the Tax Status */ public String getlbr_TaxStatus () { return (String)get_Value(COLUMNNAME_lbr_TaxStatus); } }
gpl-2.0
Nolane/stacks
app/src/main/java/com/nolane/stacks/provider/Stack.java
4660
package com.nolane.stacks.provider; import android.database.Cursor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.nolane.stacks.utils.GeneralUtils; import java.io.Serializable; import static com.nolane.stacks.provider.CardsDatabase.StacksColumns.STACK_COLOR; import static com.nolane.stacks.provider.CardsDatabase.StacksColumns.STACK_COUNT_CARDS; import static com.nolane.stacks.provider.CardsDatabase.StacksColumns.STACK_COUNT_IN_LEARNING; import static com.nolane.stacks.provider.CardsDatabase.StacksColumns.STACK_ID; import static com.nolane.stacks.provider.CardsDatabase.StacksColumns.STACK_LANGUAGE; import static com.nolane.stacks.provider.CardsDatabase.StacksColumns.STACK_MAX_IN_LEARNING; import static com.nolane.stacks.provider.CardsDatabase.StacksColumns.STACK_TITLE; public class Stack implements Serializable { public static class StackFactory implements CursorWrapper.ModelFactory<Stack> { private int id; private int title; private int maxInLearning; private int countCards; private int countInLearning; private int language; private int color; @Override public void prepare(@NonNull Cursor c) { id = c.getColumnIndex(STACK_ID); if (-1 == id) { throw new IllegalArgumentException("Each query must request id column."); } title = c.getColumnIndex(STACK_TITLE); maxInLearning = c.getColumnIndex(STACK_MAX_IN_LEARNING); countCards = c.getColumnIndex(STACK_COUNT_CARDS); countInLearning = c.getColumnIndex(STACK_COUNT_IN_LEARNING); language = c.getColumnIndex(STACK_LANGUAGE); color = c.getColumnIndex(STACK_COLOR); } @Override @NonNull public Stack wrapRow(@NonNull Cursor c) { return new Stack( c.getLong(id), -1 != title ? c.getString(title) : null, -1 != maxInLearning ? c.getInt(maxInLearning) : null, -1 != countCards ? c.getInt(countCards) : null, -1 != countInLearning ? c.getInt(countInLearning) : null, -1 != language ? c.getString(language) : null, -1 != color ? c.getInt(color) : null ); } } private static final int MAX_TITLE_LEN = 30; public static boolean checkTitle(@NonNull CharSequence title) { return title.length() <= MAX_TITLE_LEN; } private static final int MAX_LANGUAGE_LEN = 20; public static boolean checkLanguage(@NonNull CharSequence language) { return language.length() < MAX_LANGUAGE_LEN; } @NonNull public final Long id; @Nullable public final String title; @Nullable public final Integer maxInLearning; @Nullable public final Integer countCards; @Nullable public final Integer countInLearning; @Nullable public final String language; @Nullable public final Integer color; public Stack(@NonNull Long id, @Nullable String title, @Nullable Integer maxInLearning, @Nullable Integer countCards, @Nullable Integer countInLearning, @Nullable String language, @Nullable Integer color) { if ((null != title) && !checkTitle(title)) { throw new IllegalArgumentException("Title is too long."); } if ((null != language) && !checkLanguage(language)) { throw new IllegalArgumentException("Language is too long."); } this.id = id; this.title = title; this.maxInLearning = maxInLearning; this.countCards = countCards; this.countInLearning = countInLearning; this.language = language; this.color = color; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Stack stack = (Stack) o; return GeneralUtils.equals(id, stack.id) && GeneralUtils.equals(title, stack.title) && GeneralUtils.equals(maxInLearning, stack.maxInLearning) && GeneralUtils.equals(countCards, stack.countCards) && GeneralUtils.equals(countInLearning, stack.countInLearning) && GeneralUtils.equals(language, stack.language) && GeneralUtils.equals(color, stack.color); } @Override public int hashCode() { return GeneralUtils.hash(id, title, maxInLearning, countCards, countInLearning, language, color); } }
gpl-2.0
BIORIMP/biorimp
BIO-RIMP/test_data/code/xerces/src/org/apache/xerces/impl/dv/InvalidDatatypeValueException.java
1359
/* * Copyright 2001, 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.dv; /** * Datatype exception for invalid values. * * @xerces.internal * * @author Sandy Gao, IBM * * @version $Id: InvalidDatatypeValueException.java,v 1.6 2004/10/06 14:56:50 mrglavas Exp $ */ public class InvalidDatatypeValueException extends DatatypeException { /** Serialization version. */ static final long serialVersionUID = -5523739426958236125L; /** * Create a new datatype exception by providing an error code and a list * of error message substitution arguments. * * @param key error code * @param args error arguments */ public InvalidDatatypeValueException(String key, Object[] args) { super(key, args); } }
gpl-2.0
Karniyarik/karniyarik
karniyarik-citydeal/src/main/java/com/karniyarik/citydeal/CityDealProvider.java
8798
package com.karniyarik.citydeal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.lang.StringUtils; import com.karniyarik.crawler.util.URLAnalyzer; import com.karniyarik.recognizer.ext.CitiesInTurkeyRegistry; import edu.emory.mathcs.backport.java.util.Collections; public class CityDealProvider { private static CityDealProvider instance = null; private List<City> cities = new ArrayList<City>(); private Map<String, List<CityDeal>> cityDealMap = new HashMap<String, List<CityDeal>>(); private List<CityDeal> allDeals = new ArrayList<CityDeal>(); private List<City> activeCities = new ArrayList<City>(); private Map<String, City> cityMap = new HashMap<String, City>(); private Map<Integer, CityDeal> cityDealIDMap = new HashMap<Integer, CityDeal>(); private FirsatClubDataFetcher dataFetcher = null; private final ReadWriteLock lock; private CityDealProvider() { lock = new ReentrantReadWriteLock(); loadCities(); loadFromPersistentStorage(); } private void loadCities() { List<String> cityList = CitiesInTurkeyRegistry.getInstance().getCities(); for(String cityStr: cityList) { City city = new City(); city.setName(cityStr); cities.add(city); cityMap.put(city.getValue(), city); } } private void loadFromPersistentStorage() { CityDealList readDeals = new CityDealIO().readDeals(); if(readDeals == null) { //wait the scheduled update operation //update(); } else { contructLists(readDeals.getCityDeals(), false); } } public static CityDealProvider getInstance() { if (instance == null) { instance = new CityDealProvider(); } return instance; } public List<CityDeal> getAllDeals() { return allDeals; } public List<City> getCities() { lock.readLock().lock(); List<City> cities = this.cities; lock.readLock().unlock(); return cities; } public City getCity(String value) { lock.readLock().lock(); City city = cityMap.get(value); lock.readLock().unlock(); return city; } public List<CityDeal> getDealList(String cityValue) { lock.readLock().lock(); List<CityDeal> list = cityDealMap.get(cityValue); if (list == null) { list = new ArrayList<CityDeal>(); } List<CityDeal> result = new ArrayList<CityDeal>(); Date curDate = new Date(); for(CityDeal deal: list) { if(deal.getEndDate().getTime() >= curDate.getTime()) { result.add(deal); } } lock.readLock().unlock(); return result; } public List<CityDeal> getExpiredDealList(String cityValue) { lock.readLock().lock(); List<CityDeal> list = cityDealMap.get(cityValue); if (list == null) { list = new ArrayList<CityDeal>(); } List<CityDeal> result = new ArrayList<CityDeal>(); Date curDate = new Date(); for(CityDeal deal: list) { if(deal.getEndDate().getTime() < curDate.getTime()) { result.add(deal); } } lock.readLock().unlock(); return result; } public List<City> getActiveCities() { lock.readLock().lock(); List<City> activeCities = this.activeCities; lock.readLock().unlock(); return activeCities; } public CityDeal getDeal(int id) { lock.readLock().lock(); CityDeal cityDeal = cityDealIDMap.get(id); lock.readLock().unlock(); return cityDeal; } private void contructLists(List<CityDeal> deals, boolean setDealParameters) { lock.writeLock().lock(); try{ if (deals != null && deals.size() > 0) { Date curDate = new Date(); long threshold = 1000*60*60*24; List<CityDeal> newAllDeals = new ArrayList<CityDeal>(); for(CityDeal deal: allDeals) { Date date = deal.getEndDate(); if(curDate.getTime() - date.getTime() < threshold) { newAllDeals.add(deal); } else { cityDealIDMap.remove(deal.getId()); } } //cities.clear(); //cityMap.clear(); allDeals.clear(); cityDealIDMap.clear(); activeCities.clear(); cityDealMap.clear(); // for(City city: cities) // { // cityMap.put(city.getValue(), city); // } insertDeals(newAllDeals, false); insertDeals(deals, setDealParameters); for (City city : cities) { List<CityDeal> list = cityDealMap.get(city.getValue()); if (list != null) { Collections.sort(list, new CityDealEndTimeComparator()); city.setDealCount(list.size()); activeCities.add(city); } else { city.setDealCount(0); } } Collections.sort(activeCities, new CityDealCountComparator()); Collections.sort(cities, new CityNameComparator()); } } finally { lock.writeLock().unlock(); } } private void insertDeals(List<CityDeal> deals, boolean setDealParameters) { for (CityDeal deal : deals) { List<CityDeal> cityDeals = checkCityIfNotExistsCreate(deal); if(setDealParameters){ deal.setId((deal.getCity() +deal.getDescription().toString()).hashCode()); String url = deal.getProductURL(); deal.setProductURL(processURL(url)); String imgUrl = deal.getImage(); deal.setImage(processImgURL(imgUrl)); double percentage = 0; if (deal.getPrice() != null || deal.getPrice() != 0) { percentage = 100 - (deal.getDiscountPrice() / deal.getPrice() * 100d); } deal.setDiscountPercentage(percentage); } deal.setPaid(isPaid(deal.getProductURL())); CityDeal oldCityDeal = cityDealIDMap.get(deal.getId()); if(deal.getSource().equalsIgnoreCase("limango")) {} //if not inserted before else //if(oldCityDeal == null || deal.getEndDate().getTime() > oldCityDeal.getEndDate().getTime()) { if(oldCityDeal != null) { cityDeals.remove(oldCityDeal); allDeals.remove(oldCityDeal); } cityDeals.add(deal); allDeals.add(deal); cityDealIDMap.put(deal.getId(), deal); } } } private List<CityDeal> checkCityIfNotExistsCreate(CityDeal deal) { String recognizedCity = CitiesInTurkeyRegistry.getInstance().getCity(deal.getCity()); if(StringUtils.isBlank(recognizedCity)) { recognizedCity = deal.getCity(); } List<CityDeal> cityDeals = cityDealMap.get(City.getValue(recognizedCity)); if (cityDeals == null) { cityDeals = new ArrayList<CityDeal>(); City city = cityMap.get(City.getValue(deal.getCity())); if(city == null) { city = new City(); city.setName(deal.getCity()); cityMap.put(city.getValue(), city); cities.add(city); } cityDealMap.put(city.getValue(), cityDeals); } return cityDeals; } private String processURL(String url) { url = url.replaceFirst("aff_id=(\\d+)", "aff_id=239"); url = url.replaceFirst("source=(\\w+)", "source=web"); return url; } private boolean isPaid(String url) { Map<String, String> queryParameters = new URLAnalyzer().getQueryParameters(url); String offerid = queryParameters.get("offer_id"); if(StringUtils.isNotBlank(offerid)) { int offidInt = Integer.parseInt(offerid); if(offidInt > 0) { return true; } } return false; } private String processImgURL(String url) { url = url.replaceFirst("w=(\\d+)", "w=180"); url = url.replaceFirst("h=(\\d+)", "h=140"); return url; } public void update() { try { // String[] ignored = new String[]{"sehirfirsati", "aktifkampanya", "firmanya", "grupca", "markapon", "piriveta", "grupanya"}; // List<String> ignoredSources = Arrays.asList(ignored); // // dataFetcher = new FirsatClubDataFetcher(ignoredSources); CityDealXMLCollector xmlFetcher = new CityDealXMLCollector(); List<CityDeal> xmlDeals = xmlFetcher.getDeals(); //List<CityDeal> crawledDeals = dataFetcher.fetchData(); //xmlDeals.addAll(crawledDeals); contructLists(xmlDeals, true); CityDealList storage = new CityDealList(); storage.setCities(cities); storage.setCityDeals(allDeals); new CityDealIO().writeDeals(storage); } catch (Exception e) { } } public static void main(String[] args) { CityDealProvider.getInstance().getCities(); CityDealProvider.getInstance().update(); List<CityDeal> dealList = CityDealProvider.getInstance().getDealList("ankara"); int a = 8; } }
gpl-2.0
mikrosimage/jebu-core
src/main/java/ebu/metadata_schema/ebucore_2015/ElementType.java
1081
package ebu.metadata_schema.ebucore_2015; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java pour elementType complex type. * * <p>Le fragment de schéma suivant indique le contenu attendu figurant dans cette classe. * * <pre> * &lt;complexType name="elementType"> * &lt;simpleContent> * &lt;extension base="&lt;http://purl.org/dc/elements/1.1/>elementType"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "elementType") @XmlSeeAlso({ VersionType.class, CompoundNameType.class, OrganisationDepartmentType.class, ebu.metadata_schema.ebucore_2015.ContactDetailsType.StageName.class, Comment.class }) public class ElementType extends org.purl.dc.elements._1.ElementType implements Serializable { private final static long serialVersionUID = -1L; }
gpl-2.0
a97381416/jack.github.io
my_project/springboot/springboot-swagger-learn/src/main/java/com/example/demo/Swagger2.java
1379
package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Created by Jack-Wang on 2017/11/7. */ @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.web")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful APIs") .description("更多Spring Boot相关文章请关注:http://blog.didispace.com/") .termsOfServiceUrl("http://blog.didispace.com/") .contact("程序员") .version("1.0") .build(); } }
gpl-2.0
GaloisInc/KOA
infrastructure/source/WebVotingSystem/src/ie/ucd/srg/koa/koaschema/EJSFinderKieslijstenBean.java
382
package ie.ucd.srg.koa.koaschema; import ie.ucd.srg.ejs.persistence.EJSFinder; /** * EJSFinderKieslijstenBean * @generated */ public interface EJSFinderKieslijstenBean { /** * findKieslijstenByFk_kkr_1 * @generated */ public EJSFinder findKieslijstenByFk_kkr_1(ie.ucd.srg.koa.koaschema.KieskringenKey inKey) throws javax.ejb.FinderException, java.rmi.RemoteException; }
gpl-2.0
dmbel/Enjoy
app/src/main/java/ru/enjoy/server/data/NjoyCreateProductAndCategoryPointer.java
189
package ru.enjoy.server.data; public class NjoyCreateProductAndCategoryPointer { transient public int id; transient public int categoryId; public int productId; public String rating; }
gpl-2.0